@queenanya/baileys 7.5.11 → 8.1.0

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