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