dibosockets 1.0.2 → 1.0.3

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 (40) hide show
  1. package/WAProto/WAProto.proto +4775 -5619
  2. package/lib/Defaults/baileys-version.json +3 -3
  3. package/lib/Defaults/index.js +106 -122
  4. package/lib/Socket/RHandler.js +530 -448
  5. package/lib/Socket/business.js +260 -266
  6. package/lib/Socket/chats.js +908 -1137
  7. package/lib/Socket/index.js +10 -43
  8. package/lib/Socket/messages-recv.js +1054 -1065
  9. package/lib/Socket/messages-send.js +903 -881
  10. package/lib/Socket/newsletter.js +303 -286
  11. package/lib/Socket/socket.js +654 -666
  12. package/lib/Store/make-in-memory-store.js +439 -439
  13. package/lib/Types/Newsletter.js +38 -18
  14. package/lib/Utils/baileys-event-stream.js +63 -63
  15. package/lib/Utils/event-buffer.js +518 -518
  16. package/lib/Utils/generics.js +428 -432
  17. package/lib/Utils/index.js +36 -36
  18. package/lib/Utils/messages-media.js +887 -926
  19. package/lib/Utils/messages.js +1030 -1105
  20. package/lib/Utils/process-message.js +385 -404
  21. package/lib/Utils/use-multi-file-auth-state.js +125 -122
  22. package/lib/Utils/validate-connection.js +173 -229
  23. package/lib/WABinary/jid-utils.js +83 -85
  24. package/lib/index.js +86 -74
  25. package/package.json +2 -2
  26. package/lib/Api/Internet/growagarden.js +0 -28
  27. package/lib/Api/creator.json +0 -13
  28. package/lib/Api/downloader/tiktokdownload.js +0 -132
  29. package/lib/Api/index.js +0 -38
  30. package/lib/Api/nsfw/loli.js +0 -79
  31. package/lib/Api/stalker/githubstalk.js +0 -46
  32. package/lib/Api/stalker/stalkroblox.js +0 -94
  33. package/lib/Api/stalker/tiktokstalk.js +0 -68
  34. package/lib/Api/tools/ssweb.js +0 -38
  35. package/lib/Defaults/phonenumber_mcc.json +0 -223
  36. package/lib/Socket/communities.js +0 -441
  37. package/lib/Utils/async-iterable.js +0 -41
  38. package/lib/Utils/browser-utils.js +0 -35
  39. package/lib/Utils/message-retry-manager.js +0 -128
  40. package/lib/Utils/resolveJid.js +0 -52
