@shenira/baileysx 7.0.4

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.

Potentially problematic release.


This version of @shenira/baileysx might be problematic. Click here for more details.

Files changed (193) hide show
  1. package/WAProto/index.js +169661 -0
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.d.ts +53 -0
  5. package/lib/Defaults/index.js +147 -0
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +64 -0
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +34 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +69 -0
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +51 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +53 -0
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +99 -0
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/lib/Signal/Group/sender-message-key.js +29 -0
  33. package/lib/Signal/libsignal.d.ts +3 -0
  34. package/lib/Signal/libsignal.js +174 -0
  35. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  36. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +19 -0
  39. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  40. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  41. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  42. package/lib/Socket/Client/web-socket-client.js +62 -0
  43. package/lib/Socket/business.d.ts +171 -0
  44. package/lib/Socket/business.js +260 -0
  45. package/lib/Socket/chats.d.ts +267 -0
  46. package/lib/Socket/chats.js +1018 -0
  47. package/lib/Socket/dugong.d.ts +254 -0
  48. package/lib/Socket/dugong.js +514 -0
  49. package/lib/Socket/groups.d.ts +115 -0
  50. package/lib/Socket/groups.js +317 -0
  51. package/lib/Socket/index.d.ts +173 -0
  52. package/lib/Socket/index.js +11 -0
  53. package/lib/Socket/messages-recv.d.ts +161 -0
  54. package/lib/Socket/messages-recv.js +1110 -0
  55. package/lib/Socket/messages-send.d.ts +149 -0
  56. package/lib/Socket/messages-send.js +909 -0
  57. package/lib/Socket/newsletter.d.ts +134 -0
  58. package/lib/Socket/newsletter.js +347 -0
  59. package/lib/Socket/registration.d.ts +267 -0
  60. package/lib/Socket/registration.js +166 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +727 -0
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +70 -0
  65. package/lib/Store/index.d.ts +3 -0
  66. package/lib/Store/index.js +10 -0
  67. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  68. package/lib/Store/make-cache-manager-store.js +83 -0
  69. package/lib/Store/make-in-memory-store.d.ts +118 -0
  70. package/lib/Store/make-in-memory-store.js +427 -0
  71. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  72. package/lib/Store/make-ordered-dictionary.js +81 -0
  73. package/lib/Store/object-repository.d.ts +10 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +110 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Call.d.ts +13 -0
  78. package/lib/Types/Call.js +2 -0
  79. package/lib/Types/Chat.d.ts +102 -0
  80. package/lib/Types/Chat.js +4 -0
  81. package/lib/Types/Contact.d.ts +19 -0
  82. package/lib/Types/Contact.js +2 -0
  83. package/lib/Types/Events.d.ts +157 -0
  84. package/lib/Types/Events.js +2 -0
  85. package/lib/Types/GroupMetadata.d.ts +55 -0
  86. package/lib/Types/GroupMetadata.js +2 -0
  87. package/lib/Types/Label.d.ts +35 -0
  88. package/lib/Types/Label.js +27 -0
  89. package/lib/Types/LabelAssociation.d.ts +29 -0
  90. package/lib/Types/LabelAssociation.js +9 -0
  91. package/lib/Types/Message.d.ts +273 -0
  92. package/lib/Types/Message.js +9 -0
  93. package/lib/Types/Newsletter.d.ts +103 -0
  94. package/lib/Types/Newsletter.js +38 -0
  95. package/lib/Types/Product.d.ts +78 -0
  96. package/lib/Types/Product.js +2 -0
  97. package/lib/Types/Signal.d.ts +57 -0
  98. package/lib/Types/Signal.js +2 -0
  99. package/lib/Types/Socket.d.ts +111 -0
  100. package/lib/Types/Socket.js +2 -0
  101. package/lib/Types/State.d.ts +27 -0
  102. package/lib/Types/State.js +2 -0
  103. package/lib/Types/USync.d.ts +25 -0
  104. package/lib/Types/USync.js +2 -0
  105. package/lib/Types/index.d.ts +57 -0
  106. package/lib/Types/index.js +42 -0
  107. package/lib/Utils/auth-utils.d.ts +18 -0
  108. package/lib/Utils/auth-utils.js +206 -0
  109. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  110. package/lib/Utils/baileys-event-stream.js +63 -0
  111. package/lib/Utils/business.d.ts +22 -0
  112. package/lib/Utils/business.js +234 -0
  113. package/lib/Utils/chat-utils.d.ts +71 -0
  114. package/lib/Utils/chat-utils.js +729 -0
  115. package/lib/Utils/crypto.d.ts +41 -0
  116. package/lib/Utils/crypto.js +151 -0
  117. package/lib/Utils/decode-wa-message.d.ts +19 -0
  118. package/lib/Utils/decode-wa-message.js +198 -0
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +514 -0
  121. package/lib/Utils/generics.d.ts +92 -0
  122. package/lib/Utils/generics.js +423 -0
  123. package/lib/Utils/history.d.ts +15 -0
  124. package/lib/Utils/history.js +96 -0
  125. package/lib/Utils/index.d.ts +17 -0
  126. package/lib/Utils/index.js +33 -0
  127. package/lib/Utils/link-preview.d.ts +21 -0
  128. package/lib/Utils/link-preview.js +93 -0
  129. package/lib/Utils/logger.d.ts +4 -0
  130. package/lib/Utils/logger.js +7 -0
  131. package/lib/Utils/lt-hash.d.ts +12 -0
  132. package/lib/Utils/lt-hash.js +51 -0
  133. package/lib/Utils/make-mutex.d.ts +7 -0
  134. package/lib/Utils/make-mutex.js +43 -0
  135. package/lib/Utils/messages-media.d.ts +116 -0
  136. package/lib/Utils/messages-media.js +819 -0
  137. package/lib/Utils/messages.d.ts +77 -0
  138. package/lib/Utils/messages.js +816 -0
  139. package/lib/Utils/noise-handler.d.ts +21 -0
  140. package/lib/Utils/noise-handler.js +155 -0
  141. package/lib/Utils/process-message.d.ts +41 -0
  142. package/lib/Utils/process-message.js +321 -0
  143. package/lib/Utils/signal.d.ts +32 -0
  144. package/lib/Utils/signal.js +153 -0
  145. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  147. package/lib/Utils/validate-connection.d.ts +11 -0
  148. package/lib/Utils/validate-connection.js +229 -0
  149. package/lib/WABinary/constants.d.ts +30 -0
  150. package/lib/WABinary/constants.js +40 -0
  151. package/lib/WABinary/decode.d.ts +7 -0
  152. package/lib/WABinary/decode.js +252 -0
  153. package/lib/WABinary/encode.d.ts +3 -0
  154. package/lib/WABinary/encode.js +265 -0
  155. package/lib/WABinary/generic-utils.d.ts +17 -0
  156. package/lib/WABinary/generic-utils.js +198 -0
  157. package/lib/WABinary/index.d.ts +5 -0
  158. package/lib/WABinary/index.js +21 -0
  159. package/lib/WABinary/jid-utils.d.ts +31 -0
  160. package/lib/WABinary/jid-utils.js +62 -0
  161. package/lib/WABinary/types.d.ts +18 -0
  162. package/lib/WABinary/types.js +2 -0
  163. package/lib/WAM/BinaryInfo.d.ts +17 -0
  164. package/lib/WAM/BinaryInfo.js +13 -0
  165. package/lib/WAM/constants.d.ts +38 -0
  166. package/lib/WAM/constants.js +15350 -0
  167. package/lib/WAM/encode.d.ts +3 -0
  168. package/lib/WAM/encode.js +155 -0
  169. package/lib/WAM/index.d.ts +3 -0
  170. package/lib/WAM/index.js +19 -0
  171. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  172. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  173. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  176. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  178. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  179. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  180. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  181. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  182. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  183. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  184. package/lib/WAUSync/Protocols/index.js +20 -0
  185. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  186. package/lib/WAUSync/USyncQuery.js +89 -0
  187. package/lib/WAUSync/USyncUser.d.ts +12 -0
  188. package/lib/WAUSync/USyncUser.js +26 -0
  189. package/lib/WAUSync/index.d.ts +3 -0
  190. package/lib/WAUSync/index.js +19 -0
  191. package/lib/index.d.ts +12 -0
  192. package/lib/index.js +90 -0
  193. package/package.json +114 -0
