@gara31/void-baileys 7.0.0-rc.14

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