@d0v3riz/baileys 6.3.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 (147) hide show
  1. package/README.md +956 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +2845 -0
  4. package/WAProto/index.d.ts +32006 -0
  5. package/WAProto/index.js +87184 -0
  6. package/WASignalGroup/GroupProtocol.js +1697 -0
  7. package/WASignalGroup/ciphertext_message.js +16 -0
  8. package/WASignalGroup/group_cipher.js +106 -0
  9. package/WASignalGroup/group_session_builder.js +46 -0
  10. package/WASignalGroup/index.js +5 -0
  11. package/WASignalGroup/keyhelper.js +21 -0
  12. package/WASignalGroup/protobufs.js +3 -0
  13. package/WASignalGroup/readme.md +6 -0
  14. package/WASignalGroup/sender_chain_key.js +50 -0
  15. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  16. package/WASignalGroup/sender_key_message.js +92 -0
  17. package/WASignalGroup/sender_key_name.js +70 -0
  18. package/WASignalGroup/sender_key_record.js +54 -0
  19. package/WASignalGroup/sender_key_state.js +129 -0
  20. package/WASignalGroup/sender_message_key.js +39 -0
  21. package/lib/Defaults/baileys-version.json +3 -0
  22. package/lib/Defaults/index.d.ts +284 -0
  23. package/lib/Defaults/index.js +115 -0
  24. package/lib/Defaults/phonenumber-mcc.json +223 -0
  25. package/lib/Signal/libsignal.d.ts +3 -0
  26. package/lib/Signal/libsignal.js +151 -0
  27. package/lib/Socket/Client/abstract-socket-client.d.ts +16 -0
  28. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  29. package/lib/Socket/Client/index.d.ts +3 -0
  30. package/lib/Socket/Client/index.js +19 -0
  31. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  32. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  33. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  34. package/lib/Socket/Client/web-socket-client.js +62 -0
  35. package/lib/Socket/business.d.ts +124 -0
  36. package/lib/Socket/business.js +259 -0
  37. package/lib/Socket/chats.d.ts +74 -0
  38. package/lib/Socket/chats.js +838 -0
  39. package/lib/Socket/groups.d.ts +105 -0
  40. package/lib/Socket/groups.js +291 -0
  41. package/lib/Socket/index.d.ts +126 -0
  42. package/lib/Socket/index.js +10 -0
  43. package/lib/Socket/messages-recv.d.ts +112 -0
  44. package/lib/Socket/messages-recv.js +641 -0
  45. package/lib/Socket/messages-send.d.ts +110 -0
  46. package/lib/Socket/messages-send.js +648 -0
  47. package/lib/Socket/registration.d.ts +211 -0
  48. package/lib/Socket/registration.js +166 -0
  49. package/lib/Socket/socket.d.ts +42 -0
  50. package/lib/Socket/socket.js +527 -0
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/index.js +10 -0
  53. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  54. package/lib/Store/make-cache-manager-store.js +83 -0
  55. package/lib/Store/make-in-memory-store.d.ts +117 -0
  56. package/lib/Store/make-in-memory-store.js +435 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +106 -0
  62. package/lib/Types/Auth.js +2 -0
  63. package/lib/Types/Call.d.ts +12 -0
  64. package/lib/Types/Call.js +2 -0
  65. package/lib/Types/Chat.d.ts +102 -0
  66. package/lib/Types/Chat.js +4 -0
  67. package/lib/Types/Contact.d.ts +18 -0
  68. package/lib/Types/Contact.js +2 -0
  69. package/lib/Types/Events.d.ts +152 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.d.ts +42 -0
  72. package/lib/Types/GroupMetadata.js +2 -0
  73. package/lib/Types/Label.d.ts +35 -0
  74. package/lib/Types/Label.js +27 -0
  75. package/lib/Types/LabelAssociation.d.ts +29 -0
  76. package/lib/Types/LabelAssociation.js +9 -0
  77. package/lib/Types/Message.d.ts +245 -0
  78. package/lib/Types/Message.js +9 -0
  79. package/lib/Types/Product.d.ts +78 -0
  80. package/lib/Types/Product.js +2 -0
  81. package/lib/Types/Signal.d.ts +57 -0
  82. package/lib/Types/Signal.js +2 -0
  83. package/lib/Types/Socket.d.ts +106 -0
  84. package/lib/Types/Socket.js +2 -0
  85. package/lib/Types/State.d.ts +27 -0
  86. package/lib/Types/State.js +2 -0
  87. package/lib/Types/index.d.ts +54 -0
  88. package/lib/Types/index.js +39 -0
  89. package/lib/Utils/auth-utils.d.ts +18 -0
  90. package/lib/Utils/auth-utils.js +202 -0
  91. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  92. package/lib/Utils/baileys-event-stream.js +63 -0
  93. package/lib/Utils/business.d.ts +22 -0
  94. package/lib/Utils/business.js +234 -0
  95. package/lib/Utils/chat-utils.d.ts +71 -0
  96. package/lib/Utils/chat-utils.js +710 -0
  97. package/lib/Utils/crypto.d.ts +38 -0
  98. package/lib/Utils/crypto.js +137 -0
  99. package/lib/Utils/decode-wa-message.d.ts +19 -0
  100. package/lib/Utils/decode-wa-message.js +160 -0
  101. package/lib/Utils/event-buffer.d.ts +35 -0
  102. package/lib/Utils/event-buffer.js +514 -0
  103. package/lib/Utils/generics.d.ts +92 -0
  104. package/lib/Utils/generics.js +368 -0
  105. package/lib/Utils/history.d.ts +15 -0
  106. package/lib/Utils/history.js +91 -0
  107. package/lib/Utils/index.d.ts +17 -0
  108. package/lib/Utils/index.js +33 -0
  109. package/lib/Utils/link-preview.d.ts +21 -0
  110. package/lib/Utils/link-preview.js +116 -0
  111. package/lib/Utils/logger.d.ts +4 -0
  112. package/lib/Utils/logger.js +7 -0
  113. package/lib/Utils/lt-hash.d.ts +12 -0
  114. package/lib/Utils/lt-hash.js +51 -0
  115. package/lib/Utils/make-mutex.d.ts +7 -0
  116. package/lib/Utils/make-mutex.js +43 -0
  117. package/lib/Utils/messages-media.d.ts +101 -0
  118. package/lib/Utils/messages-media.js +632 -0
  119. package/lib/Utils/messages.d.ts +75 -0
  120. package/lib/Utils/messages.js +738 -0
  121. package/lib/Utils/noise-handler.d.ts +20 -0
  122. package/lib/Utils/noise-handler.js +142 -0
  123. package/lib/Utils/process-message.d.ts +41 -0
  124. package/lib/Utils/process-message.js +297 -0
  125. package/lib/Utils/signal.d.ts +32 -0
  126. package/lib/Utils/signal.js +151 -0
  127. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  128. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  129. package/lib/Utils/validate-connection.d.ts +11 -0
  130. package/lib/Utils/validate-connection.js +188 -0
  131. package/lib/WABinary/constants.d.ts +27 -0
  132. package/lib/WABinary/constants.js +40 -0
  133. package/lib/WABinary/decode.d.ts +7 -0
  134. package/lib/WABinary/decode.js +252 -0
  135. package/lib/WABinary/encode.d.ts +3 -0
  136. package/lib/WABinary/encode.js +228 -0
  137. package/lib/WABinary/generic-utils.d.ts +15 -0
  138. package/lib/WABinary/generic-utils.js +110 -0
  139. package/lib/WABinary/index.d.ts +5 -0
  140. package/lib/WABinary/index.js +21 -0
  141. package/lib/WABinary/jid-utils.d.ts +27 -0
  142. package/lib/WABinary/jid-utils.js +56 -0
  143. package/lib/WABinary/types.d.ts +18 -0
  144. package/lib/WABinary/types.js +2 -0
  145. package/lib/index.d.ts +9 -0
  146. package/lib/index.js +27 -0
  147. package/package.json +100 -0