@@ -1,404 +1,385 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
- exports.decryptPollVote = decryptPollVote;
5
- const WAProto_1 = require("../../WAProto");
6
- const Types_1 = require("../Types");
7
- const messages_1 = require("../Utils/messages");
8
- const WABinary_1 = require("../WABinary");
9
- const crypto_1 = require("./crypto");
10
- const generics_1 = require("./generics");
11
- const history_1 = require("./history");
12
- const REAL_MSG_STUB_TYPES = new Set([
13
- Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
- Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
- Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
16
- Types_1.WAMessageStubType.CALL_MISSED_VOICE
17
- ]);
18
- const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
- Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
- ]);
21
- /** Cleans a received message to further processing */
22
- const cleanMessage = (message, meId) => {
23
- // ensure remoteJid and participant doesn't have device or agent in it
24
- // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
- try {
26
- message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
27
- }
28
- catch (_e) {
29
- // if normalization fails, retain original remoteJid
30
- }
31
- if (message.key.participant) {
32
- try {
33
- message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
34
- }
35
- catch (_e) {
36
- // ignore if can't normalize participant
37
- }
38
- }
39
- const content = (0, messages_1.normalizeMessageContent)(message.message);
40
- // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
41
- if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
42
- normaliseKey(content.reactionMessage.key);
43
- }
44
- if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
45
- normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
46
- }
47
- function normaliseKey(msgKey) {
48
- // if the reaction is from another user
49
- // we've to correctly map the key to this user's perspective
50
- if (!message.key.fromMe) {
51
- // if the sender believed the message being reacted to is not from them
52
- // we've to correct the key to be from them, or some other participant
53
- msgKey.fromMe = !msgKey.fromMe
54
- ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
55
- // if the message being reacted to, was from them
56
- // fromMe automatically becomes false
57
- : false;
58
- // set the remoteJid to being the same as the chat the message came from
59
- msgKey.remoteJid = message.key.remoteJid;
60
- // set participant of the message
61
- msgKey.participant = msgKey.participant || message.key.participant;
62
- }
63
- }
64
- };
65
- exports.cleanMessage = cleanMessage;
66
- const isRealMessage = (message, meId) => {
67
- var _a;
68
- const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
69
- const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
70
- return (!!normalizedContent
71
- || REAL_MSG_STUB_TYPES.has(message.messageStubType)
72
- || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
73
- && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
74
- && hasSomeContent
75
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
76
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
77
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
78
- };
79
- exports.isRealMessage = isRealMessage;
80
- const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
81
- exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
82
- /**
83
- * Get the ID of the chat from the given key.
84
- * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
85
- */
86
- const getChatId = ({ remoteJid, participant, fromMe }) => {
87
- if ((0, WABinary_1.isJidBroadcast)(remoteJid)
88
- && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
89
- && !fromMe) {
90
- return participant;
91
- }
92
- return remoteJid;
93
- };
94
- exports.getChatId = getChatId;
95
- /**
96
- * Decrypt a poll vote
97
- * @param vote encrypted vote
98
- * @param ctx additional info about the poll required for decryption
99
- * @returns list of SHA256 options
100
- */
101
- function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
102
- const sign = Buffer.concat([
103
- toBinary(pollMsgId),
104
- toBinary(pollCreatorJid),
105
- toBinary(voterJid),
106
- toBinary('Poll Vote'),
107
- new Uint8Array([1])
108
- ]);
109
- const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
110
- const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
111
- const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
112
- const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
113
- return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
114
- function toBinary(txt) {
115
- return Buffer.from(txt);
116
- }
117
- }
118
- const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
119
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
120
- const meId = creds.me.id;
121
- const { accountSettings } = creds;
122
- const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
123
- const isRealMsg = (0, exports.isRealMessage)(message, meId);
124
- if (isRealMsg) {
125
- chat.messages = [{ message }];
126
- chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
127
- // only increment unread count if not CIPHERTEXT and from another person
128
- if ((0, exports.shouldIncrementChatUnread)(message)) {
129
- chat.unreadCount = (chat.unreadCount || 0) + 1;
130
- }
131
- }
132
- const content = (0, messages_1.normalizeMessageContent)(message.message);
133
- const senderId = message.key.participant || message.key.remoteJid;
134
- if ((0, WABinary_1.isLidUser)(senderId)) {
135
- const jid = (0, WABinary_1.lidToJid)(senderId);
136
- if (message.key.participant) {
137
- message.key.participant = jid;
138
- }
139
- else {
140
- message.key.remoteJid = jid;
141
- }
142
- }
143
- const mJids = content && content.contextInfo && content.contextInfo.mentionedJid ? content.contextInfo.mentionedJid : [];
144
- for (let i = 0; i < mJids.length; i++) {
145
- if ((0, WABinary_1.isLidUser)(mJids[i])) {
146
- mJids[i] = (0, WABinary_1.lidToJid)(mJids[i]);
147
- }
148
- }
149
- if (content && content.contextInfo && content.contextInfo.participant && (0, WABinary_1.isLidUser)(content.contextInfo.participant)) {
150
- content.contextInfo.participant = (0, WABinary_1.lidToJid)(content.contextInfo.participant);
151
- }
152
- // unarchive chat if it's a real message, or someone reacted to our message
153
- // and we've the unarchive chats setting on
154
- if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
155
- && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
156
- chat.archived = false;
157
- chat.readOnly = false;
158
- }
159
- const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
160
- if (protocolMsg) {
161
- switch (protocolMsg.type) {
162
- case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
163
- const histNotification = protocolMsg.historySyncNotification;
164
- const process = shouldProcessHistoryMsg;
165
- const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
166
- logger === null || logger === void 0 ? void 0 : logger.info({
167
- histNotification,
168
- process,
169
- id: message.key.id,
170
- isLatest,
171
- }, 'got history notification');
172
- if (process) {
173
- if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
174
- ev.emit('creds.update', {
175
- processedHistoryMessages: [
176
- ...(creds.processedHistoryMessages || []),
177
- { key: message.key, messageTimestamp: message.messageTimestamp }
178
- ]
179
- });
180
- }
181
- const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
182
- ev.emit('messaging-history.set', {
183
- ...data,
184
- isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
185
- ? isLatest
186
- : undefined,
187
- peerDataRequestSessionId: histNotification.peerDataRequestSessionId
188
- });
189
- }
190
- break;
191
- case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
192
- const keys = protocolMsg.appStateSyncKeyShare.keys;
193
- if (keys === null || keys === void 0 ? void 0 : keys.length) {
194
- let newAppStateSyncKeyId = '';
195
- await keyStore.transaction(async () => {
196
- const newKeys = [];
197
- for (const { keyData, keyId } of keys) {
198
- const strKeyId = Buffer.from(keyId.keyId).toString('base64');
199
- newKeys.push(strKeyId);
200
- await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
201
- newAppStateSyncKeyId = strKeyId;
202
- }
203
- logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
204
- });
205
- ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
206
- }
207
- else {
208
- logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
209
- }
210
- break;
211
- case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
212
- ev.emit('messages.update', [
213
- {
214
- key: {
215
- ...message.key,
216
- id: protocolMsg.key.id
217
- },
218
- update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
219
- }
220
- ]);
221
- break;
222
- case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
223
- Object.assign(chat, {
224
- ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
225
- ephemeralExpiration: protocolMsg.ephemeralExpiration || null
226
- });
227
- break;
228
- case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
229
- const response = protocolMsg.peerDataOperationRequestResponseMessage;
230
- if (response) {
231
- placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
232
- // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
233
- const { peerDataOperationResult } = response;
234
- for (const result of peerDataOperationResult) {
235
- const { placeholderMessageResendResponse: retryResponse } = result;
236
- if (retryResponse) {
237
- const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
238
- // wait till another upsert event is available, don't want it to be part of the PDO response message
239
- setTimeout(() => {
240
- ev.emit('messages.upsert', {
241
- messages: [webMessageInfo],
242
- type: 'notify',
243
- requestId: response.stanzaId
244
- });
245
- }, 500);
246
- }
247
- }
248
- }
249
- case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
250
- ev.emit('messages.update', [
251
- {
252
- // flip the sender / fromMe properties because they're in the perspective of the sender
253
- key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
254
- update: {
255
- message: {
256
- editedMessage: {
257
- message: protocolMsg.editedMessage
258
- }
259
- },
260
- messageTimestamp: protocolMsg.timestampMs
261
- ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
262
- : message.messageTimestamp
263
- }
264
- }
265
- ]);
266
- break;
267
- }
268
- }
269
- else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
270
- const reaction = {
271
- ...content.reactionMessage,
272
- key: message.key,
273
- };
274
- ev.emit('messages.reaction', [{
275
- reaction,
276
- key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
277
- }]);
278
- }
279
- else if (message.messageStubType) {
280
- const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
281
- //let actor = whatsappID (message.participant)
282
- let participants;
283
- const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
284
- const emitGroupUpdate = (update) => {
285
- var _a;
286
- ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
287
- };
288
- const emitGroupRequestJoin = (participant, action, method) => {
289
- ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
290
- };
291
- const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
292
- switch (message.messageStubType) {
293
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
294
- participants = message.messageStubParameters || [];
295
- emitParticipantsUpdate('modify');
296
- break;
297
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
298
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
299
- participants = message.messageStubParameters || [];
300
- emitParticipantsUpdate('remove');
301
- // mark the chat read only if you left the group
302
- if (participantsIncludesMe()) {
303
- chat.readOnly = true;
304
- }
305
- break;
306
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
307
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
308
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
309
- participants = message.messageStubParameters || [];
310
- if (participantsIncludesMe()) {
311
- chat.readOnly = false;
312
- }
313
- emitParticipantsUpdate('add');
314
- break;
315
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
316
- participants = message.messageStubParameters || [];
317
- emitParticipantsUpdate('demote');
318
- break;
319
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
320
- participants = message.messageStubParameters || [];
321
- emitParticipantsUpdate('promote');
322
- break;
323
- case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
324
- const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
325
- emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
326
- break;
327
- case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
328
- const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
329
- emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
330
- break;
331
- case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
332
- const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
333
- chat.name = name;
334
- emitGroupUpdate({ subject: name });
335
- break;
336
- case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
337
- const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
338
- chat.description = description;
339
- emitGroupUpdate({ desc: description });
340
- break;
341
- case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
342
- const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
343
- emitGroupUpdate({ inviteCode: code });
344
- break;
345
- case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
346
- const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
347
- emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
348
- break;
349
- case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
350
- const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
351
- emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
352
- break;
353
- case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
354
- const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
355
- const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
356
- const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
357
- emitGroupRequestJoin(participant, action, method);
358
- break;
359
- }
360
- }
361
- else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
362
- const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
363
- // we need to fetch the poll creation message to get the poll enc key
364
- const pollMsg = await getMessage(creationMsgKey);
365
- if (pollMsg) {
366
- const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
367
- const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
368
- const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
369
- const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
370
- try {
371
- const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
372
- pollEncKey,
373
- pollCreatorJid,
374
- pollMsgId: creationMsgKey.id,
375
- voterJid,
376
- });
377
- ev.emit('messages.update', [
378
- {
379
- key: creationMsgKey,
380
- update: {
381
- pollUpdates: [
382
- {
383
- pollUpdateMessageKey: message.key,
384
- vote: voteMsg,
385
- senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
386
- }
387
- ]
388
- }
389
- }
390
- ]);
391
- }
392
- catch (err) {
393
- logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
394
- }
395
- }
396
- else {
397
- logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
398
- }
399
- }
400
- if (Object.keys(chat).length > 1) {
401
- ev.emit('chats.update', [chat]);
402
- }
403
- };
404
- exports.default = processMessage;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
+ exports.decryptPollVote = decryptPollVote;
5
+ const WAProto_1 = require("../../WAProto");
6
+ const Types_1 = require("../Types");
7
+ const messages_1 = require("../Utils/messages");
8
+ const WABinary_1 = require("../WABinary");
9
+ const crypto_1 = require("./crypto");
10
+ const generics_1 = require("./generics");
11
+ const history_1 = require("./history");
12
+ const REAL_MSG_STUB_TYPES = new Set([
13
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
16
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE
17
+ ]);
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
+ ]);
21
+ /** Cleans a received message to further processing */
22
+ const cleanMessage = (message, meId) => {
23
+ // ensure remoteJid and participant doesn't have device or agent in it
24
+ // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
+ try {
26
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
27
+ }
28
+ catch (_e) {
29
+ // if normalization fails, retain original remoteJid
30
+ }
31
+ if (message.key.participant) {
32
+ try {
33
+ message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
34
+ }
35
+ catch (_e) {
36
+ // ignore if can't normalize participant
37
+ }
38
+ }
39
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
40
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
41
+ if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
42
+ normaliseKey(content.reactionMessage.key);
43
+ }
44
+ if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
45
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
46
+ }
47
+ function normaliseKey(msgKey) {
48
+ // if the reaction is from another user
49
+ // we've to correctly map the key to this user's perspective
50
+ if (!message.key.fromMe) {
51
+ // if the sender believed the message being reacted to is not from them
52
+ // we've to correct the key to be from them, or some other participant
53
+ msgKey.fromMe = !msgKey.fromMe
54
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
55
+ // if the message being reacted to, was from them
56
+ // fromMe automatically becomes false
57
+ : false;
58
+ // set the remoteJid to being the same as the chat the message came from
59
+ msgKey.remoteJid = message.key.remoteJid;
60
+ // set participant of the message
61
+ msgKey.participant = msgKey.participant || message.key.participant;
62
+ }
63
+ }
64
+ };
65
+ exports.cleanMessage = cleanMessage;
66
+ const isRealMessage = (message, meId) => {
67
+ var _a;
68
+ const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
69
+ const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
70
+ return (!!normalizedContent
71
+ || REAL_MSG_STUB_TYPES.has(message.messageStubType)
72
+ || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
73
+ && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
74
+ && hasSomeContent
75
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
76
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
77
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
78
+ };
79
+ exports.isRealMessage = isRealMessage;
80
+ const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
81
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
82
+ /**
83
+ * Get the ID of the chat from the given key.
84
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
85
+ */
86
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
87
+ if ((0, WABinary_1.isJidBroadcast)(remoteJid)
88
+ && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
89
+ && !fromMe) {
90
+ return participant;
91
+ }
92
+ return remoteJid;
93
+ };
94
+ exports.getChatId = getChatId;
95
+ /**
96
+ * Decrypt a poll vote
97
+ * @param vote encrypted vote
98
+ * @param ctx additional info about the poll required for decryption
99
+ * @returns list of SHA256 options
100
+ */
101
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
102
+ const sign = Buffer.concat([
103
+ toBinary(pollMsgId),
104
+ toBinary(pollCreatorJid),
105
+ toBinary(voterJid),
106
+ toBinary('Poll Vote'),
107
+ new Uint8Array([1])
108
+ ]);
109
+ const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
110
+ const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
111
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
112
+ const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
113
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
114
+ function toBinary(txt) {
115
+ return Buffer.from(txt);
116
+ }
117
+ }
118
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
119
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
120
+ const meId = creds.me.id;
121
+ const { accountSettings } = creds;
122
+ const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
123
+ const isRealMsg = (0, exports.isRealMessage)(message, meId);
124
+ if (isRealMsg) {
125
+ chat.messages = [{ message }];
126
+ chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
127
+ // only increment unread count if not CIPHERTEXT and from another person
128
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
129
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
130
+ }
131
+ }
132
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
133
+ // unarchive chat if it's a real message, or someone reacted to our message
134
+ // and we've the unarchive chats setting on
135
+ if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
136
+ && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
137
+ chat.archived = false;
138
+ chat.readOnly = false;
139
+ }
140
+ const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
141
+ if (protocolMsg) {
142
+ switch (protocolMsg.type) {
143
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
144
+ const histNotification = protocolMsg.historySyncNotification;
145
+ const process = shouldProcessHistoryMsg;
146
+ const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
147
+ logger === null || logger === void 0 ? void 0 : logger.info({
148
+ histNotification,
149
+ process,
150
+ id: message.key.id,
151
+ isLatest,
152
+ }, 'got history notification');
153
+ if (process) {
154
+ if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
155
+ ev.emit('creds.update', {
156
+ processedHistoryMessages: [
157
+ ...(creds.processedHistoryMessages || []),
158
+ { key: message.key, messageTimestamp: message.messageTimestamp }
159
+ ]
160
+ });
161
+ }
162
+ const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
163
+ ev.emit('messaging-history.set', {
164
+ ...data,
165
+ isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
166
+ ? isLatest
167
+ : undefined,
168
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
169
+ });
170
+ }
171
+ break;
172
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
173
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
174
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
175
+ let newAppStateSyncKeyId = '';
176
+ await keyStore.transaction(async () => {
177
+ const newKeys = [];
178
+ for (const { keyData, keyId } of keys) {
179
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
180
+ newKeys.push(strKeyId);
181
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
182
+ newAppStateSyncKeyId = strKeyId;
183
+ }
184
+ logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
185
+ });
186
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
187
+ }
188
+ else {
189
+ logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
190
+ }
191
+ break;
192
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
193
+ ev.emit('messages.update', [
194
+ {
195
+ key: {
196
+ ...message.key,
197
+ id: protocolMsg.key.id
198
+ },
199
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
200
+ }
201
+ ]);
202
+ break;
203
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
204
+ Object.assign(chat, {
205
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
206
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
207
+ });
208
+ break;
209
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
210
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
211
+ if (response) {
212
+ placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
213
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
214
+ const { peerDataOperationResult } = response;
215
+ for (const result of peerDataOperationResult) {
216
+ const { placeholderMessageResendResponse: retryResponse } = result;
217
+ if (retryResponse) {
218
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
219
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
220
+ setTimeout(() => {
221
+ ev.emit('messages.upsert', {
222
+ messages: [webMessageInfo],
223
+ type: 'notify',
224
+ requestId: response.stanzaId
225
+ });
226
+ }, 500);
227
+ }
228
+ }
229
+ }
230
+ case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
231
+ ev.emit('messages.update', [
232
+ {
233
+ // flip the sender / fromMe properties because they're in the perspective of the sender
234
+ key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
235
+ update: {
236
+ message: {
237
+ editedMessage: {
238
+ message: protocolMsg.editedMessage
239
+ }
240
+ },
241
+ messageTimestamp: protocolMsg.timestampMs
242
+ ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
243
+ : message.messageTimestamp
244
+ }
245
+ }
246
+ ]);
247
+ break;
248
+ }
249
+ }
250
+ else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
251
+ const reaction = {
252
+ ...content.reactionMessage,
253
+ key: message.key,
254
+ };
255
+ ev.emit('messages.reaction', [{
256
+ reaction,
257
+ key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
258
+ }]);
259
+ }
260
+ else if (message.messageStubType) {
261
+ const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
262
+ //let actor = whatsappID (message.participant)
263
+ let participants;
264
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
265
+ const emitGroupUpdate = (update) => {
266
+ var _a;
267
+ ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
268
+ };
269
+ const emitGroupRequestJoin = (participant, action, method) => {
270
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
271
+ };
272
+ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
273
+ switch (message.messageStubType) {
274
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
275
+ participants = message.messageStubParameters || [];
276
+ emitParticipantsUpdate('modify');
277
+ break;
278
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
279
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
280
+ participants = message.messageStubParameters || [];
281
+ emitParticipantsUpdate('remove');
282
+ // mark the chat read only if you left the group
283
+ if (participantsIncludesMe()) {
284
+ chat.readOnly = true;
285
+ }
286
+ break;
287
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
288
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
289
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
290
+ participants = message.messageStubParameters || [];
291
+ if (participantsIncludesMe()) {
292
+ chat.readOnly = false;
293
+ }
294
+ emitParticipantsUpdate('add');
295
+ break;
296
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
297
+ participants = message.messageStubParameters || [];
298
+ emitParticipantsUpdate('demote');
299
+ break;
300
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
301
+ participants = message.messageStubParameters || [];
302
+ emitParticipantsUpdate('promote');
303
+ break;
304
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
305
+ const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
306
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
307
+ break;
308
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
309
+ const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
310
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
311
+ break;
312
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
313
+ const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
314
+ chat.name = name;
315
+ emitGroupUpdate({ subject: name });
316
+ break;
317
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
318
+ const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
319
+ chat.description = description;
320
+ emitGroupUpdate({ desc: description });
321
+ break;
322
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
323
+ const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
324
+ emitGroupUpdate({ inviteCode: code });
325
+ break;
326
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
327
+ const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
328
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
329
+ break;
330
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
331
+ const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
332
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
333
+ break;
334
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
335
+ const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
336
+ const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
337
+ const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
338
+ emitGroupRequestJoin(participant, action, method);
339
+ break;
340
+ }
341
+ }
342
+ else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
343
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
344
+ // we need to fetch the poll creation message to get the poll enc key
345
+ const pollMsg = await getMessage(creationMsgKey);
346
+ if (pollMsg) {
347
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
348
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
349
+ const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
350
+ const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
351
+ try {
352
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
353
+ pollEncKey,
354
+ pollCreatorJid,
355
+ pollMsgId: creationMsgKey.id,
356
+ voterJid,
357
+ });
358
+ ev.emit('messages.update', [
359
+ {
360
+ key: creationMsgKey,
361
+ update: {
362
+ pollUpdates: [
363
+ {
364
+ pollUpdateMessageKey: message.key,
365
+ vote: voteMsg,
366
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
367
+ }
368
+ ]
369
+ }
370
+ }
371
+ ]);
372
+ }
373
+ catch (err) {
374
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
375
+ }
376
+ }
377
+ else {
378
+ logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
379
+ }
380
+ }
381
+ if (Object.keys(chat).length > 1) {
382
+ ev.emit('chats.update', [chat]);
383
+ }
384
+ };
385
+ exports.default = processMessage;