dibosockets 1.0.2 → 1.0.4

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 +5619 -5619
  2. package/lib/Api/Internet/growagarden.js +28 -28
  3. package/lib/Api/creator.json +13 -13
  4. package/lib/Api/downloader/tiktokdownload.js +132 -132
  5. package/lib/Api/index.js +38 -38
  6. package/lib/Api/nsfw/loli.js +79 -79
  7. package/lib/Api/stalker/githubstalk.js +46 -46
  8. package/lib/Api/stalker/stalkroblox.js +94 -94
  9. package/lib/Api/stalker/tiktokstalk.js +68 -68
  10. package/lib/Api/tools/ssweb.js +38 -38
  11. package/lib/Defaults/baileys-version.json +3 -3
  12. package/lib/Defaults/index.js +122 -122
  13. package/lib/Defaults/phonenumber_mcc.json +223 -223
  14. package/lib/Socket/RHandler.js +448 -448
  15. package/lib/Socket/business.js +266 -266
  16. package/lib/Socket/chats.js +1137 -1137
  17. package/lib/Socket/communities.js +441 -441
  18. package/lib/Socket/index.js +43 -43
  19. package/lib/Socket/messages-recv.js +1065 -1065
  20. package/lib/Socket/messages-send.js +881 -881
  21. package/lib/Socket/newsletter.js +286 -286
  22. package/lib/Socket/socket.js +666 -666
  23. package/lib/Store/make-in-memory-store.js +439 -439
  24. package/lib/Types/Newsletter.js +18 -18
  25. package/lib/Utils/async-iterable.js +41 -41
  26. package/lib/Utils/baileys-event-stream.js +63 -63
  27. package/lib/Utils/browser-utils.js +34 -34
  28. package/lib/Utils/event-buffer.js +518 -518
  29. package/lib/Utils/generics.js +431 -431
  30. package/lib/Utils/index.js +36 -36
  31. package/lib/Utils/message-retry-manager.js +127 -127
  32. package/lib/Utils/messages-media.js +926 -926
  33. package/lib/Utils/messages.js +1105 -1105
  34. package/lib/Utils/process-message.js +404 -404
  35. package/lib/Utils/resolveJid.js +52 -52
  36. package/lib/Utils/use-multi-file-auth-state.js +122 -122
  37. package/lib/Utils/validate-connection.js +228 -228
  38. package/lib/WABinary/jid-utils.js +85 -85
  39. package/lib/index.js +87 -74
  40. package/package.json +2 -2
@@ -1,404 +1,404 @@
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
+ 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;