@@ -0,0 +1,838 @@
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.makeChatsSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const WAProto_1 = require("../../WAProto");
9
+ const Defaults_1 = require("../Defaults");
10
+ const Types_1 = require("../Types");
11
+ const Utils_1 = require("../Utils");
12
+ const make_mutex_1 = require("../Utils/make-mutex");
13
+ const process_message_1 = __importDefault(require("../Utils/process-message"));
14
+ const WABinary_1 = require("../WABinary");
15
+ const socket_1 = require("./socket");
16
+ const MAX_SYNC_ATTEMPTS = 2;
17
+ const makeChatsSocket = (config) => {
18
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
19
+ const sock = (0, socket_1.makeSocket)(config);
20
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
21
+ let privacySettings;
22
+ let needToFlushWithAppStateSync = false;
23
+ let pendingAppStateSync = false;
24
+ /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
25
+ const processingMutex = (0, make_mutex_1.makeMutex)();
26
+ /** helper function to fetch the given app state sync key */
27
+ const getAppStateSyncKey = async (keyId) => {
28
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
29
+ return key;
30
+ };
31
+ const fetchPrivacySettings = async (force = false) => {
32
+ if (!privacySettings || force) {
33
+ const { content } = await query({
34
+ tag: 'iq',
35
+ attrs: {
36
+ xmlns: 'privacy',
37
+ to: WABinary_1.S_WHATSAPP_NET,
38
+ type: 'get'
39
+ },
40
+ content: [
41
+ { tag: 'privacy', attrs: {} }
42
+ ]
43
+ });
44
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
45
+ }
46
+ return privacySettings;
47
+ };
48
+ /** helper function to run a privacy IQ query */
49
+ const privacyQuery = async (name, value) => {
50
+ await query({
51
+ tag: 'iq',
52
+ attrs: {
53
+ xmlns: 'privacy',
54
+ to: WABinary_1.S_WHATSAPP_NET,
55
+ type: 'set'
56
+ },
57
+ content: [{
58
+ tag: 'privacy',
59
+ attrs: {},
60
+ content: [
61
+ {
62
+ tag: 'category',
63
+ attrs: { name, value }
64
+ }
65
+ ]
66
+ }]
67
+ });
68
+ };
69
+ const updateLastSeenPrivacy = async (value) => {
70
+ await privacyQuery('last', value);
71
+ };
72
+ const updateOnlinePrivacy = async (value) => {
73
+ await privacyQuery('online', value);
74
+ };
75
+ const updateProfilePicturePrivacy = async (value) => {
76
+ await privacyQuery('profile', value);
77
+ };
78
+ const updateStatusPrivacy = async (value) => {
79
+ await privacyQuery('status', value);
80
+ };
81
+ const updateReadReceiptsPrivacy = async (value) => {
82
+ await privacyQuery('readreceipts', value);
83
+ };
84
+ const updateGroupsAddPrivacy = async (value) => {
85
+ await privacyQuery('groupadd', value);
86
+ };
87
+ const updateDefaultDisappearingMode = async (duration) => {
88
+ await query({
89
+ tag: 'iq',
90
+ attrs: {
91
+ xmlns: 'disappearing_mode',
92
+ to: WABinary_1.S_WHATSAPP_NET,
93
+ type: 'set'
94
+ },
95
+ content: [{
96
+ tag: 'disappearing_mode',
97
+ attrs: {
98
+ duration: duration.toString()
99
+ }
100
+ }]
101
+ });
102
+ };
103
+ /** helper function to run a generic IQ query */
104
+ const interactiveQuery = async (userNodes, queryNode) => {
105
+ const result = await query({
106
+ tag: 'iq',
107
+ attrs: {
108
+ to: WABinary_1.S_WHATSAPP_NET,
109
+ type: 'get',
110
+ xmlns: 'usync',
111
+ },
112
+ content: [
113
+ {
114
+ tag: 'usync',
115
+ attrs: {
116
+ sid: generateMessageTag(),
117
+ mode: 'query',
118
+ last: 'true',
119
+ index: '0',
120
+ context: 'interactive',
121
+ },
122
+ content: [
123
+ {
124
+ tag: 'query',
125
+ attrs: {},
126
+ content: [queryNode]
127
+ },
128
+ {
129
+ tag: 'list',
130
+ attrs: {},
131
+ content: userNodes
132
+ }
133
+ ]
134
+ }
135
+ ],
136
+ });
137
+ const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
138
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
139
+ const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
140
+ return users;
141
+ };
142
+ const onWhatsApp = async (...jids) => {
143
+ const query = { tag: 'contact', attrs: {} };
144
+ const list = jids.map((jid) => ({
145
+ tag: 'user',
146
+ attrs: {},
147
+ content: [{
148
+ tag: 'contact',
149
+ attrs: {},
150
+ content: jid,
151
+ }],
152
+ }));
153
+ const results = await interactiveQuery(list, query);
154
+ return results.map(user => {
155
+ const contact = (0, WABinary_1.getBinaryNodeChild)(user, 'contact');
156
+ return { exists: (contact === null || contact === void 0 ? void 0 : contact.attrs.type) === 'in', jid: user.attrs.jid };
157
+ }).filter(item => item.exists);
158
+ };
159
+ const fetchStatus = async (jid) => {
160
+ const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
161
+ if (result) {
162
+ const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
163
+ return {
164
+ status: status === null || status === void 0 ? void 0 : status.content.toString(),
165
+ setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
166
+ };
167
+ }
168
+ };
169
+ /** update the profile picture for yourself or a group */
170
+ const updateProfilePicture = async (jid, content) => {
171
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
172
+ await query({
173
+ tag: 'iq',
174
+ attrs: {
175
+ to: (0, WABinary_1.jidNormalizedUser)(jid),
176
+ type: 'set',
177
+ xmlns: 'w:profile:picture'
178
+ },
179
+ content: [
180
+ {
181
+ tag: 'picture',
182
+ attrs: { type: 'image' },
183
+ content: img
184
+ }
185
+ ]
186
+ });
187
+ };
188
+ /** remove the profile picture for yourself or a group */
189
+ const removeProfilePicture = async (jid) => {
190
+ await query({
191
+ tag: 'iq',
192
+ attrs: {
193
+ to: (0, WABinary_1.jidNormalizedUser)(jid),
194
+ type: 'set',
195
+ xmlns: 'w:profile:picture'
196
+ }
197
+ });
198
+ };
199
+ /** update the profile status for yourself */
200
+ const updateProfileStatus = async (status) => {
201
+ await query({
202
+ tag: 'iq',
203
+ attrs: {
204
+ to: WABinary_1.S_WHATSAPP_NET,
205
+ type: 'set',
206
+ xmlns: 'status'
207
+ },
208
+ content: [
209
+ {
210
+ tag: 'status',
211
+ attrs: {},
212
+ content: Buffer.from(status, 'utf-8')
213
+ }
214
+ ]
215
+ });
216
+ };
217
+ const updateProfileName = async (name) => {
218
+ await chatModify({ pushNameSetting: name }, '');
219
+ };
220
+ const fetchBlocklist = async () => {
221
+ const result = await query({
222
+ tag: 'iq',
223
+ attrs: {
224
+ xmlns: 'blocklist',
225
+ to: WABinary_1.S_WHATSAPP_NET,
226
+ type: 'get'
227
+ }
228
+ });
229
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
230
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
231
+ .map(n => n.attrs.jid);
232
+ };
233
+ const updateBlockStatus = async (jid, action) => {
234
+ await query({
235
+ tag: 'iq',
236
+ attrs: {
237
+ xmlns: 'blocklist',
238
+ to: WABinary_1.S_WHATSAPP_NET,
239
+ type: 'set'
240
+ },
241
+ content: [
242
+ {
243
+ tag: 'item',
244
+ attrs: {
245
+ action,
246
+ jid
247
+ }
248
+ }
249
+ ]
250
+ });
251
+ };
252
+ const getBusinessProfile = async (jid) => {
253
+ var _a, _b, _c, _d, _e, _f, _g;
254
+ const results = await query({
255
+ tag: 'iq',
256
+ attrs: {
257
+ to: 's.whatsapp.net',
258
+ xmlns: 'w:biz',
259
+ type: 'get'
260
+ },
261
+ content: [{
262
+ tag: 'business_profile',
263
+ attrs: { v: '244' },
264
+ content: [{
265
+ tag: 'profile',
266
+ attrs: { jid }
267
+ }]
268
+ }]
269
+ });
270
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
271
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
272
+ if (profiles) {
273
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
274
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
275
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
276
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
277
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
278
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
279
+ const businessHoursConfig = businessHours
280
+ ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
281
+ : undefined;
282
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
283
+ return {
284
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
285
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
286
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
287
+ website: websiteStr ? [websiteStr] : [],
288
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
289
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
290
+ 'business_hours': {
291
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
292
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
293
+ }
294
+ };
295
+ }
296
+ };
297
+ const cleanDirtyBits = async (type, fromTimestamp) => {
298
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
299
+ await sendNode({
300
+ tag: 'iq',
301
+ attrs: {
302
+ to: WABinary_1.S_WHATSAPP_NET,
303
+ type: 'set',
304
+ xmlns: 'urn:xmpp:whatsapp:dirty',
305
+ id: generateMessageTag(),
306
+ },
307
+ content: [
308
+ {
309
+ tag: 'clean',
310
+ attrs: {
311
+ type,
312
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
313
+ }
314
+ }
315
+ ]
316
+ });
317
+ };
318
+ const newAppStateChunkHandler = (isInitialSync) => {
319
+ return {
320
+ onMutation(mutation) {
321
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
322
+ }
323
+ };
324
+ };
325
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
326
+ // we use this to determine which events to fire
327
+ // otherwise when we resync from scratch -- all notifications will fire
328
+ const initialVersionMap = {};
329
+ const globalMutationMap = {};
330
+ await authState.keys.transaction(async () => {
331
+ var _a;
332
+ const collectionsToHandle = new Set(collections);
333
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
334
+ const attemptsMap = {};
335
+ // keep executing till all collections are done
336
+ // sometimes a single patch request will not return all the patches (God knows why)
337
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
338
+ while (collectionsToHandle.size) {
339
+ const states = {};
340
+ const nodes = [];
341
+ for (const name of collectionsToHandle) {
342
+ const result = await authState.keys.get('app-state-sync-version', [name]);
343
+ let state = result[name];
344
+ if (state) {
345
+ if (typeof initialVersionMap[name] === 'undefined') {
346
+ initialVersionMap[name] = state.version;
347
+ }
348
+ }
349
+ else {
350
+ state = (0, Utils_1.newLTHashState)();
351
+ }
352
+ states[name] = state;
353
+ logger.info(`resyncing ${name} from v${state.version}`);
354
+ nodes.push({
355
+ tag: 'collection',
356
+ attrs: {
357
+ name,
358
+ version: state.version.toString(),
359
+ // return snapshot if being synced from scratch
360
+ 'return_snapshot': (!state.version).toString()
361
+ }
362
+ });
363
+ }
364
+ const result = await query({
365
+ tag: 'iq',
366
+ attrs: {
367
+ to: WABinary_1.S_WHATSAPP_NET,
368
+ xmlns: 'w:sync:app:state',
369
+ type: 'set'
370
+ },
371
+ content: [
372
+ {
373
+ tag: 'sync',
374
+ attrs: {},
375
+ content: nodes
376
+ }
377
+ ]
378
+ });
379
+ // extract from binary node
380
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
381
+ for (const key in decoded) {
382
+ const name = key;
383
+ const { patches, hasMorePatches, snapshot } = decoded[name];
384
+ try {
385
+ if (snapshot) {
386
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
387
+ states[name] = newState;
388
+ Object.assign(globalMutationMap, mutationMap);
389
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
390
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
391
+ }
392
+ // only process if there are syncd patches
393
+ if (patches.length) {
394
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
395
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
396
+ logger.info(`synced ${name} to v${newState.version}`);
397
+ initialVersionMap[name] = newState.version;
398
+ Object.assign(globalMutationMap, mutationMap);
399
+ }
400
+ if (hasMorePatches) {
401
+ logger.info(`${name} has more patches...`);
402
+ }
403
+ else { // collection is done with sync
404
+ collectionsToHandle.delete(name);
405
+ }
406
+ }
407
+ catch (error) {
408
+ // if retry attempts overshoot
409
+ // or key not found
410
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
411
+ || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
412
+ || error.name === 'TypeError';
413
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
414
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
415
+ // increment number of retries
416
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
417
+ if (isIrrecoverableError) {
418
+ // stop retrying
419
+ collectionsToHandle.delete(name);
420
+ }
421
+ }
422
+ }
423
+ }
424
+ });
425
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
426
+ for (const key in globalMutationMap) {
427
+ onMutation(globalMutationMap[key]);
428
+ }
429
+ });
430
+ /**
431
+ * fetch the profile picture of a user/group
432
+ * type = "preview" for a low res picture
433
+ * type = "image for the high res picture"
434
+ */
435
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
436
+ var _a;
437
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
438
+ const result = await query({
439
+ tag: 'iq',
440
+ attrs: {
441
+ to: jid,
442
+ type: 'get',
443
+ xmlns: 'w:profile:picture'
444
+ },
445
+ content: [
446
+ { tag: 'picture', attrs: { type, query: 'url' } }
447
+ ]
448
+ }, timeoutMs);
449
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
450
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
451
+ };
452
+ const sendPresenceUpdate = async (type, toJid) => {
453
+ const me = authState.creds.me;
454
+ if (type === 'available' || type === 'unavailable') {
455
+ if (!me.name) {
456
+ logger.warn('no name present, ignoring presence update request...');
457
+ return;
458
+ }
459
+ ev.emit('connection.update', { isOnline: type === 'available' });
460
+ await sendNode({
461
+ tag: 'presence',
462
+ attrs: {
463
+ name: me.name,
464
+ type
465
+ }
466
+ });
467
+ }
468
+ else {
469
+ await sendNode({
470
+ tag: 'chatstate',
471
+ attrs: {
472
+ from: me.id,
473
+ to: toJid,
474
+ },
475
+ content: [
476
+ {
477
+ tag: type === 'recording' ? 'composing' : type,
478
+ attrs: type === 'recording' ? { media: 'audio' } : {}
479
+ }
480
+ ]
481
+ });
482
+ }
483
+ };
484
+ /**
485
+ * @param toJid the jid to subscribe to
486
+ * @param tcToken token for subscription, use if present
487
+ */
488
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
489
+ tag: 'presence',
490
+ attrs: {
491
+ to: toJid,
492
+ id: generateMessageTag(),
493
+ type: 'subscribe'
494
+ },
495
+ content: tcToken
496
+ ? [
497
+ {
498
+ tag: 'tctoken',
499
+ attrs: {},
500
+ content: tcToken
501
+ }
502
+ ]
503
+ : undefined
504
+ }));
505
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
506
+ var _a;
507
+ let presence;
508
+ const jid = attrs.from;
509
+ const participant = attrs.participant || attrs.from;
510
+ if (shouldIgnoreJid(jid)) {
511
+ return;
512
+ }
513
+ if (tag === 'presence') {
514
+ presence = {
515
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
516
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
517
+ };
518
+ }
519
+ else if (Array.isArray(content)) {
520
+ const [firstChild] = content;
521
+ let type = firstChild.tag;
522
+ if (type === 'paused') {
523
+ type = 'available';
524
+ }
525
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
526
+ type = 'recording';
527
+ }
528
+ presence = { lastKnownPresence: type };
529
+ }
530
+ else {
531
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
532
+ }
533
+ if (presence) {
534
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
535
+ }
536
+ };
537
+ const appPatch = async (patchCreate) => {
538
+ const name = patchCreate.type;
539
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
540
+ if (!myAppStateKeyId) {
541
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
542
+ }
543
+ let initial;
544
+ let encodeResult;
545
+ await processingMutex.mutex(async () => {
546
+ await authState.keys.transaction(async () => {
547
+ logger.debug({ patch: patchCreate }, 'applying app patch');
548
+ await resyncAppState([name], false);
549
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
550
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
551
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
552
+ const { patch, state } = encodeResult;
553
+ const node = {
554
+ tag: 'iq',
555
+ attrs: {
556
+ to: WABinary_1.S_WHATSAPP_NET,
557
+ type: 'set',
558
+ xmlns: 'w:sync:app:state'
559
+ },
560
+ content: [
561
+ {
562
+ tag: 'sync',
563
+ attrs: {},
564
+ content: [
565
+ {
566
+ tag: 'collection',
567
+ attrs: {
568
+ name,
569
+ version: (state.version - 1).toString(),
570
+ 'return_snapshot': 'false'
571
+ },
572
+ content: [
573
+ {
574
+ tag: 'patch',
575
+ attrs: {},
576
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
577
+ }
578
+ ]
579
+ }
580
+ ]
581
+ }
582
+ ]
583
+ };
584
+ await query(node);
585
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
586
+ });
587
+ });
588
+ if (config.emitOwnEvents) {
589
+ const { onMutation } = newAppStateChunkHandler(false);
590
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
591
+ for (const key in mutationMap) {
592
+ onMutation(mutationMap[key]);
593
+ }
594
+ }
595
+ };
596
+ /** sending abt props may fix QR scan fail if server expects */
597
+ const fetchAbt = async () => {
598
+ const abtNode = await query({
599
+ tag: 'iq',
600
+ attrs: {
601
+ to: WABinary_1.S_WHATSAPP_NET,
602
+ xmlns: 'abt',
603
+ type: 'get',
604
+ },
605
+ content: [
606
+ { tag: 'props', attrs: { protocol: '1' } }
607
+ ]
608
+ });
609
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(abtNode, 'props');
610
+ let props = {};
611
+ if (propsNode) {
612
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
613
+ }
614
+ logger.debug('fetched abt');
615
+ return props;
616
+ };
617
+ /** sending non-abt props may fix QR scan fail if server expects */
618
+ const fetchProps = async () => {
619
+ const resultNode = await query({
620
+ tag: 'iq',
621
+ attrs: {
622
+ to: WABinary_1.S_WHATSAPP_NET,
623
+ xmlns: 'w',
624
+ type: 'get',
625
+ },
626
+ content: [
627
+ { tag: 'props', attrs: {} }
628
+ ]
629
+ });
630
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
631
+ let props = {};
632
+ if (propsNode) {
633
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
634
+ }
635
+ logger.debug('fetched props');
636
+ return props;
637
+ };
638
+ /**
639
+ * modify a chat -- mark unread, read etc.
640
+ * lastMessages must be sorted in reverse chronologically
641
+ * requires the last messages till the last message received; required for archive & unread
642
+ */
643
+ const chatModify = (mod, jid) => {
644
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
645
+ return appPatch(patch);
646
+ };
647
+ /**
648
+ * Adds label for the chats
649
+ */
650
+ const addChatLabel = (jid, labelId) => {
651
+ return chatModify({
652
+ addChatLabel: {
653
+ labelId
654
+ }
655
+ }, jid);
656
+ };
657
+ /**
658
+ * Removes label for the chat
659
+ */
660
+ const removeChatLabel = (jid, labelId) => {
661
+ return chatModify({
662
+ removeChatLabel: {
663
+ labelId
664
+ }
665
+ }, jid);
666
+ };
667
+ /**
668
+ * Adds label for the message
669
+ */
670
+ const addMessageLabel = (jid, messageId, labelId) => {
671
+ return chatModify({
672
+ addMessageLabel: {
673
+ messageId,
674
+ labelId
675
+ }
676
+ }, jid);
677
+ };
678
+ /**
679
+ * Removes label for the message
680
+ */
681
+ const removeMessageLabel = (jid, messageId, labelId) => {
682
+ return chatModify({
683
+ removeMessageLabel: {
684
+ messageId,
685
+ labelId
686
+ }
687
+ }, jid);
688
+ };
689
+ /**
690
+ * queries need to be fired on connection open
691
+ * help ensure parity with WA Web
692
+ * */
693
+ const executeInitQueries = async () => {
694
+ await Promise.all([
695
+ fetchAbt(),
696
+ fetchProps(),
697
+ fetchBlocklist(),
698
+ fetchPrivacySettings(),
699
+ ]);
700
+ };
701
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
702
+ var _a, _b, _c;
703
+ ev.emit('messages.upsert', { messages: [msg], type });
704
+ if (!!msg.pushName) {
705
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
706
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
707
+ if (!msg.key.fromMe) {
708
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
709
+ }
710
+ // update our pushname too
711
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
712
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
713
+ }
714
+ }
715
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
716
+ const shouldProcessHistoryMsg = historyMsg
717
+ ? (shouldSyncHistoryMessage(historyMsg)
718
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
719
+ : false;
720
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
721
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
722
+ pendingAppStateSync = true;
723
+ }
724
+ await Promise.all([
725
+ (async () => {
726
+ if (historyMsg
727
+ && authState.creds.myAppStateKeyId) {
728
+ pendingAppStateSync = false;
729
+ await doAppStateSync();
730
+ }
731
+ })(),
732
+ (0, process_message_1.default)(msg, {
733
+ shouldProcessHistoryMsg,
734
+ ev,
735
+ creds: authState.creds,
736
+ keyStore: authState.keys,
737
+ logger,
738
+ options: config.options,
739
+ getMessage: config.getMessage,
740
+ })
741
+ ]);
742
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
743
+ && pendingAppStateSync) {
744
+ await doAppStateSync();
745
+ pendingAppStateSync = false;
746
+ }
747
+ async function doAppStateSync() {
748
+ if (!authState.creds.accountSyncCounter) {
749
+ logger.info('doing initial app state sync');
750
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
751
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
752
+ ev.emit('creds.update', { accountSyncCounter });
753
+ if (needToFlushWithAppStateSync) {
754
+ logger.debug('flushing with app state sync');
755
+ ev.flush();
756
+ }
757
+ }
758
+ }
759
+ });
760
+ ws.on('CB:presence', handlePresenceUpdate);
761
+ ws.on('CB:chatstate', handlePresenceUpdate);
762
+ ws.on('CB:ib,,dirty', async (node) => {
763
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
764
+ const type = attrs.type;
765
+ switch (type) {
766
+ case 'account_sync':
767
+ if (attrs.timestamp) {
768
+ let { lastAccountSyncTimestamp } = authState.creds;
769
+ if (lastAccountSyncTimestamp) {
770
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
771
+ }
772
+ lastAccountSyncTimestamp = +attrs.timestamp;
773
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
774
+ }
775
+ break;
776
+ case 'groups':
777
+ // handled in groups.ts
778
+ break;
779
+ default:
780
+ logger.info({ node }, 'received unknown sync');
781
+ break;
782
+ }
783
+ });
784
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
785
+ var _a;
786
+ if (connection === 'open') {
787
+ if (fireInitQueries) {
788
+ executeInitQueries()
789
+ .catch(error => onUnexpectedError(error, 'init queries'));
790
+ }
791
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
792
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
793
+ }
794
+ if (receivedPendingNotifications) {
795
+ // if we don't have the app state key
796
+ // we keep buffering events until we finally have
797
+ // the key and can sync the messages
798
+ if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
799
+ ev.buffer();
800
+ needToFlushWithAppStateSync = true;
801
+ }
802
+ }
803
+ });
804
+ return {
805
+ ...sock,
806
+ processingMutex,
807
+ fetchPrivacySettings,
808
+ upsertMessage,
809
+ appPatch,
810
+ sendPresenceUpdate,
811
+ presenceSubscribe,
812
+ profilePictureUrl,
813
+ onWhatsApp,
814
+ fetchBlocklist,
815
+ fetchStatus,
816
+ updateProfilePicture,
817
+ removeProfilePicture,
818
+ updateProfileStatus,
819
+ updateProfileName,
820
+ updateBlockStatus,
821
+ updateLastSeenPrivacy,
822
+ updateOnlinePrivacy,
823
+ updateProfilePicturePrivacy,
824
+ updateStatusPrivacy,
825
+ updateReadReceiptsPrivacy,
826
+ updateGroupsAddPrivacy,
827
+ updateDefaultDisappearingMode,
828
+ getBusinessProfile,
829
+ resyncAppState,
830
+ chatModify,
831
+ cleanDirtyBits,
832
+ addChatLabel,
833
+ removeChatLabel,
834
+ addMessageLabel,
835
+ removeMessageLabel
836
+ };
837
+ };
838
+ exports.makeChatsSocket = makeChatsSocket;