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