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