keith-baileys 1.0.26

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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/WAProto/GenerateStatics.sh +2 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/index.js +165029 -0
  6. package/WAProto/keith +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/Keith +1 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.js +105 -0
  11. package/lib/Signal/Group/Keith +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Keith +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Socket/Client/Keith +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +62 -0
  31. package/lib/Socket/Keith +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +880 -0
  34. package/lib/Socket/groups.js +340 -0
  35. package/lib/Socket/groupstatus.js +237 -0
  36. package/lib/Socket/index.js +10 -0
  37. package/lib/Socket/messages-recv.js +1077 -0
  38. package/lib/Socket/messages-send.js +988 -0
  39. package/lib/Socket/mex.js +46 -0
  40. package/lib/Socket/newsletter.js +233 -0
  41. package/lib/Socket/socket.js +617 -0
  42. package/lib/Socket/usync.js +65 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +10 -0
  46. package/lib/Types/Contact.js +2 -0
  47. package/lib/Types/Events.js +2 -0
  48. package/lib/Types/GroupMetadata.js +2 -0
  49. package/lib/Types/Keith +1 -0
  50. package/lib/Types/Label.js +27 -0
  51. package/lib/Types/LabelAssociation.js +9 -0
  52. package/lib/Types/Message.js +7 -0
  53. package/lib/Types/Newsletter.js +33 -0
  54. package/lib/Types/Product.js +2 -0
  55. package/lib/Types/Signal.js +2 -0
  56. package/lib/Types/Socket.js +2 -0
  57. package/lib/Types/State.js +2 -0
  58. package/lib/Types/USync.js +2 -0
  59. package/lib/Types/index.js +42 -0
  60. package/lib/Utils/Keith +1 -0
  61. package/lib/Utils/auth-utils.js +199 -0
  62. package/lib/Utils/baileys-event-stream.js +63 -0
  63. package/lib/Utils/business.js +240 -0
  64. package/lib/Utils/chat-utils.js +741 -0
  65. package/lib/Utils/crypto.js +187 -0
  66. package/lib/Utils/decode-wa-message.js +283 -0
  67. package/lib/Utils/event-buffer.js +516 -0
  68. package/lib/Utils/generics.js +400 -0
  69. package/lib/Utils/history.js +100 -0
  70. package/lib/Utils/index.js +34 -0
  71. package/lib/Utils/lid-mapping.js +88 -0
  72. package/lib/Utils/link-preview.js +122 -0
  73. package/lib/Utils/logger.js +7 -0
  74. package/lib/Utils/lt-hash.js +51 -0
  75. package/lib/Utils/make-mutex.js +44 -0
  76. package/lib/Utils/messages-media.js +706 -0
  77. package/lib/Utils/messages.js +797 -0
  78. package/lib/Utils/noise-handler.js +150 -0
  79. package/lib/Utils/process-message.js +381 -0
  80. package/lib/Utils/signal.js +155 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  82. package/lib/Utils/validate-connection.js +170 -0
  83. package/lib/WABinary/Keith +1 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +266 -0
  86. package/lib/WABinary/encode.js +252 -0
  87. package/lib/WABinary/generic-utils.js +110 -0
  88. package/lib/WABinary/index.js +21 -0
  89. package/lib/WABinary/jid-utils.js +66 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15243 -0
  93. package/lib/WAM/encode.js +153 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAM/keith +1 -0
  96. package/lib/WAUSync/Keith +1 -0
  97. package/lib/WAUSync/Protocols/Keith +1 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  104. package/lib/WAUSync/Protocols/index.js +20 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +26 -0
  107. package/lib/WAUSync/index.js +19 -0
  108. package/lib/index.js +30 -0
  109. package/package.json +32 -0
