libzapitu 1.0.0-alpha.3

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