@itsliaaa/baileys 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1078 -0
  3. package/WAProto/index.js +100441 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/index.js +144 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +29 -0
  8. package/lib/Signal/Group/group_cipher.js +81 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +17 -0
  11. package/lib/Signal/Group/sender-chain-key.js +25 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  13. package/lib/Signal/Group/sender-key-message.js +65 -0
  14. package/lib/Signal/Group/sender-key-name.js +47 -0
  15. package/lib/Signal/Group/sender-key-record.js +40 -0
  16. package/lib/Signal/Group/sender-key-state.js +83 -0
  17. package/lib/Signal/Group/sender-message-key.js +25 -0
  18. package/lib/Signal/libsignal.js +402 -0
  19. package/lib/Signal/lid-mapping.js +270 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +53 -0
  23. package/lib/Socket/business.js +378 -0
  24. package/lib/Socket/chats.js +1048 -0
  25. package/lib/Socket/communities.js +430 -0
  26. package/lib/Socket/groups.js +328 -0
  27. package/lib/Socket/index.js +11 -0
  28. package/lib/Socket/messages-recv.js +1442 -0
  29. package/lib/Socket/messages-send.js +1153 -0
  30. package/lib/Socket/mex.js +41 -0
  31. package/lib/Socket/newsletter.js +227 -0
  32. package/lib/Socket/socket.js +936 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +421 -0
  35. package/lib/Store/make-ordered-dictionary.js +78 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +17 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/Signal.js +1 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +12 -0
  52. package/lib/Types/USync.js +1 -0
  53. package/lib/Types/index.js +25 -0
  54. package/lib/Utils/auth-utils.js +289 -0
  55. package/lib/Utils/browser-utils.js +28 -0
  56. package/lib/Utils/business.js +230 -0
  57. package/lib/Utils/chat-utils.js +811 -0
  58. package/lib/Utils/crypto.js +117 -0
  59. package/lib/Utils/decode-wa-message.js +282 -0
  60. package/lib/Utils/event-buffer.js +573 -0
  61. package/lib/Utils/generics.js +385 -0
  62. package/lib/Utils/history.js +130 -0
  63. package/lib/Utils/identity-change-handler.js +48 -0
  64. package/lib/Utils/index.js +19 -0
  65. package/lib/Utils/link-preview.js +84 -0
  66. package/lib/Utils/logger.js +2 -0
  67. package/lib/Utils/lt-hash.js +7 -0
  68. package/lib/Utils/make-mutex.js +32 -0
  69. package/lib/Utils/message-retry-manager.js +224 -0
  70. package/lib/Utils/messages-media.js +789 -0
  71. package/lib/Utils/messages.js +1832 -0
  72. package/lib/Utils/noise-handler.js +200 -0
  73. package/lib/Utils/pre-key-manager.js +105 -0
  74. package/lib/Utils/process-message.js +527 -0
  75. package/lib/Utils/reporting-utils.js +257 -0
  76. package/lib/Utils/signal.js +158 -0
  77. package/lib/Utils/sync-action-utils.js +47 -0
  78. package/lib/Utils/tc-token-utils.js +17 -0
  79. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  80. package/lib/Utils/validate-connection.js +206 -0
  81. package/lib/WABinary/constants.js +1300 -0
  82. package/lib/WABinary/decode.js +261 -0
  83. package/lib/WABinary/encode.js +219 -0
  84. package/lib/WABinary/generic-utils.js +197 -0
  85. package/lib/WABinary/index.js +5 -0
  86. package/lib/WABinary/jid-utils.js +95 -0
  87. package/lib/WABinary/types.js +1 -0
  88. package/lib/WAM/BinaryInfo.js +9 -0
  89. package/lib/WAM/constants.js +22852 -0
  90. package/lib/WAM/encode.js +149 -0
  91. package/lib/WAM/index.js +3 -0
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  95. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  96. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  97. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  98. package/lib/WAUSync/Protocols/index.js +4 -0
  99. package/lib/WAUSync/USyncQuery.js +93 -0
  100. package/lib/WAUSync/USyncUser.js +22 -0
  101. package/lib/WAUSync/index.js +3 -0
  102. package/lib/index.js +11 -0
  103. package/package.json +72 -0