@@ -0,0 +1,1077 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesRecvSocket = void 0;
7
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
+ const boom_1 = require("@hapi/boom");
9
+ const crypto_1 = require("crypto");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Types_1 = require("../Types");
13
+ const Utils_1 = require("../Utils");
14
+ const make_mutex_1 = require("../Utils/make-mutex");
15
+ const WABinary_1 = require("../WABinary");
16
+ const groups_1 = require("./groups");
17
+ const messages_send_1 = require("./messages-send");
18
+ const makeMessagesRecvSocket = (config) => {
19
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
20
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
21
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage } = sock;
22
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
23
+ const retryMutex = (0, make_mutex_1.makeMutex)();
24
+ const msgRetryCache = config.msgRetryCounterCache ||
25
+ new node_cache_1.default({
26
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
27
+ useClones: false
28
+ });
29
+ const callOfferCache = config.callOfferCache ||
30
+ new node_cache_1.default({
31
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
32
+ useClones: false
33
+ });
34
+ const placeholderResendCache = config.placeholderResendCache ||
35
+ new node_cache_1.default({
36
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
37
+ useClones: false
38
+ });
39
+ let sendActiveReceipts = false;
40
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
41
+ const stanza = {
42
+ tag: 'ack',
43
+ attrs: {
44
+ id: attrs.id,
45
+ to: attrs.from,
46
+ class: tag
47
+ }
48
+ };
49
+ if (!!errorCode) {
50
+ stanza.attrs.error = errorCode.toString();
51
+ }
52
+ if (!!attrs.participant) {
53
+ stanza.attrs.participant = attrs.participant;
54
+ }
55
+ if (!!attrs.recipient) {
56
+ stanza.attrs.recipient = attrs.recipient;
57
+ }
58
+ if (!!attrs.type &&
59
+ (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
60
+ stanza.attrs.type = attrs.type;
61
+ }
62
+ if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
63
+ stanza.attrs.from = authState.creds.me.id;
64
+ }
65
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
66
+ await sendNode(stanza);
67
+ };
68
+ const rejectCall = async (callId, callFrom) => {
69
+ const stanza = {
70
+ tag: 'call',
71
+ attrs: {
72
+ from: authState.creds.me.id,
73
+ to: callFrom
74
+ },
75
+ content: [
76
+ {
77
+ tag: 'reject',
78
+ attrs: {
79
+ 'call-id': callId,
80
+ 'call-creator': callFrom,
81
+ count: '0'
82
+ },
83
+ content: undefined
84
+ }
85
+ ]
86
+ };
87
+ await query(stanza);
88
+ };
89
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
90
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
91
+ const { key: msgKey } = fullMessage;
92
+ const msgId = msgKey.id;
93
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
94
+ let retryCount = msgRetryCache.get(key) || 0;
95
+ if (retryCount >= maxMsgRetryCount) {
96
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
97
+ msgRetryCache.del(key);
98
+ return;
99
+ }
100
+ retryCount += 1;
101
+ msgRetryCache.set(key, retryCount);
102
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
103
+ if (retryCount === 1) {
104
+ //request a resend via phone
105
+ const msgId = await requestPlaceholderResend(msgKey);
106
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
107
+ }
108
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
109
+ await authState.keys.transaction(async () => {
110
+ const receipt = {
111
+ tag: 'receipt',
112
+ attrs: {
113
+ id: msgId,
114
+ type: 'retry',
115
+ to: node.attrs.from
116
+ },
117
+ content: [
118
+ {
119
+ tag: 'retry',
120
+ attrs: {
121
+ count: retryCount.toString(),
122
+ id: node.attrs.id,
123
+ t: node.attrs.t,
124
+ v: '1'
125
+ }
126
+ },
127
+ {
128
+ tag: 'registration',
129
+ attrs: {},
130
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
131
+ }
132
+ ]
133
+ };
134
+ if (node.attrs.recipient) {
135
+ receipt.attrs.recipient = node.attrs.recipient;
136
+ }
137
+ if (node.attrs.participant) {
138
+ receipt.attrs.participant = node.attrs.participant;
139
+ }
140
+ if (retryCount > 1 || forceIncludeKeys) {
141
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
142
+ const [keyId] = Object.keys(preKeys);
143
+ const key = preKeys[+keyId];
144
+ const content = receipt.content;
145
+ content.push({
146
+ tag: 'keys',
147
+ attrs: {},
148
+ content: [
149
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
150
+ { tag: 'identity', attrs: {}, content: identityKey.public },
151
+ (0, Utils_1.xmppPreKey)(key, +keyId),
152
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
153
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
154
+ ]
155
+ });
156
+ ev.emit('creds.update', update);
157
+ }
158
+ await sendNode(receipt);
159
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
160
+ });
161
+ };
162
+ const handleEncryptNotification = async (node) => {
163
+ const from = node.attrs.from;
164
+ if (from === WABinary_1.S_WHATSAPP_NET) {
165
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
166
+ const count = +countChild.attrs.value;
167
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
168
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
169
+ if (shouldUploadMorePreKeys) {
170
+ await uploadPreKeys();
171
+ }
172
+ }
173
+ else {
174
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
175
+ if (identityNode) {
176
+ logger.info({ jid: from }, 'identity changed');
177
+ // not handling right now
178
+ // signal will override new identity anyway
179
+ }
180
+ else {
181
+ logger.info({ node }, 'unknown encrypt notification');
182
+ }
183
+ }
184
+ };
185
+ const handleGroupNotification = (participant, child, msg) => {
186
+ var _a, _b, _c, _d;
187
+ const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
188
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
189
+ case 'create':
190
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
191
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
192
+ msg.messageStubParameters = [metadata.subject];
193
+ msg.key = { participant: metadata.owner };
194
+ ev.emit('chats.upsert', [
195
+ {
196
+ id: metadata.id,
197
+ name: metadata.subject,
198
+ conversationTimestamp: metadata.creation
199
+ }
200
+ ]);
201
+ ev.emit('groups.upsert', [
202
+ {
203
+ ...metadata,
204
+ author: participant
205
+ }
206
+ ]);
207
+ break;
208
+ case 'ephemeral':
209
+ case 'not_ephemeral':
210
+ msg.message = {
211
+ protocolMessage: {
212
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
213
+ ephemeralExpiration: +(child.attrs.expiration || 0)
214
+ }
215
+ };
216
+ break;
217
+ case 'modify':
218
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
219
+ msg.messageStubParameters = oldNumber || [];
220
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
221
+ break;
222
+ case 'promote':
223
+ case 'demote':
224
+ case 'remove':
225
+ case 'add':
226
+ case 'leave':
227
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
228
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
229
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
230
+ if (participants.length === 1 &&
231
+ // if recv. "remove" message and sender removed themselves
232
+ // mark as left
233
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
234
+ child.tag === 'remove') {
235
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
236
+ }
237
+ msg.messageStubParameters = participants;
238
+ break;
239
+ case 'subject':
240
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
241
+ msg.messageStubParameters = [child.attrs.subject];
242
+ break;
243
+ case 'description':
244
+ const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
245
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
246
+ msg.messageStubParameters = description ? [description] : undefined;
247
+ break;
248
+ case 'announcement':
249
+ case 'not_announcement':
250
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
251
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
252
+ break;
253
+ case 'locked':
254
+ case 'unlocked':
255
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
256
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
257
+ break;
258
+ case 'invite':
259
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
260
+ msg.messageStubParameters = [child.attrs.code];
261
+ break;
262
+ case 'member_add_mode':
263
+ const addMode = child.content;
264
+ if (addMode) {
265
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
266
+ msg.messageStubParameters = [addMode.toString()];
267
+ }
268
+ break;
269
+ case 'membership_approval_mode':
270
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
271
+ if (approvalMode) {
272
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
273
+ msg.messageStubParameters = [approvalMode.attrs.state];
274
+ }
275
+ break;
276
+ case 'created_membership_requests':
277
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
278
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
279
+ break;
280
+ case 'revoked_membership_requests':
281
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
282
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
283
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
284
+ break;
285
+ }
286
+ };
287
+ const processNotification = async (node) => {
288
+ var _a, _b, _c;
289
+ const result = {};
290
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
291
+ const nodeType = node.attrs.type;
292
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
293
+ switch (nodeType) {
294
+ case 'privacy_token':
295
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
296
+ for (const { attrs, content } of tokenList) {
297
+ const jid = attrs.jid;
298
+ ev.emit('chats.update', [
299
+ {
300
+ id: jid,
301
+ tcToken: content
302
+ }
303
+ ]);
304
+ logger.debug({ jid }, 'got privacy token update');
305
+ }
306
+ break;
307
+ case 'newsletter':
308
+ await handleNewsletterNotification(node);
309
+ break;
310
+ case 'mex':
311
+ await handleMexNewsletterNotification(node);
312
+ break;
313
+ case 'w:gp2':
314
+ handleGroupNotification(node.attrs.participant, child, result);
315
+ break;
316
+ case 'mediaretry':
317
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
318
+ ev.emit('messages.media-update', [event]);
319
+ break;
320
+ case 'encrypt':
321
+ await handleEncryptNotification(node);
322
+ break;
323
+ case 'devices':
324
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
325
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
326
+ const deviceJids = devices.map(d => d.attrs.jid);
327
+ logger.info({ deviceJids }, 'got my own devices');
328
+ }
329
+ break;
330
+ case 'server_sync':
331
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
332
+ if (update) {
333
+ const name = update.attrs.name;
334
+ await resyncAppState([name], false);
335
+ }
336
+ break;
337
+ case 'picture':
338
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
339
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
340
+ ev.emit('contacts.update', [
341
+ {
342
+ id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.from) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
343
+ imgUrl: setPicture ? 'changed' : 'removed'
344
+ }
345
+ ]);
346
+ if ((0, WABinary_1.isJidGroup)(from)) {
347
+ const node = setPicture || delPicture;
348
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
349
+ if (setPicture) {
350
+ result.messageStubParameters = [setPicture.attrs.id];
351
+ }
352
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
353
+ result.key = {
354
+ ...(result.key || {}),
355
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
356
+ };
357
+ }
358
+ break;
359
+ case 'account_sync':
360
+ if (child.tag === 'disappearing_mode') {
361
+ const newDuration = +child.attrs.duration;
362
+ const timestamp = +child.attrs.t;
363
+ logger.info({ newDuration }, 'updated account disappearing mode');
364
+ ev.emit('creds.update', {
365
+ accountSettings: {
366
+ ...authState.creds.accountSettings,
367
+ defaultDisappearingMode: {
368
+ ephemeralExpiration: newDuration,
369
+ ephemeralSettingTimestamp: timestamp
370
+ }
371
+ }
372
+ });
373
+ }
374
+ else if (child.tag === 'blocklist') {
375
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
376
+ for (const { attrs } of blocklists) {
377
+ const blocklist = [attrs.jid];
378
+ const type = attrs.action === 'block' ? 'add' : 'remove';
379
+ ev.emit('blocklist.update', { blocklist, type });
380
+ }
381
+ }
382
+ break;
383
+ case 'link_code_companion_reg':
384
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
385
+ const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
386
+ const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
387
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
388
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
389
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
390
+ const random = (0, crypto_1.randomBytes)(32);
391
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
392
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
393
+ salt: linkCodeSalt,
394
+ info: 'link_code_pairing_key_bundle_encryption_key'
395
+ });
396
+ const encryptPayload = Buffer.concat([
397
+ Buffer.from(authState.creds.signedIdentityKey.public),
398
+ primaryIdentityPublicKey,
399
+ random
400
+ ]);
401
+ const encryptIv = (0, crypto_1.randomBytes)(12);
402
+ const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
403
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
404
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
405
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
406
+ authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
407
+ await query({
408
+ tag: 'iq',
409
+ attrs: {
410
+ to: WABinary_1.S_WHATSAPP_NET,
411
+ type: 'set',
412
+ id: sock.generateMessageTag(),
413
+ xmlns: 'md'
414
+ },
415
+ content: [
416
+ {
417
+ tag: 'link_code_companion_reg',
418
+ attrs: {
419
+ jid: authState.creds.me.id,
420
+ stage: 'companion_finish'
421
+ },
422
+ content: [
423
+ {
424
+ tag: 'link_code_pairing_wrapped_key_bundle',
425
+ attrs: {},
426
+ content: encryptedPayload
427
+ },
428
+ {
429
+ tag: 'companion_identity_public',
430
+ attrs: {},
431
+ content: authState.creds.signedIdentityKey.public
432
+ },
433
+ {
434
+ tag: 'link_code_pairing_ref',
435
+ attrs: {},
436
+ content: ref
437
+ }
438
+ ]
439
+ }
440
+ ]
441
+ });
442
+ authState.creds.registered = true;
443
+ ev.emit('creds.update', authState.creds);
444
+ }
445
+ if (Object.keys(result).length) {
446
+ return result;
447
+ }
448
+ };
449
+ async function decipherLinkPublicKey(data) {
450
+ const buffer = toRequiredBuffer(data);
451
+ const salt = buffer.slice(0, 32);
452
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
453
+ const iv = buffer.slice(32, 48);
454
+ const payload = buffer.slice(48, 80);
455
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
456
+ }
457
+ function toRequiredBuffer(data) {
458
+ if (data === undefined) {
459
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
460
+ }
461
+ return data instanceof Buffer ? data : Buffer.from(data);
462
+ }
463
+ const willSendMessageAgain = (id, participant) => {
464
+ const key = `${id}:${participant}`;
465
+ const retryCount = msgRetryCache.get(key) || 0;
466
+ return retryCount < maxMsgRetryCount;
467
+ };
468
+ const updateSendMessageAgainCount = (id, participant) => {
469
+ const key = `${id}:${participant}`;
470
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
471
+ msgRetryCache.set(key, newValue);
472
+ };
473
+ const sendMessagesAgain = async (key, ids, retryNode) => {
474
+ var _a;
475
+ // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
476
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
477
+ const remoteJid = key.remoteJid;
478
+ const participant = key.participant || remoteJid;
479
+ // if it's the primary jid sending the request
480
+ // just re-send the message to everyone
481
+ // prevents the first message decryption failure
482
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
483
+ await assertSessions([participant], true);
484
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
485
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
486
+ }
487
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
488
+ for (const [i, msg] of msgs.entries()) {
489
+ if (msg) {
490
+ updateSendMessageAgainCount(ids[i], participant);
491
+ const msgRelayOpts = { messageId: ids[i] };
492
+ if (sendToAll) {
493
+ msgRelayOpts.useUserDevicesCache = false;
494
+ }
495
+ else {
496
+ msgRelayOpts.participant = {
497
+ jid: participant,
498
+ count: +retryNode.attrs.count
499
+ };
500
+ }
501
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
502
+ }
503
+ else {
504
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
505
+ }
506
+ }
507
+ };
508
+ const handleReceipt = async (node) => {
509
+ var _a, _b;
510
+ const { attrs, content } = node;
511
+ const isLid = attrs.from.includes('lid');
512
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, isLid ? (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.lid : (_b = authState.creds.me) === null || _b === void 0 ? void 0 : _b.id);
513
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
514
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
515
+ const key = {
516
+ remoteJid,
517
+ id: '',
518
+ fromMe,
519
+ participant: attrs.participant
520
+ };
521
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
522
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
523
+ await sendMessageAck(node);
524
+ return;
525
+ }
526
+ const ids = [attrs.id];
527
+ if (Array.isArray(content)) {
528
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
529
+ ids.push(...items.map(i => i.attrs.id));
530
+ }
531
+ try {
532
+ await Promise.all([
533
+ processingMutex.mutex(async () => {
534
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
535
+ if (typeof status !== 'undefined' &&
536
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
537
+ // or another device of ours has read some messages
538
+ (status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
539
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
540
+ if (attrs.participant) {
541
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
542
+ ev.emit('message-receipt.update', ids.map(id => ({
543
+ key: { ...key, id },
544
+ receipt: {
545
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
546
+ [updateKey]: +attrs.t
547
+ }
548
+ })));
549
+ }
550
+ }
551
+ else {
552
+ ev.emit('messages.update', ids.map(id => ({
553
+ key: { ...key, id },
554
+ update: { status }
555
+ })));
556
+ }
557
+ }
558
+ if (attrs.type === 'retry') {
559
+ // correctly set who is asking for the retry
560
+ key.participant = key.participant || attrs.from;
561
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
562
+ if (willSendMessageAgain(ids[0], key.participant)) {
563
+ if (key.fromMe) {
564
+ try {
565
+ logger.debug({ attrs, key }, 'recv retry request');
566
+ await sendMessagesAgain(key, ids, retryNode);
567
+ }
568
+ catch (error) {
569
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
570
+ }
571
+ }
572
+ else {
573
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
574
+ }
575
+ }
576
+ else {
577
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
578
+ }
579
+ }
580
+ })
581
+ ]);
582
+ }
583
+ finally {
584
+ await sendMessageAck(node);
585
+ }
586
+ };
587
+ const handleNotification = async (node) => {
588
+ const remoteJid = node.attrs.from;
589
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
590
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
591
+ await sendMessageAck(node);
592
+ return;
593
+ }
594
+ try {
595
+ await Promise.all([
596
+ processingMutex.mutex(async () => {
597
+ var _a;
598
+ const msg = await processNotification(node);
599
+ if (msg) {
600
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
601
+ msg.key = {
602
+ remoteJid,
603
+ fromMe,
604
+ participant: node.attrs.participant,
605
+ id: node.attrs.id,
606
+ ...(msg.key || {})
607
+ };
608
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
609
+ msg.messageTimestamp = +node.attrs.t;
610
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
611
+ await upsertMessage(fullMsg, 'append');
612
+ }
613
+ })
614
+ ]);
615
+ }
616
+ finally {
617
+ await sendMessageAck(node);
618
+ }
619
+ };
620
+ const handleMessage = async (node) => {
621
+ var _a, _b, _c;
622
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
623
+ logger.debug({ key: node.attrs.key }, 'ignored message');
624
+ await sendMessageAck(node);
625
+ return;
626
+ }
627
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
628
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
629
+ if (encNode && encNode.attrs.type === 'msmsg') {
630
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
631
+ await sendMessageAck(node);
632
+ return;
633
+ }
634
+ let response;
635
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !encNode) {
636
+ await sendMessageAck(node);
637
+ const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
638
+ response = await requestPlaceholderResend(key);
639
+ if (response === 'RESOLVED') {
640
+ return;
641
+ }
642
+ logger.debug('received unavailable message, acked and requested resend from phone');
643
+ }
644
+ else {
645
+ if (placeholderResendCache.get(node.attrs.id)) {
646
+ placeholderResendCache.del(node.attrs.id);
647
+ }
648
+ }
649
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
650
+ if (response && ((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
651
+ msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
652
+ }
653
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER &&
654
+ node.attrs.sender_pn) {
655
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
656
+ }
657
+ try {
658
+ await Promise.all([
659
+ processingMutex.mutex(async () => {
660
+ var _a;
661
+ await decrypt();
662
+ // message failed to decrypt
663
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
664
+ if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
665
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
666
+ }
667
+ retryMutex.mutex(async () => {
668
+ if (ws.isOpen) {
669
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
670
+ return;
671
+ }
672
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
673
+ await sendRetryRequest(node, !encNode);
674
+ if (retryRequestDelayMs) {
675
+ await (0, Utils_1.delay)(retryRequestDelayMs);
676
+ }
677
+ }
678
+ else {
679
+ logger.debug({ node }, 'connection closed, ignoring retry req');
680
+ }
681
+ });
682
+ }
683
+ else {
684
+ // no type in the receipt => message delivered
685
+ let type = undefined;
686
+ let participant = msg.key.participant;
687
+ if (category === 'peer') {
688
+ // special peer message
689
+ type = 'peer_msg';
690
+ }
691
+ else if (msg.key.fromMe) {
692
+ // message was sent by us from a different device
693
+ type = 'sender';
694
+ // need to specially handle this case
695
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
696
+ participant = author;
697
+ }
698
+ }
699
+ else if (!sendActiveReceipts) {
700
+ type = 'inactive';
701
+ }
702
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
703
+ // send ack for history message
704
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
705
+ if (isAnyHistoryMsg) {
706
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
707
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
708
+ }
709
+ }
710
+ (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
711
+ await sendMessageAck(node);
712
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
713
+ })
714
+ ]);
715
+ }
716
+ catch (error) {
717
+ logger.error({ error, node }, 'error in handling message');
718
+ }
719
+ };
720
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
721
+ var _a;
722
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
723
+ throw new boom_1.Boom('Not authenticated');
724
+ }
725
+ const pdoMessage = {
726
+ historySyncOnDemandRequest: {
727
+ chatJid: oldestMsgKey.remoteJid,
728
+ oldestMsgFromMe: oldestMsgKey.fromMe,
729
+ oldestMsgId: oldestMsgKey.id,
730
+ oldestMsgTimestampMs: oldestMsgTimestamp,
731
+ onDemandMsgCount: count
732
+ },
733
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
734
+ };
735
+ return sendPeerDataOperationMessage(pdoMessage);
736
+ };
737
+ const requestPlaceholderResend = async (messageKey) => {
738
+ var _a;
739
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
740
+ throw new boom_1.Boom('Not authenticated');
741
+ }
742
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
743
+ logger.debug({ messageKey }, 'already requested resend');
744
+ return;
745
+ }
746
+ else {
747
+ placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
748
+ }
749
+ await (0, Utils_1.delay)(5000);
750
+ if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
751
+ logger.debug({ messageKey }, 'message received while resend requested');
752
+ return 'RESOLVED';
753
+ }
754
+ const pdoMessage = {
755
+ placeholderMessageResendRequest: [
756
+ {
757
+ messageKey
758
+ }
759
+ ],
760
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
761
+ };
762
+ setTimeout(() => {
763
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
764
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
765
+ placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
766
+ }
767
+ }, 15000);
768
+ return sendPeerDataOperationMessage(pdoMessage);
769
+ };
770
+ const handleCall = async (node) => {
771
+ const { attrs } = node;
772
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
773
+ const callId = infoChild.attrs['call-id'];
774
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
775
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
776
+ const call = {
777
+ chatId: attrs.from,
778
+ from,
779
+ id: callId,
780
+ date: new Date(+attrs.t * 1000),
781
+ offline: !!attrs.offline,
782
+ status
783
+ };
784
+ if (status === 'offer') {
785
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
786
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
787
+ call.groupJid = infoChild.attrs['group-jid'];
788
+ callOfferCache.set(call.id, call);
789
+ }
790
+ const existingCall = callOfferCache.get(call.id);
791
+ // use existing call info to populate this event
792
+ if (existingCall) {
793
+ call.isVideo = existingCall.isVideo;
794
+ call.isGroup = existingCall.isGroup;
795
+ }
796
+ // delete data once call has ended
797
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
798
+ callOfferCache.del(call.id);
799
+ }
800
+ ev.emit('call', [call]);
801
+ await sendMessageAck(node);
802
+ };
803
+ const handleBadAck = async ({ attrs }) => {
804
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
805
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
806
+ // // current hypothesis is that if pash is sent in the ack
807
+ // // it means -- the message hasn't reached all devices yet
808
+ // // we'll retry sending the message here
809
+ // if(attrs.phash) {
810
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
811
+ // const msg = await getMessage(key)
812
+ // if(msg) {
813
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
814
+ // } else {
815
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
816
+ // }
817
+ // }
818
+ // error in acknowledgement,
819
+ // device could not display the message
820
+ if (attrs.error) {
821
+ logger.warn({ attrs }, 'received error in ack');
822
+ ev.emit('messages.update', [
823
+ {
824
+ key,
825
+ update: {
826
+ status: Types_1.WAMessageStatus.ERROR,
827
+ messageStubParameters: [attrs.error]
828
+ }
829
+ }
830
+ ]);
831
+ }
832
+ };
833
+ /// processes a node with the given function
834
+ /// and adds the task to the existing buffer if we're buffering events
835
+ const processNodeWithBuffer = async (node, identifier, exec) => {
836
+ ev.buffer();
837
+ await execTask();
838
+ ev.flush();
839
+ function execTask() {
840
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
841
+ }
842
+ };
843
+ const makeOfflineNodeProcessor = () => {
844
+ const nodeProcessorMap = new Map([
845
+ ['message', handleMessage],
846
+ ['call', handleCall],
847
+ ['receipt', handleReceipt],
848
+ ['notification', handleNotification]
849
+ ]);
850
+ const nodes = [];
851
+ let isProcessing = false;
852
+ const enqueue = (type, node) => {
853
+ nodes.push({ type, node });
854
+ if (isProcessing) {
855
+ return;
856
+ }
857
+ isProcessing = true;
858
+ const promise = async () => {
859
+ while (nodes.length && ws.isOpen) {
860
+ const { type, node } = nodes.shift();
861
+ const nodeProcessor = nodeProcessorMap.get(type);
862
+ if (!nodeProcessor) {
863
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
864
+ continue;
865
+ }
866
+ await nodeProcessor(node);
867
+ }
868
+ isProcessing = false;
869
+ };
870
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
871
+ };
872
+ return { enqueue };
873
+ };
874
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
875
+ const processNode = (type, node, identifier, exec) => {
876
+ const isOffline = !!node.attrs.offline;
877
+ if (isOffline) {
878
+ offlineNodeProcessor.enqueue(type, node);
879
+ }
880
+ else {
881
+ processNodeWithBuffer(node, identifier, exec);
882
+ }
883
+ };
884
+ // Handles newsletter notifications
885
+ async function handleNewsletterNotification(node) {
886
+ var _a;
887
+ const from = node.attrs.from;
888
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
889
+ const author = node.attrs.participant;
890
+ logger.info({ from, child }, 'got newsletter notification');
891
+ switch (child.tag) {
892
+ case 'reaction':
893
+ const reactionUpdate = {
894
+ id: from,
895
+ server_id: child.attrs.message_id,
896
+ reaction: {
897
+ code: (0, WABinary_1.getBinaryNodeChildString)(child, 'reaction'),
898
+ count: 1
899
+ }
900
+ };
901
+ ev.emit('newsletter.reaction', reactionUpdate);
902
+ break;
903
+ case 'view':
904
+ const viewUpdate = {
905
+ id: from,
906
+ server_id: child.attrs.message_id,
907
+ count: parseInt(((_a = child.content) === null || _a === void 0 ? void 0 : _a.toString()) || '0', 10)
908
+ };
909
+ ev.emit('newsletter.view', viewUpdate);
910
+ break;
911
+ case 'participant':
912
+ const participantUpdate = {
913
+ id: from,
914
+ author,
915
+ user: child.attrs.jid,
916
+ action: child.attrs.action,
917
+ new_role: child.attrs.role
918
+ };
919
+ ev.emit('newsletter-participants.update', participantUpdate);
920
+ break;
921
+ case 'update':
922
+ const settingsNode = (0, WABinary_1.getBinaryNodeChild)(child, 'settings');
923
+ if (settingsNode) {
924
+ const update = {};
925
+ const nameNode = (0, WABinary_1.getBinaryNodeChild)(settingsNode, 'name');
926
+ if (nameNode === null || nameNode === void 0 ? void 0 : nameNode.content)
927
+ update.name = nameNode.content.toString();
928
+ const descriptionNode = (0, WABinary_1.getBinaryNodeChild)(settingsNode, 'description');
929
+ if (descriptionNode === null || descriptionNode === void 0 ? void 0 : descriptionNode.content)
930
+ update.description = descriptionNode.content.toString();
931
+ ev.emit('newsletter-settings.update', {
932
+ id: from,
933
+ update
934
+ });
935
+ }
936
+ break;
937
+ case 'message':
938
+ const plaintextNode = (0, WABinary_1.getBinaryNodeChild)(child, 'plaintext');
939
+ if (plaintextNode === null || plaintextNode === void 0 ? void 0 : plaintextNode.content) {
940
+ try {
941
+ const contentBuf = typeof plaintextNode.content === 'string'
942
+ ? Buffer.from(plaintextNode.content, 'binary')
943
+ : Buffer.from(plaintextNode.content);
944
+ const messageProto = WAProto_1.proto.Message.decode(contentBuf);
945
+ const fullMessage = WAProto_1.proto.WebMessageInfo.fromObject({
946
+ key: {
947
+ remoteJid: from,
948
+ id: child.attrs.message_id || child.attrs.server_id,
949
+ fromMe: false
950
+ },
951
+ message: messageProto,
952
+ messageTimestamp: +child.attrs.t
953
+ });
954
+ await upsertMessage(fullMessage, 'append');
955
+ logger.info('Processed plaintext newsletter message');
956
+ }
957
+ catch (error) {
958
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
959
+ }
960
+ }
961
+ break;
962
+ default:
963
+ logger.warn({ node }, 'Unknown newsletter notification');
964
+ break;
965
+ }
966
+ }
967
+ // Handles mex newsletter notifications
968
+ async function handleMexNewsletterNotification(node) {
969
+ const mexNode = (0, WABinary_1.getBinaryNodeChild)(node, 'mex');
970
+ if (!(mexNode === null || mexNode === void 0 ? void 0 : mexNode.content)) {
971
+ logger.warn({ node }, 'Invalid mex newsletter notification');
972
+ return;
973
+ }
974
+ let data;
975
+ try {
976
+ data = JSON.parse(mexNode.content.toString());
977
+ }
978
+ catch (error) {
979
+ logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
980
+ return;
981
+ }
982
+ const operation = data === null || data === void 0 ? void 0 : data.operation;
983
+ const updates = data === null || data === void 0 ? void 0 : data.updates;
984
+ if (!updates || !operation) {
985
+ logger.warn({ data }, 'Invalid mex newsletter notification content');
986
+ return;
987
+ }
988
+ logger.info({ operation, updates }, 'got mex newsletter notification');
989
+ switch (operation) {
990
+ case 'NotificationNewsletterUpdate':
991
+ for (const update of updates) {
992
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
993
+ ev.emit('newsletter-settings.update', {
994
+ id: update.jid,
995
+ update: update.settings
996
+ });
997
+ }
998
+ }
999
+ break;
1000
+ case 'NotificationNewsletterAdminPromote':
1001
+ for (const update of updates) {
1002
+ if (update.jid && update.user) {
1003
+ ev.emit('newsletter-participants.update', {
1004
+ id: update.jid,
1005
+ author: node.attrs.from,
1006
+ user: update.user,
1007
+ new_role: 'ADMIN',
1008
+ action: 'promote'
1009
+ });
1010
+ }
1011
+ }
1012
+ break;
1013
+ default:
1014
+ logger.info({ operation, data }, 'Unhandled mex newsletter notification');
1015
+ break;
1016
+ }
1017
+ }
1018
+ // recv a message
1019
+ ws.on('CB:message', (node) => {
1020
+ processNode('message', node, 'processing message', handleMessage);
1021
+ });
1022
+ ws.on('CB:call', async (node) => {
1023
+ processNode('call', node, 'handling call', handleCall);
1024
+ });
1025
+ ws.on('CB:receipt', node => {
1026
+ processNode('receipt', node, 'handling receipt', handleReceipt);
1027
+ });
1028
+ ws.on('CB:notification', async (node) => {
1029
+ processNode('notification', node, 'handling notification', handleNotification);
1030
+ });
1031
+ ws.on('CB:ack,class:message', (node) => {
1032
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1033
+ });
1034
+ ev.on('call', ([call]) => {
1035
+ // missed call + group call notification message generation
1036
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1037
+ const msg = {
1038
+ key: {
1039
+ remoteJid: call.chatId,
1040
+ id: call.id,
1041
+ fromMe: false
1042
+ },
1043
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date)
1044
+ };
1045
+ if (call.status === 'timeout') {
1046
+ if (call.isGroup) {
1047
+ msg.messageStubType = call.isVideo
1048
+ ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1049
+ : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1050
+ }
1051
+ else {
1052
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1053
+ }
1054
+ }
1055
+ else {
1056
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1057
+ }
1058
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1059
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1060
+ }
1061
+ });
1062
+ ev.on('connection.update', ({ isOnline }) => {
1063
+ if (typeof isOnline !== 'undefined') {
1064
+ sendActiveReceipts = isOnline;
1065
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1066
+ }
1067
+ });
1068
+ return {
1069
+ ...sock,
1070
+ sendMessageAck,
1071
+ sendRetryRequest,
1072
+ rejectCall,
1073
+ fetchMessageHistory,
1074
+ requestPlaceholderResend
1075
+ };
1076
+ };
1077
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;