@heavstaltech/baileys 1.0.0

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