naya-flore 4.7.1

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