@@ -0,0 +1,527 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { WAMessageStubType } from '../Types/index.js';
3
+ import { getContentType, normalizeMessageContent } from '../Utils/messages.js';
4
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, isLidUser, jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
5
+ import { aesDecryptGCM, hmacSign } from './crypto.js';
6
+ import { getKeyAuthor, toNumber } from './generics.js';
7
+ import { downloadAndProcessHistorySyncNotification } from './history.js';
8
+ const REAL_MSG_STUB_TYPES = new Set([
9
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
10
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
11
+ WAMessageStubType.CALL_MISSED_VIDEO,
12
+ WAMessageStubType.CALL_MISSED_VOICE
13
+ ]);
14
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
15
+ /** Cleans a received message to further processing */
16
+ export const cleanMessage = (message, meId, meLid) => {
17
+ // ensure remoteJid and participant doesn't have device or agent in it
18
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
19
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
20
+ }
21
+ else {
22
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
23
+ }
24
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
25
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid');
26
+ }
27
+ else {
28
+ message.key.participant = jidNormalizedUser(message.key.participant);
29
+ }
30
+ const content = normalizeMessageContent(message.message);
31
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
32
+ if (content?.reactionMessage) {
33
+ normaliseKey(content.reactionMessage.key);
34
+ }
35
+ if (content?.pollUpdateMessage) {
36
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
37
+ }
38
+ function normaliseKey(msgKey) {
39
+ // if the reaction is from another user
40
+ // we've to correctly map the key to this user's perspective
41
+ if (!message.key.fromMe) {
42
+ // if the sender believed the message being reacted to is not from them
43
+ // we've to correct the key to be from them, or some other participant
44
+ msgKey.fromMe = !msgKey.fromMe
45
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
46
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
47
+ : // if the message being reacted to, was from them
48
+ // fromMe automatically becomes false
49
+ false;
50
+ // set the remoteJid to being the same as the chat the message came from
51
+ // TODO: investigate inconsistencies
52
+ msgKey.remoteJid = message.key.remoteJid;
53
+ // set participant of the message
54
+ msgKey.participant = msgKey.participant || message.key.participant;
55
+ }
56
+ }
57
+ };
58
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
59
+ export const isRealMessage = (message) => {
60
+ const normalizedContent = normalizeMessageContent(message.message);
61
+ const hasSomeContent = !!getContentType(normalizedContent);
62
+ return ((!!normalizedContent ||
63
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
64
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
65
+ hasSomeContent &&
66
+ !normalizedContent?.protocolMessage &&
67
+ !normalizedContent?.reactionMessage &&
68
+ !normalizedContent?.pollUpdateMessage);
69
+ };
70
+ export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
71
+ /**
72
+ * Get the ID of the chat from the given key.
73
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
74
+ */
75
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
76
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
77
+ return participant;
78
+ }
79
+ return remoteJid;
80
+ };
81
+ /**
82
+ * Decrypt a poll vote
83
+ * @param vote encrypted vote
84
+ * @param ctx additional info about the poll required for decryption
85
+ * @returns list of SHA256 options
86
+ */
87
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
88
+ const sign = Buffer.concat([
89
+ toBinary(pollMsgId),
90
+ toBinary(pollCreatorJid),
91
+ toBinary(voterJid),
92
+ toBinary('Poll Vote'),
93
+ new Uint8Array([1])
94
+ ]);
95
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
96
+ const decKey = hmacSign(sign, key0, 'sha256');
97
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
98
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
99
+ return proto.Message.PollVoteMessage.decode(decrypted);
100
+ function toBinary(txt) {
101
+ return Buffer.from(txt);
102
+ }
103
+ }
104
+ /**
105
+ * Decrypt an event response
106
+ * @param response encrypted event response
107
+ * @param ctx additional info about the event required for decryption
108
+ * @returns event response message
109
+ */
110
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
111
+ const sign = Buffer.concat([
112
+ toBinary(eventMsgId),
113
+ toBinary(eventCreatorJid),
114
+ toBinary(responderJid),
115
+ toBinary('Event Response'),
116
+ new Uint8Array([1])
117
+ ]);
118
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256');
119
+ const decKey = hmacSign(sign, key0, 'sha256');
120
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
121
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
122
+ return proto.Message.EventResponseMessage.decode(decrypted);
123
+ function toBinary(txt) {
124
+ return Buffer.from(txt);
125
+ }
126
+ }
127
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
128
+ const meId = creds.me.id;
129
+ const { accountSettings } = creds;
130
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
131
+ const isRealMsg = isRealMessage(message);
132
+ if (isRealMsg) {
133
+ chat.messages = [{ message }];
134
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
135
+ // only increment unread count if not CIPHERTEXT and from another person
136
+ if (shouldIncrementChatUnread(message)) {
137
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
138
+ }
139
+ }
140
+ const content = normalizeMessageContent(message.message);
141
+ // unarchive chat if it's a real message, or someone reacted to our message
142
+ // and we've the unarchive chats setting on
143
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
144
+ chat.archived = false;
145
+ chat.readOnly = false;
146
+ }
147
+ const protocolMsg = content?.protocolMessage;
148
+ if (protocolMsg) {
149
+ switch (protocolMsg.type) {
150
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
151
+ const histNotification = protocolMsg.historySyncNotification;
152
+ const process = shouldProcessHistoryMsg;
153
+ const isLatest = !creds.processedHistoryMessages?.length;
154
+ logger?.info({
155
+ histNotification,
156
+ process,
157
+ id: message.key.id,
158
+ isLatest
159
+ }, 'got history notification');
160
+ if (process) {
161
+ // TODO: investigate
162
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
163
+ ev.emit('creds.update', {
164
+ processedHistoryMessages: [
165
+ ...(creds.processedHistoryMessages || []),
166
+ { key: message.key, messageTimestamp: message.messageTimestamp }
167
+ ]
168
+ });
169
+ }
170
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger);
171
+ if (data.lidPnMappings?.length) {
172
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync');
173
+ await signalRepository.lidMapping
174
+ .storeLIDPNMappings(data.lidPnMappings)
175
+ .catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'));
176
+ }
177
+ ev.emit('messaging-history.set', {
178
+ ...data,
179
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
180
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
181
+ });
182
+ }
183
+ break;
184
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
185
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
186
+ if (keys?.length) {
187
+ let newAppStateSyncKeyId = '';
188
+ await keyStore.transaction(async () => {
189
+ const newKeys = [];
190
+ for (const { keyData, keyId } of keys) {
191
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
192
+ newKeys.push(strKeyId);
193
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
194
+ newAppStateSyncKeyId = strKeyId;
195
+ }
196
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
197
+ }, meId);
198
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
199
+ }
200
+ else {
201
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
202
+ }
203
+ break;
204
+ case proto.Message.ProtocolMessage.Type.REVOKE:
205
+ ev.emit('messages.update', [
206
+ {
207
+ key: {
208
+ ...message.key,
209
+ id: protocolMsg.key.id
210
+ },
211
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
212
+ }
213
+ ]);
214
+ break;
215
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
216
+ Object.assign(chat, {
217
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
218
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
219
+ });
220
+ break;
221
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
222
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
223
+ if (response) {
224
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
225
+ const peerDataOperationResult = response.peerDataOperationResult || [];
226
+ for (const result of peerDataOperationResult) {
227
+ const retryResponse = result?.placeholderMessageResendResponse;
228
+ //eslint-disable-next-line max-depth
229
+ if (!retryResponse?.webMessageInfoBytes) {
230
+ continue;
231
+ }
232
+ //eslint-disable-next-line max-depth
233
+ try {
234
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
235
+ const msgId = webMessageInfo.key?.id;
236
+ // Retrieve cached original message data (preserves LID details,
237
+ // timestamps, etc. that the phone may omit in its PDO response)
238
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined;
239
+ //eslint-disable-next-line max-depth
240
+ if (msgId) {
241
+ await placeholderResendCache?.del(msgId);
242
+ }
243
+ let finalMsg;
244
+ //eslint-disable-next-line max-depth
245
+ if (cachedData && typeof cachedData === 'object') {
246
+ // Apply decoded message content onto cached metadata (preserves LID etc.)
247
+ cachedData.message = webMessageInfo.message;
248
+ //eslint-disable-next-line max-depth
249
+ if (webMessageInfo.messageTimestamp) {
250
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
251
+ }
252
+ finalMsg = cachedData;
253
+ }
254
+ else {
255
+ finalMsg = webMessageInfo;
256
+ }
257
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend');
258
+ ev.emit('messages.upsert', {
259
+ messages: [finalMsg],
260
+ type: 'notify',
261
+ requestId: response.stanzaId
262
+ });
263
+ }
264
+ catch (err) {
265
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response');
266
+ }
267
+ }
268
+ }
269
+ break;
270
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
271
+ ev.emit('messages.update', [
272
+ {
273
+ // flip the sender / fromMe properties because they're in the perspective of the sender
274
+ key: { ...message.key, id: protocolMsg.key?.id },
275
+ update: {
276
+ message: {
277
+ editedMessage: {
278
+ message: protocolMsg.editedMessage
279
+ }
280
+ },
281
+ messageTimestamp: protocolMsg.timestampMs
282
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
283
+ : message.messageTimestamp
284
+ }
285
+ }
286
+ ]);
287
+ break;
288
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
289
+ const labelAssociationMsg = protocolMsg.memberLabel;
290
+ if (labelAssociationMsg?.label) {
291
+ ev.emit('group.member-tag.update', {
292
+ groupId: chat.id,
293
+ label: labelAssociationMsg.label,
294
+ participant: message.key.participant,
295
+ participantAlt: message.key.participantAlt,
296
+ messageTimestamp: Number(message.messageTimestamp)
297
+ });
298
+ }
299
+ break;
300
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
301
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
302
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
303
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
304
+ const pairs = [];
305
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
306
+ const lid = latestLid || assignedLid;
307
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
308
+ }
309
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
310
+ if (pairs.length) {
311
+ for (const { pn, lid } of pairs) {
312
+ await signalRepository.migrateSession(pn, lid);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ else if (content?.reactionMessage) {
318
+ const reaction = {
319
+ ...content.reactionMessage,
320
+ key: message.key
321
+ };
322
+ ev.emit('messages.reaction', [
323
+ {
324
+ reaction,
325
+ key: content.reactionMessage?.key
326
+ }
327
+ ]);
328
+ }
329
+ else if (content?.encEventResponseMessage) {
330
+ const encEventResponse = content.encEventResponseMessage;
331
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
332
+ // we need to fetch the event creation message to get the event enc key
333
+ const eventMsg = await getMessage(creationMsgKey);
334
+ if (eventMsg) {
335
+ try {
336
+ const meIdNormalised = jidNormalizedUser(meId);
337
+ // all jids need to be PN
338
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid;
339
+ const eventCreatorPn = isLidUser(eventCreatorKey)
340
+ ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
341
+ : eventCreatorKey;
342
+ const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised);
343
+ const responderJid = getKeyAuthor(message.key, meIdNormalised);
344
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
345
+ if (!eventEncKey) {
346
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption');
347
+ }
348
+ else {
349
+ const responseMsg = decryptEventResponse(encEventResponse, {
350
+ eventEncKey,
351
+ eventCreatorJid,
352
+ eventMsgId: creationMsgKey.id,
353
+ responderJid
354
+ });
355
+ const eventResponse = {
356
+ eventResponseMessageKey: message.key,
357
+ senderTimestampMs: responseMsg.timestampMs,
358
+ response: responseMsg
359
+ };
360
+ ev.emit('messages.update', [
361
+ {
362
+ key: creationMsgKey,
363
+ update: {
364
+ eventResponses: [eventResponse]
365
+ }
366
+ }
367
+ ]);
368
+ }
369
+ }
370
+ catch (err) {
371
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response');
372
+ }
373
+ }
374
+ else {
375
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response');
376
+ }
377
+ }
378
+ else if (message.messageStubType) {
379
+ const jid = message.key?.remoteJid;
380
+ //let actor = whatsappID (message.participant)
381
+ let participants;
382
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
383
+ id: jid,
384
+ author: message.key.participant,
385
+ authorPn: message.key.participantAlt,
386
+ participants,
387
+ action
388
+ });
389
+ const emitGroupUpdate = (update) => {
390
+ ev.emit('groups.update', [
391
+ { id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
392
+ ]);
393
+ };
394
+ const emitGroupRequestJoin = (participant, action, method) => {
395
+ ev.emit('group.join-request', {
396
+ id: jid,
397
+ author: message.key.participant,
398
+ authorPn: message.key.participantAlt,
399
+ participant: participant.lid,
400
+ participantPn: participant.pn,
401
+ action,
402
+ method: method
403
+ });
404
+ };
405
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)); // ADD SUPPORT FOR LID
406
+ switch (message.messageStubType) {
407
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
408
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
409
+ emitParticipantsUpdate('modify');
410
+ break;
411
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
412
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
413
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
414
+ emitParticipantsUpdate('remove');
415
+ // mark the chat read only if you left the group
416
+ if (participantsIncludesMe()) {
417
+ chat.readOnly = true;
418
+ }
419
+ break;
420
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
421
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
422
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
423
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
424
+ if (participantsIncludesMe()) {
425
+ chat.readOnly = false;
426
+ }
427
+ emitParticipantsUpdate('add');
428
+ break;
429
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
430
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
431
+ emitParticipantsUpdate('demote');
432
+ break;
433
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
434
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
435
+ emitParticipantsUpdate('promote');
436
+ break;
437
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
438
+ const announceValue = message.messageStubParameters?.[0];
439
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
440
+ break;
441
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
442
+ const restrictValue = message.messageStubParameters?.[0];
443
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
444
+ break;
445
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
446
+ const name = message.messageStubParameters?.[0];
447
+ chat.name = name;
448
+ emitGroupUpdate({ subject: name });
449
+ break;
450
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
451
+ const description = message.messageStubParameters?.[0];
452
+ chat.description = description;
453
+ emitGroupUpdate({ desc: description });
454
+ break;
455
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
456
+ const code = message.messageStubParameters?.[0];
457
+ emitGroupUpdate({ inviteCode: code });
458
+ break;
459
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
460
+ const memberAddValue = message.messageStubParameters?.[0];
461
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
462
+ break;
463
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
464
+ const approvalMode = message.messageStubParameters?.[0];
465
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
466
+ break;
467
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
468
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
469
+ const action = message.messageStubParameters?.[1];
470
+ const method = message.messageStubParameters?.[2];
471
+ emitGroupRequestJoin(participant, action, method);
472
+ break;
473
+ }
474
+ } /* else if(content?.pollUpdateMessage) {
475
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
476
+ // we need to fetch the poll creation message to get the poll enc key
477
+ // TODO: make standalone, remove getMessage reference
478
+ // TODO: Remove entirely
479
+ const pollMsg = await getMessage(creationMsgKey)
480
+ if(pollMsg) {
481
+ const meIdNormalised = jidNormalizedUser(meId)
482
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
483
+ const voterJid = getKeyAuthor(message.key, meIdNormalised)
484
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
485
+
486
+ try {
487
+ const voteMsg = decryptPollVote(
488
+ content.pollUpdateMessage.vote!,
489
+ {
490
+ pollEncKey,
491
+ pollCreatorJid,
492
+ pollMsgId: creationMsgKey.id!,
493
+ voterJid,
494
+ }
495
+ )
496
+ ev.emit('messages.update', [
497
+ {
498
+ key: creationMsgKey,
499
+ update: {
500
+ pollUpdates: [
501
+ {
502
+ pollUpdateMessageKey: message.key,
503
+ vote: voteMsg,
504
+ senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
505
+ }
506
+ ]
507
+ }
508
+ }
509
+ ])
510
+ } catch(err) {
511
+ logger?.warn(
512
+ { err, creationMsgKey },
513
+ 'failed to decrypt poll vote'
514
+ )
515
+ }
516
+ } else {
517
+ logger?.warn(
518
+ { creationMsgKey },
519
+ 'poll creation message not found, cannot decrypt update'
520
+ )
521
+ }
522
+ } */
523
+ if (Object.keys(chat).length > 1) {
524
+ ev.emit('chats.update', [chat]);
525
+ }
526
+ };
527
+ export default processMessage;