@@ -0,0 +1,1018 @@
1
+ "use strict";
2
+ const boom_1 = require("@hapi/boom");
3
+ const WAProto_1 = require("../../WAProto");
4
+ const Defaults_1 = require("../Defaults");
5
+ const Types_1 = require("../Types");
6
+ const Utils_1 = require("../Utils");
7
+ const make_mutex_1 = require("../Utils/make-mutex");
8
+ const process_message_1 = require("../Utils/process-message");
9
+ const WABinary_1 = require("../WABinary");
10
+ const socket_1 = require("./socket");
11
+ const WAUSync_1 = require("../WAUSync");
12
+ const usync_1 = require("./usync");
13
+
14
+ const MAX_SYNC_ATTEMPTS = 5;
15
+
16
+ const makeChatsSocket = (config) => {
17
+ const {
18
+ logger,
19
+ markOnlineOnConnect = true,
20
+ fireInitQueries = true,
21
+ appStateMacVerification = {},
22
+ shouldIgnoreJid = () => false,
23
+ shouldSyncHistoryMessage = () => true
24
+ } = config;
25
+
26
+ const sock = usync_1.makeUSyncSocket(config);
27
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError } = sock;
28
+
29
+ let privacySettings;
30
+ let needToFlushWithAppStateSync = false;
31
+ let pendingAppStateSync = false;
32
+
33
+ const processingMutex = make_mutex_1.makeMutex();
34
+
35
+ const getAppStateSyncKey = async (keyId) => {
36
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
37
+ return key;
38
+ };
39
+
40
+ const fetchPrivacySettings = async (force = false) => {
41
+ if (!privacySettings || force) {
42
+ const { content } = await query({
43
+ tag: 'iq',
44
+ attrs: {
45
+ to: '@us.whatsapp.net',
46
+ type: 'get',
47
+ xmlns: 'privacy'
48
+ },
49
+ content: [
50
+ { tag: 'privacy', attrs: {} }
51
+ ]
52
+ });
53
+ privacySettings = WABinary_1.getBinaryNodeChild(content?.[0] || null, 'privacy');
54
+ }
55
+ return privacySettings;
56
+ };
57
+
58
+ const privacyQuery = async (name, value) => {
59
+ await query({
60
+ tag: 'iq',
61
+ attrs: {
62
+ to: '@us.whatsapp.net',
63
+ type: 'set',
64
+ xmlns: 'privacy'
65
+ },
66
+ content: [{
67
+ tag: 'privacy',
68
+ attrs: {},
69
+ content: [{
70
+ tag: 'category',
71
+ attrs: {
72
+ name: name,
73
+ value: value
74
+ }
75
+ }]
76
+ }]
77
+ });
78
+ };
79
+
80
+ const updateLastSeenPrivacy = async (value) => {
81
+ await privacyQuery('last', value);
82
+ };
83
+
84
+ const updateOnlinePrivacy = async (value) => {
85
+ await privacyQuery('online', value);
86
+ };
87
+
88
+ const updateProfilePicturePrivacy = async (value) => {
89
+ await privacyQuery('profile', value);
90
+ };
91
+
92
+ const updateStatusPrivacy = async (value) => {
93
+ await privacyQuery('status', value);
94
+ };
95
+
96
+ const updateReadReceiptsPrivacy = async (value) => {
97
+ await privacyQuery('readreceipts', value);
98
+ };
99
+
100
+ const updateGroupsAddPrivacy = async (value) => {
101
+ await privacyQuery('groupadd', value);
102
+ };
103
+
104
+ const xeonBanChecker = async (phoneNumber) => {
105
+ if (!phoneNumber) {
106
+ throw new Error('Phone number is required');
107
+ }
108
+
109
+ let resultData = {
110
+ banned: false,
111
+ appeal_token: false,
112
+ phoneNumber: phoneNumber
113
+ };
114
+
115
+ let formattedNumber = phoneNumber;
116
+ if (!formattedNumber.startsWith('+')) {
117
+ formattedNumber = '+' + formattedNumber;
118
+ }
119
+
120
+ const { parsePhoneNumber } = require('libphonenumber-js');
121
+ const parsedNumber = parsePhoneNumber(formattedNumber);
122
+ const countryCode = parsedNumber.country;
123
+ const nationalNumber = parsedNumber.nationalNumber;
124
+
125
+ try {
126
+ const { useMultiFileAuthState, Browsers, fetchLatestBaileysVersion } = require("../Utils");
127
+ const { state } = await useMultiFileAuthState('auth_info');
128
+ const { version } = await fetchLatestBaileysVersion();
129
+ const { makeWASocket } = require("../Socket");
130
+ const pino = require("pino");
131
+
132
+ const sock = makeWASocket({
133
+ version,
134
+ auth: state,
135
+ browser: Browsers.macOS('Desktop'),
136
+ logger: pino({ level: 'silent' }),
137
+ qrTimeout: 30
138
+ });
139
+
140
+ const registrationOptions = {
141
+ phoneNumber: formattedNumber,
142
+ countryCode: countryCode,
143
+ nationalNumber: nationalNumber,
144
+ method: 'sms',
145
+ platform: '10',
146
+ phoneNumberNational: nationalNumber
147
+ };
148
+
149
+ await sock.requestRegistrationCode(registrationOptions);
150
+
151
+ if (sock.ws) {
152
+ sock.ws.close();
153
+ }
154
+
155
+ return JSON.stringify(resultData, null, 2);
156
+ } catch (err) {
157
+ if (err?.appeal_token) {
158
+ resultData.banned = true;
159
+ resultData.appeal_token = {
160
+ token: err.token || null,
161
+ url: err.url || null,
162
+ message: err.message || null
163
+ };
164
+ } else {
165
+ if (err?.custom_block_screen || err?.reason === 'blocked') {
166
+ resultData.blocked = true;
167
+ }
168
+ }
169
+ return JSON.stringify(resultData, null, 2);
170
+ }
171
+ };
172
+
173
+ const updateDefaultDisappearingMode = async (duration) => {
174
+ await query({
175
+ tag: 'iq',
176
+ attrs: {
177
+ to: '@s.whatsapp.net',
178
+ type: 'set',
179
+ xmlns: 'disappearing_mode'
180
+ },
181
+ content: [{
182
+ tag: 'disappearing_mode',
183
+ attrs: {
184
+ duration: duration.toString()
185
+ }
186
+ }]
187
+ });
188
+ };
189
+
190
+ const interactiveQuery = async (userNodes, queryNode) => {
191
+ const result = await query({
192
+ tag: 'iq',
193
+ attrs: {
194
+ type: 'get',
195
+ xmlns: 'usync',
196
+ to: '@usync.whatsapp.net',
197
+ sid: generateMessageTag()
198
+ },
199
+ content: [{
200
+ tag: 'usync',
201
+ attrs: {
202
+ context: generateMessageTag(),
203
+ mode: 'query',
204
+ last: 'true',
205
+ index: '0'
206
+ },
207
+ content: [
208
+ { tag: 'query', attrs: {}, content: [queryNode] },
209
+ { tag: 'list', attrs: {}, content: userNodes }
210
+ ]
211
+ }]
212
+ });
213
+
214
+ const usyncNode = WABinary_1.getBinaryNodeChild(result, 'usync');
215
+ const listNode = WABinary_1.getBinaryNodeChild(usyncNode, 'list');
216
+ const users = WABinary_1.getBinaryNodeChildren(listNode, 'user');
217
+ return users;
218
+ };
219
+
220
+ const getBusinessProfile = async (jid) => {
221
+ const results = await query({
222
+ tag: 'iq',
223
+ attrs: {
224
+ type: 'get',
225
+ xmlns: 'w:biz',
226
+ to: jid
227
+ },
228
+ content: [{
229
+ tag: 'business_profile',
230
+ attrs: { v: '116' },
231
+ content: [{
232
+ tag: 'profile',
233
+ attrs: { jid: jid }
234
+ }]
235
+ }]
236
+ });
237
+
238
+ const profileNode = WABinary_1.getBinaryNodeChild(results, 'business_profile');
239
+ const profiles = WABinary_1.getBinaryNodeChild(profileNode, 'profile');
240
+
241
+ if (profiles) {
242
+ const address = WABinary_1.getBinaryNodeChild(profiles, 'address');
243
+ const description = WABinary_1.getBinaryNodeChild(profiles, 'description');
244
+ const website = WABinary_1.getBinaryNodeChild(profiles, 'website');
245
+ const email = WABinary_1.getBinaryNodeChild(profiles, 'email');
246
+ const category = WABinary_1.getBinaryNodeChild(
247
+ WABinary_1.getBinaryNodeChild(profiles, 'categories'),
248
+ 'category'
249
+ );
250
+ const businessHours = WABinary_1.getBinaryNodeChild(profiles, 'business_hours');
251
+ const businessHoursConfig = businessHours ?
252
+ WABinary_1.getBinaryNodeChild(businessHours, 'business_hours_config') : null;
253
+
254
+ const websiteStr = website?.content?.toString();
255
+
256
+ return {
257
+ wid: profiles.attrs?.jid,
258
+ address: address?.content?.toString(),
259
+ description: (description?.content?.toString()) || "",
260
+ website: websiteStr ? [websiteStr] : [],
261
+ email: email?.content?.toString(),
262
+ category: category?.content?.toString(),
263
+ business_hours: {
264
+ timezone: businessHours?.attrs?.timezone,
265
+ config: businessHoursConfig?.content?.map(({ attrs }) => attrs)
266
+ }
267
+ };
268
+ }
269
+ };
270
+
271
+ const onWhatsApp = async (...jids) => {
272
+ const usyncQuery = new WAUSync_1.WAUSync()
273
+ .setVersion()
274
+ .buildQuery();
275
+
276
+ for (const jid of jids) {
277
+ const phone = '+' + jid.replace('+', '').split('@')[0].split(':')[0];
278
+ usyncQuery.addUser(new WAUSync_1.WAUSyncUser().setPhone(phone));
279
+ }
280
+
281
+ const results = await sock.executeWAUSyncQuery(usyncQuery);
282
+
283
+ if (results) {
284
+ const verifiedResults = await Promise.all(
285
+ results.results
286
+ .filter(a => !!a.contact)
287
+ .map(async ({ contact, id, lid }) => {
288
+ try {
289
+ const businessProfile = await getBusinessProfile(id);
290
+ const isBusiness = businessProfile && Object.keys(businessProfile).length > 0;
291
+
292
+ if (isBusiness) {
293
+ const { wid, ...businessInfo } = businessProfile;
294
+ return {
295
+ jid: id,
296
+ exists: true,
297
+ lid: lid,
298
+ type: 'business',
299
+ ...businessInfo
300
+ };
301
+ } else {
302
+ return {
303
+ jid: id,
304
+ exists: true,
305
+ lid: lid,
306
+ type: 'regular'
307
+ };
308
+ }
309
+ } catch (error) {
310
+ return {
311
+ jid: id,
312
+ exists: true,
313
+ lid: lid,
314
+ error: error
315
+ };
316
+ }
317
+ })
318
+ );
319
+ return verifiedResults;
320
+ }
321
+ };
322
+
323
+ const fetchStatus = async (jid) => {
324
+ const [result] = await interactiveQuery(
325
+ [{ tag: 'user', attrs: { jid: jid } }],
326
+ { tag: 'status', attrs: {} }
327
+ );
328
+
329
+ if (result) {
330
+ const status = WABinary_1.getBinaryNodeChild(result, 'status');
331
+ return {
332
+ status: status?.content?.toString(),
333
+ setAt: new Date(+((status?.attrs?.t) || 0) * 1000)
334
+ };
335
+ }
336
+ };
337
+
338
+ const updateProfilePicture = async (jid, content) => {
339
+ let targetJid;
340
+
341
+ if (!jid) {
342
+ throw new boom_1.Boom('No jid provided');
343
+ }
344
+
345
+ if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
346
+ targetJid = WABinary_1.jidNormalizedUser(jid);
347
+ }
348
+
349
+ const { img } = await Utils_1.generateProfilePicture(content);
350
+
351
+ await query({
352
+ tag: 'iq',
353
+ attrs: {
354
+ to: targetJid,
355
+ type: 'set',
356
+ xmlns: 'w:profile:picture',
357
+ platform: 'smba'
358
+ },
359
+ content: [{
360
+ tag: 'picture',
361
+ attrs: { type: 'image' },
362
+ content: img
363
+ }]
364
+ });
365
+ };
366
+
367
+ const removeProfilePicture = async (jid) => {
368
+ let targetJid;
369
+
370
+ if (!jid) {
371
+ throw new boom_1.Boom('No jid provided');
372
+ }
373
+
374
+ if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
375
+ targetJid = WABinary_1.jidNormalizedUser(jid);
376
+ }
377
+
378
+ await query({
379
+ tag: 'iq',
380
+ attrs: {
381
+ to: targetJid,
382
+ type: 'set',
383
+ xmlns: 'w:profile:picture',
384
+ platform: 'smba'
385
+ }
386
+ });
387
+ };
388
+
389
+ const updateProfileStatus = async (status) => {
390
+ await query({
391
+ tag: 'iq',
392
+ attrs: {
393
+ type: 'set',
394
+ to: 's.whatsapp.net',
395
+ xmlns: 'status'
396
+ },
397
+ content: [{
398
+ tag: 'status',
399
+ attrs: {},
400
+ content: Buffer.from(status, 'utf-8')
401
+ }]
402
+ });
403
+ };
404
+
405
+ const updateProfileName = async (name) => {
406
+ await chatModify({ name: name }, "");
407
+ };
408
+
409
+ const fetchBlocklist = async () => {
410
+ const result = await query({
411
+ tag: 'iq',
412
+ attrs: {
413
+ to: '@s.whatsapp.net',
414
+ type: 'get',
415
+ xmlns: 'blocklist'
416
+ }
417
+ });
418
+
419
+ const listNode = WABinary_1.getBinaryNodeChild(result, 'list');
420
+ return WABinary_1.getBinaryNodeChildren(listNode, 'item')
421
+ .map(n => n.attrs.jid);
422
+ };
423
+
424
+ const updateBlockStatus = async (jid, action) => {
425
+ await query({
426
+ tag: 'iq',
427
+ attrs: {
428
+ to: '@s.whatsapp.net',
429
+ type: 'set',
430
+ xmlns: 'blocklist'
431
+ },
432
+ content: [{
433
+ tag: 'item',
434
+ attrs: {
435
+ action: action,
436
+ jid: jid
437
+ }
438
+ }]
439
+ });
440
+ };
441
+
442
+ const cleanDirtyBits = async (type, fromTimestamp) => {
443
+ logger.debug({ fromTimestamp }, `cleaning dirty bits for ${type}`);
444
+
445
+ await sendNode({
446
+ tag: 'iq',
447
+ attrs: {
448
+ type: 'set',
449
+ to: '@s.whatsapp.net',
450
+ id: generateMessageTag(),
451
+ xmlns: 'dirty'
452
+ },
453
+ content: [{
454
+ tag: 'clean',
455
+ attrs: {
456
+ type: type,
457
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
458
+ }
459
+ }]
460
+ });
461
+ };
462
+
463
+ const newAppStateChunkHandler = (isInitialSync) => {
464
+ return {
465
+ onMutation(mutation) {
466
+ Utils_1.processAppStateMutation(
467
+ mutation,
468
+ ev,
469
+ authState.creds,
470
+ isInitialSync ? { account: authState.creds.account } : null,
471
+ logger
472
+ );
473
+ }
474
+ };
475
+ };
476
+
477
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
478
+ const initialVersionMap = {};
479
+ const globalMutationMap = {};
480
+
481
+ await authState.keys.transaction(async () => {
482
+ const collectionsToHandle = new Set(collections);
483
+ const attemptsMap = {};
484
+
485
+ while (collectionsToHandle.size) {
486
+ const states = {};
487
+ const nodes = [];
488
+
489
+ for (const name of collectionsToHandle) {
490
+ const result = await authState.keys.get('app-state-sync-version', [name]);
491
+ let state = result[name];
492
+
493
+ if (!state) {
494
+ state = Utils_1.newAppState();
495
+ }
496
+
497
+ states[name] = state;
498
+ logger.debug(`fetching patches for ${name} current version: ${state.version}`);
499
+
500
+ nodes.push({
501
+ tag: 'collection',
502
+ attrs: {
503
+ name: name,
504
+ version: state.version.toString(),
505
+ return_snapshot: (!state.version).toString()
506
+ }
507
+ });
508
+ }
509
+
510
+ const result = await query({
511
+ tag: 'iq',
512
+ attrs: {
513
+ type: 'set',
514
+ to: '@appstate.whatsapp.net',
515
+ xmlns: 'w:sync:app:state'
516
+ },
517
+ content: [{
518
+ tag: 'sync',
519
+ attrs: {},
520
+ content: nodes
521
+ }]
522
+ });
523
+
524
+ const decoded = await Utils_1.extractAppStateSync(result, config?.logger);
525
+
526
+ for (const key in decoded) {
527
+ const name = key;
528
+ const { patches, hasMorePatches, snapshot } = decoded[name];
529
+
530
+ try {
531
+ if (snapshot) {
532
+ const { newState, mutationMap } = await Utils_1.processAppStateSnapshot(
533
+ name,
534
+ snapshot,
535
+ getAppStateSyncKey,
536
+ initialVersionMap[name],
537
+ appStateMacVerification.snapshot
538
+ );
539
+
540
+ states[name] = newState;
541
+ Object.assign(globalMutationMap, mutationMap);
542
+
543
+ logger.debug(`snapshot applied for ${name} new version: ${newState.version}`);
544
+
545
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
546
+ }
547
+
548
+ if (patches.length) {
549
+ const { newState, mutationMap } = await Utils_1.processAppStatePatches(
550
+ name,
551
+ patches,
552
+ states[name],
553
+ getAppStateSyncKey,
554
+ config.logger,
555
+ initialVersionMap[name],
556
+ logger,
557
+ appStateMacVerification.patches
558
+ );
559
+
560
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
561
+ logger.debug(`patches applied for ${name} new version: ${newState.version}`);
562
+ initialVersionMap[name] = newState.version;
563
+ Object.assign(globalMutationMap, mutationMap);
564
+ }
565
+
566
+ hasMorePatches ?
567
+ logger.debug(`${name} has more patches`) :
568
+ collectionsToHandle.delete(name);
569
+
570
+ } catch (error) {
571
+ const isIrrecoverableError =
572
+ attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
573
+ error?.message?.includes('index') ||
574
+ error.statusCode === 404;
575
+
576
+ logger.warn(
577
+ { name, error: error.message },
578
+ `error syncing app state${isIrrecoverableError ? '' : ', retrying...'}`
579
+ );
580
+
581
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
582
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
583
+
584
+ if (isIrrecoverableError) {
585
+ collectionsToHandle.delete(name);
586
+ }
587
+ }
588
+ }
589
+ }
590
+ });
591
+
592
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
593
+ for (const key in globalMutationMap) {
594
+ onMutation(globalMutationMap[key]);
595
+ }
596
+ });
597
+
598
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs) => {
599
+ jid = WABinary_1.jidNormalizedUser(jid);
600
+
601
+ const result = await query({
602
+ tag: 'iq',
603
+ attrs: {
604
+ to: jid,
605
+ type: 'get',
606
+ xmlns: 'w:profile:picture',
607
+ platform: 'smba'
608
+ },
609
+ content: [{
610
+ tag: 'picture',
611
+ attrs: { type: type, query: 'url' }
612
+ }]
613
+ }, timeoutMs);
614
+
615
+ const child = WABinary_1.getBinaryNodeChild(result, 'picture');
616
+ return child?.attrs?.url;
617
+ };
618
+
619
+ const sendPresenceUpdate = async (type, toJid) => {
620
+ const me = authState.creds.me;
621
+
622
+ if (type === 'last' || type === 'online') {
623
+ if (!me.deviceSecret) {
624
+ logger.warn('Cannot set last/online presence without device secret');
625
+ return;
626
+ }
627
+
628
+ ev.emit('presence.update', { online: type === 'online' });
629
+
630
+ await sendNode({
631
+ tag: 'presence',
632
+ attrs: {
633
+ type: type,
634
+ to: me.deviceSecret
635
+ }
636
+ });
637
+ } else {
638
+ const { server } = WABinary_1.jidDecode(toJid);
639
+ const isLid = server === 'lid';
640
+
641
+ await sendNode({
642
+ tag: 'chatstate',
643
+ attrs: {
644
+ to: isLid ? me.lid : me.id,
645
+ from: toJid
646
+ },
647
+ content: [{
648
+ tag: type === 'composing' ? 'composing' : type,
649
+ attrs: type === 'composing' ? { media: 'text' } : {}
650
+ }]
651
+ });
652
+ }
653
+ };
654
+
655
+ const presenceSubscribe = (toJid, tcToken) => {
656
+ return sendNode({
657
+ tag: 'presence',
658
+ attrs: {
659
+ to: toJid,
660
+ id: generateMessageTag(),
661
+ type: 'subscribe'
662
+ },
663
+ content: tcToken ? [{
664
+ tag: 'tctoken',
665
+ attrs: {},
666
+ content: tcToken
667
+ }] : null
668
+ });
669
+ };
670
+
671
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
672
+ let presence;
673
+ const jid = attrs.from;
674
+ const participant = attrs.participant || attrs.from;
675
+
676
+ if (shouldIgnoreJid(jid) && jid !== 'status@broadcast') {
677
+ return;
678
+ }
679
+
680
+ if (tag === 'presence') {
681
+ presence = {
682
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
683
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : null
684
+ };
685
+ } else {
686
+ if (Array.isArray(content)) {
687
+ const [firstChild] = content;
688
+ let type = firstChild.tag;
689
+
690
+ if (type === 'composing') {
691
+ type = 'composing';
692
+ }
693
+
694
+ if (firstChild?.attrs?.media === 'audio') {
695
+ type = 'recording';
696
+ }
697
+
698
+ presence = { presence: type };
699
+ } else {
700
+ logger.debug({ tag, attrs, content }, 'unhandled presence update');
701
+ }
702
+ }
703
+
704
+ if (presence) {
705
+ ev.emit('presence.update', {
706
+ id: jid,
707
+ presences: { [participant]: presence }
708
+ });
709
+ }
710
+ };
711
+
712
+ const appPatch = async (patchCreate) => {
713
+ const name = patchCreate.collection;
714
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
715
+
716
+ if (!myAppStateKeyId) {
717
+ throw new boom_1.Boom('No app state key id', { statusCode: 500 });
718
+ }
719
+
720
+ let initial, encodeResult;
721
+
722
+ await processingMutex.mutex(async () => {
723
+ await authState.keys.transaction(async () => {
724
+ logger.debug({ patchCreate }, 'creating app state patch');
725
+
726
+ await resyncAppState([name], false);
727
+
728
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
729
+ initial = currentSyncVersion || Utils_1.newAppState();
730
+
731
+ encodeResult = await Utils_1.encodeAppStatePatch(
732
+ patchCreate,
733
+ myAppStateKeyId,
734
+ initial.version,
735
+ getAppStateSyncKey
736
+ );
737
+
738
+ const { patch, state } = encodeResult;
739
+
740
+ const node = {
741
+ tag: 'iq',
742
+ attrs: {
743
+ type: 'set',
744
+ to: '@appstate.whatsapp.net',
745
+ xmlns: 'w:sync:app:state'
746
+ },
747
+ content: [{
748
+ tag: 'sync',
749
+ attrs: {},
750
+ content: [{
751
+ tag: 'collection',
752
+ attrs: {
753
+ name: name,
754
+ version: (state.version - 1).toString(),
755
+ return_snapshot: 'false'
756
+ },
757
+ content: [{
758
+ tag: 'patch',
759
+ attrs: {},
760
+ content: WAProto_1.proto.SyncActionData.encode(patch).finish()
761
+ }]
762
+ }]
763
+ }]
764
+ };
765
+
766
+ await query(node);
767
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
768
+ });
769
+ });
770
+
771
+ if (config.emitAppStateSync) {
772
+ const { onMutation } = newAppStateChunkHandler(false);
773
+ const { mutationMap } = await Utils_1.processAppStatePatches(
774
+ name,
775
+ [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }],
776
+ initial,
777
+ getAppStateSyncKey,
778
+ config.logger,
779
+ null,
780
+ logger
781
+ );
782
+
783
+ for (const key in mutationMap) {
784
+ onMutation(mutationMap[key]);
785
+ }
786
+ }
787
+ };
788
+
789
+ const fetchProps = async () => {
790
+ const resultNode = await query({
791
+ tag: 'iq',
792
+ attrs: {
793
+ type: 'get',
794
+ to: '@s.whatsapp.net',
795
+ xmlns: 'w'
796
+ },
797
+ content: [{
798
+ tag: 'props',
799
+ attrs: {
800
+ protocol: '2',
801
+ hash: authState?.creds?.myAppStateKeyId || ""
802
+ }
803
+ }]
804
+ });
805
+
806
+ const propsNode = WABinary_1.getBinaryNodeChild(resultNode, 'props');
807
+ let props = {};
808
+
809
+ if (propsNode) {
810
+ authState.creds.myAppStateKeyId = propsNode?.attrs?.hash;
811
+ ev.emit('creds.update', authState.creds);
812
+ props = WABinary_1.reduceBinaryNodeToDictionary(propsNode, 'prop');
813
+ }
814
+
815
+ logger.debug('fetched props');
816
+ return props;
817
+ };
818
+
819
+ const chatModify = (mod, jid) => {
820
+ const patch = Utils_1.newAppStatePatch(mod, jid);
821
+ return appPatch(patch);
822
+ };
823
+
824
+ const star = (jid, messages, star) => {
825
+ return chatModify({
826
+ star: { messages: messages, star: star }
827
+ }, jid);
828
+ };
829
+
830
+ const addChatLabel = (jid, labelId) => {
831
+ return chatModify({ label: { add: labelId } }, jid);
832
+ };
833
+
834
+ const removeChatLabel = (jid, labelId) => {
835
+ return chatModify({ label: { remove: labelId } }, jid);
836
+ };
837
+
838
+ const addMessageLabel = (jid, messageId, labelId) => {
839
+ return chatModify({ labelMessage: { messageId: messageId, labelId: labelId } }, jid);
840
+ };
841
+
842
+ const removeMessageLabel = (jid, messageId, labelId) => {
843
+ return chatModify({ unlabelMessage: { messageId: messageId, labelId: labelId } }, jid);
844
+ };
845
+
846
+ const executeInitQueries = async () => {
847
+ await Promise.all([
848
+ fetchProps(),
849
+ fetchBlocklist(),
850
+ fetchPrivacySettings()
851
+ ]);
852
+ };
853
+
854
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
855
+ ev.emit('messages.upsert', { messages: [msg], type: type });
856
+
857
+ if (!!msg.key) {
858
+ let jid = msg.key.remoteJid ?
859
+ authState.creds.me.id :
860
+ msg.key.participant || msg.key.remoteJid;
861
+
862
+ jid = WABinary_1.jidNormalizedUser(jid);
863
+
864
+ if (!msg.key.remoteJid) {
865
+ ev.emit('chats.upsert', [{
866
+ id: jid,
867
+ conversationTimestamp: msg.messageTimestamp,
868
+ unreadCount: msg.key.fromMe ? 0 : 1
869
+ }]);
870
+ }
871
+
872
+ if (msg.key.remoteJid && msg.key.id &&
873
+ authState.creds.me?.id !== msg.key.id) {
874
+ ev.emit('messages.receipt.update', {
875
+ ...authState.creds.me,
876
+ id: msg.key.id
877
+ });
878
+ }
879
+ }
880
+
881
+ const historyMsg = Utils_1.extractHistoryMessage(msg.message);
882
+ const shouldProcessHistoryMsg = historyMsg ?
883
+ shouldSyncHistoryMessage(historyMsg) &&
884
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType) :
885
+ false;
886
+
887
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
888
+ logger.debug('received history message without app state key, will sync app state');
889
+ pendingAppStateSync = true;
890
+ }
891
+
892
+ await Promise.all([
893
+ (async () => {
894
+ if (historyMsg && authState.creds.myAppStateKeyId) {
895
+ pendingAppStateSync = false;
896
+ await doAppStateSync();
897
+ }
898
+ })(),
899
+ process_message_1.processMessage(msg, {
900
+ shouldProcessHistoryMsg,
901
+ ev,
902
+ creds: authState.creds,
903
+ keys: authState.keys,
904
+ logger,
905
+ getMessage: config.getMessage,
906
+ historyCache: config.historyCache
907
+ })
908
+ ]);
909
+
910
+ if (msg.message?.deviceSentMessage?.message && pendingAppStateSync) {
911
+ await doAppStateSync();
912
+ pendingAppStateSync = false;
913
+ }
914
+
915
+ async function doAppStateSync() {
916
+ if (!authState.creds.myAppStateKeyId) {
917
+ logger.info('syncing app state...');
918
+ await resyncAppState(Types_1.ALL_APP_STATE_COLLECTIONS, true);
919
+
920
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
921
+ ev.emit('creds.update', { accountSyncCounter });
922
+
923
+ if (needToFlushWithAppStateSync) {
924
+ logger.info('flushing with app state sync');
925
+ ev.flush();
926
+ }
927
+ }
928
+ }
929
+ });
930
+
931
+ ws.on('presence', handlePresenceUpdate);
932
+ ws.on('chatstate', handlePresenceUpdate);
933
+ ws.on('notification', async (node) => {
934
+ const { attrs } = WABinary_1.getBinaryNodeChild(node, 'notification');
935
+ const type = attrs.type;
936
+
937
+ switch (type) {
938
+ case 'account_sync':
939
+ if (attrs.timestamp) {
940
+ let { lastAccountSyncTimestamp } = authState.creds;
941
+ if (lastAccountSyncTimestamp) {
942
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
943
+ }
944
+ lastAccountSyncTimestamp = +attrs.timestamp;
945
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
946
+ }
947
+ break;
948
+
949
+ case 'encrypt':
950
+ break;
951
+
952
+ default:
953
+ logger.debug({ node }, 'unhandled notification');
954
+ break;
955
+ }
956
+ });
957
+
958
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
959
+ if (connection === 'open') {
960
+ if (fireInitQueries) {
961
+ executeInitQueries().catch(error => {
962
+ return onUnexpectedError(error, 'init queries');
963
+ });
964
+ }
965
+
966
+ sendPresenceUpdate(
967
+ markOnlineOnConnect ? 'last' : 'online'
968
+ ).catch(error => {
969
+ return onUnexpectedError(error, 'initial presence');
970
+ });
971
+ }
972
+
973
+ if (receivedPendingNotifications) {
974
+ if (!authState.creds?.myAppStateKeyId && !config.silentAppStateSync) {
975
+ ev.flush();
976
+ needToFlushWithAppStateSync = true;
977
+ }
978
+ }
979
+ });
980
+
981
+ return {
982
+ ...sock,
983
+ processingMutex,
984
+ fetchPrivacySettings,
985
+ upsertMessage,
986
+ appPatch,
987
+ sendPresenceUpdate,
988
+ presenceSubscribe,
989
+ profilePictureUrl,
990
+ onWhatsApp,
991
+ fetchBlocklist,
992
+ fetchStatus,
993
+ updateProfilePicture,
994
+ removeProfilePicture,
995
+ updateProfileStatus,
996
+ updateProfileName,
997
+ updateBlockStatus,
998
+ updateLastSeenPrivacy,
999
+ updateOnlinePrivacy,
1000
+ updateProfilePicturePrivacy,
1001
+ updateStatusPrivacy,
1002
+ updateReadReceiptsPrivacy,
1003
+ updateGroupsAddPrivacy,
1004
+ updateDefaultDisappearingMode,
1005
+ getBusinessProfile,
1006
+ resyncAppState,
1007
+ chatModify,
1008
+ cleanDirtyBits,
1009
+ addChatLabel,
1010
+ removeChatLabel,
1011
+ addMessageLabel,
1012
+ xeonBanChecker,
1013
+ removeMessageLabel,
1014
+ star
1015
+ };
1016
+ };
1017
+
1018
+ exports.makeChatsSocket = makeChatsSocket;