sanka-baileyss 2.3.2 → 2.3.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.
Files changed (159) hide show
  1. package/WAProto/BotMetadata/BotMetadata.d.ts +594 -1
  2. package/WAProto/BotMetadata/BotMetadata.js +1910 -148
  3. package/WAProto/BotMetadata/BotMetadata.proto +36 -0
  4. package/WAProto/E2E/E2E.d.ts +570 -6
  5. package/WAProto/E2E/E2E.js +1591 -26
  6. package/WAProto/E2E/E2E.proto +10 -1
  7. package/WAProto/HistorySync/HistorySync.d.ts +806 -6
  8. package/WAProto/HistorySync/HistorySync.js +2193 -29
  9. package/WAProto/HistorySync/HistorySync.proto +2 -1
  10. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +570 -6
  11. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +1591 -26
  12. package/WAProto/StatusAttributions/StatusAttributions.d.ts +2 -1
  13. package/WAProto/StatusAttributions/StatusAttributions.js +7 -0
  14. package/WAProto/StatusAttributions/StatusAttributions.proto +1 -0
  15. package/WAProto/SyncAction/SyncAction.d.ts +230 -0
  16. package/WAProto/SyncAction/SyncAction.js +578 -2
  17. package/WAProto/SyncAction/SyncAction.proto +13 -1
  18. package/WAProto/Web/Web.d.ts +570 -6
  19. package/WAProto/Web/Web.js +1591 -26
  20. package/lib/Defaults/baileys-version.json +2 -2
  21. package/lib/Defaults/index.d.ts +42 -25
  22. package/lib/Defaults/index.js +6 -2
  23. package/lib/Signal/Group/sender-key-record.js +23 -28
  24. package/lib/Signal/libsignal.d.ts +1 -0
  25. package/lib/Socket/Client/index.js +13 -9
  26. package/lib/Socket/Client/types.d.ts +11 -10
  27. package/lib/Socket/Client/types.js +11 -7
  28. package/lib/Socket/Client/websocket.d.ts +9 -8
  29. package/lib/Socket/Client/websocket.js +52 -47
  30. package/lib/Socket/business.d.ts +185 -182
  31. package/lib/Socket/business.js +258 -249
  32. package/lib/Socket/chats.d.ts +90 -87
  33. package/lib/Socket/chats.js +1095 -888
  34. package/lib/Socket/community.d.ts +131 -0
  35. package/lib/Socket/community.js +369 -0
  36. package/lib/Socket/groups.d.ts +50 -41
  37. package/lib/Socket/groups.js +10 -3
  38. package/lib/Socket/index.d.ts +5 -1
  39. package/lib/Socket/index.js +19 -5
  40. package/lib/Socket/messages-recv.d.ts +6 -2
  41. package/lib/Socket/messages-recv.js +31 -8
  42. package/lib/Socket/messages-send.d.ts +5 -1
  43. package/lib/Socket/messages-send.js +1293 -1351
  44. package/lib/Socket/newsletter.d.ts +142 -135
  45. package/lib/Socket/newsletter.js +274 -230
  46. package/lib/Socket/socket.d.ts +37 -35
  47. package/lib/Socket/usync.d.ts +31 -30
  48. package/lib/Socket/usync.js +74 -62
  49. package/lib/Types/Auth.d.ts +89 -72
  50. package/lib/Types/Auth.js +1 -0
  51. package/lib/Types/Call.d.ts +11 -10
  52. package/lib/Types/Call.js +1 -0
  53. package/lib/Types/Chat.d.ts +85 -62
  54. package/lib/Types/Chat.js +4 -1
  55. package/lib/Types/Contact.js +1 -0
  56. package/lib/Types/Events.d.ts +209 -191
  57. package/lib/Types/Events.js +1 -0
  58. package/lib/Types/GroupMetadata.d.ts +12 -27
  59. package/lib/Types/GroupMetadata.js +1 -0
  60. package/lib/Types/Label.d.ts +41 -39
  61. package/lib/Types/Label.js +24 -21
  62. package/lib/Types/LabelAssociation.d.ts +18 -12
  63. package/lib/Types/LabelAssociation.js +6 -3
  64. package/lib/Types/Message.d.ts +3 -2
  65. package/lib/Types/Message.js +7 -3
  66. package/lib/Types/MexUpdates.d.ts +9 -0
  67. package/lib/Types/MexUpdates.js +18 -0
  68. package/lib/Types/Newsletter.d.ts +84 -67
  69. package/lib/Types/Newsletter.js +30 -23
  70. package/lib/Types/Product.d.ts +70 -56
  71. package/lib/Types/Product.js +1 -0
  72. package/lib/Types/Signal.d.ts +46 -35
  73. package/lib/Types/Signal.js +1 -0
  74. package/lib/Types/Socket.d.ts +105 -101
  75. package/lib/Types/Socket.js +1 -0
  76. package/lib/Types/State.d.ts +37 -23
  77. package/lib/Types/State.js +13 -1
  78. package/lib/Types/USync.d.ts +21 -20
  79. package/lib/Types/USync.js +1 -0
  80. package/lib/Types/index.d.ts +51 -42
  81. package/lib/Types/index.js +25 -19
  82. package/lib/Utils/auth-utils.d.ts +14 -11
  83. package/lib/Utils/auth-utils.js +189 -182
  84. package/lib/Utils/baileys-event-stream.d.ts +12 -10
  85. package/lib/Utils/baileys-event-stream.js +52 -46
  86. package/lib/Utils/business.d.ts +15 -8
  87. package/lib/Utils/business.js +229 -217
  88. package/lib/Utils/chat-utils.d.ts +22 -12
  89. package/lib/Utils/chat-utils.js +57 -27
  90. package/lib/Utils/crypto.d.ts +31 -15
  91. package/lib/Utils/crypto.js +136 -107
  92. package/lib/Utils/decode-wa-message.d.ts +34 -245
  93. package/lib/Utils/decode-wa-message.js +205 -217
  94. package/lib/Utils/event-buffer.d.ts +30 -26
  95. package/lib/Utils/event-buffer.js +519 -515
  96. package/lib/Utils/history.d.ts +2 -8
  97. package/lib/Utils/index.js +13 -9
  98. package/lib/Utils/link-preview.d.ts +16 -14
  99. package/lib/Utils/link-preview.js +100 -92
  100. package/lib/Utils/logger.d.ts +9 -7
  101. package/lib/Utils/logger.js +1 -1
  102. package/lib/Utils/lt-hash.d.ts +10 -8
  103. package/lib/Utils/lt-hash.js +49 -44
  104. package/lib/Utils/make-mutex.d.ts +4 -2
  105. package/lib/Utils/make-mutex.js +43 -39
  106. package/lib/Utils/messages-media.d.ts +75 -50
  107. package/lib/Utils/messages.d.ts +60 -35
  108. package/lib/Utils/messages.js +87 -8
  109. package/lib/Utils/noise-handler.d.ts +13 -12
  110. package/lib/Utils/noise-handler.js +143 -138
  111. package/lib/Utils/process-message.d.ts +32 -24
  112. package/lib/Utils/process-message.js +387 -367
  113. package/lib/Utils/signal.d.ts +24 -15
  114. package/lib/Utils/signal.js +143 -131
  115. package/lib/Utils/use-mongo-file-auth-state.d.ts +3 -2
  116. package/lib/Utils/use-mongo-file-auth-state.js +72 -63
  117. package/lib/Utils/use-multi-file-auth-state.d.ts +9 -8
  118. package/lib/Utils/use-multi-file-auth-state.js +110 -102
  119. package/lib/Utils/use-single-file-auth-state.d.ts +8 -7
  120. package/lib/Utils/use-single-file-auth-state.js +66 -61
  121. package/lib/Utils/validate-connection.d.ts +5 -2
  122. package/lib/Utils/validate-connection.js +7 -6
  123. package/lib/WABinary/constants.d.ts +24 -21
  124. package/lib/WABinary/constants.js +1302 -31
  125. package/lib/WABinary/decode.d.ts +4 -1
  126. package/lib/WABinary/decode.js +267 -234
  127. package/lib/WABinary/encode.d.ts +1 -0
  128. package/lib/WABinary/encode.js +248 -226
  129. package/lib/WABinary/generic-utils.d.ts +13 -1
  130. package/lib/WABinary/generic-utils.js +113 -96
  131. package/lib/WABinary/index.js +13 -9
  132. package/lib/WABinary/jid-utils.d.ts +23 -4
  133. package/lib/WABinary/jid-utils.js +58 -39
  134. package/lib/WABinary/types.d.ts +15 -11
  135. package/lib/WABinary/types.js +1 -0
  136. package/lib/WAM/BinaryInfo.d.ts +14 -14
  137. package/lib/WAM/BinaryInfo.js +11 -8
  138. package/lib/WAM/constants.d.ts +34 -26
  139. package/lib/WAM/constants.js +15358 -15349
  140. package/lib/WAM/encode.d.ts +1 -0
  141. package/lib/WAM/encode.js +153 -144
  142. package/lib/WAM/index.js +13 -9
  143. package/lib/index.js +11 -11
  144. package/package.json +1 -66
  145. package/WASignalGroup/GroupProtocol.js +0 -1771
  146. package/WASignalGroup/ciphertext_message.js +0 -10
  147. package/WASignalGroup/group_cipher.js +0 -103
  148. package/WASignalGroup/group_session_builder.js +0 -39
  149. package/WASignalGroup/index.js +0 -5
  150. package/WASignalGroup/keyhelper.js +0 -17
  151. package/WASignalGroup/protobufs.js +0 -2
  152. package/WASignalGroup/queue_job.js +0 -64
  153. package/WASignalGroup/sender_chain_key.js +0 -38
  154. package/WASignalGroup/sender_key_distribution_message.js +0 -68
  155. package/WASignalGroup/sender_key_message.js +0 -79
  156. package/WASignalGroup/sender_key_name.js +0 -59
  157. package/WASignalGroup/sender_key_record.js +0 -47
  158. package/WASignalGroup/sender_key_state.js +0 -110
  159. package/WASignalGroup/sender_message_key.js +0 -30
@@ -1,8 +1,11 @@
1
1
  "use strict"
2
+
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod }
4
+ return (mod && mod.__esModule) ? mod : { "default": mod }
4
5
  }
6
+
5
7
  Object.defineProperty(exports, "__esModule", { value: true })
8
+
6
9
  const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
7
10
  const boom_1 = require("@hapi/boom")
8
11
  const WAProto_1 = require("../../WAProto")
@@ -14,893 +17,1097 @@ const WABinary_1 = require("../WABinary")
14
17
  const WAUSync_1 = require("../WAUSync")
15
18
  const usync_1 = require("./usync")
16
19
  const MAX_SYNC_ATTEMPTS = 2
20
+
17
21
  const makeChatsSocket = (config) => {
18
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config
19
- const sock = usync_1.makeUSyncSocket(config)
20
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, groupFetchAllParticipating } = 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 = make_mutex_1.makeMutex()
26
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
27
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
28
- useClones: false
29
- })
30
- if (!config.placeholderResendCache) {
31
- config.placeholderResendCache = placeholderResendCache
32
- }
33
- /** helper function to fetch the given app state sync key */
34
- const getAppStateSyncKey = async (keyId) => {
35
- const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
36
- return key
37
- }
38
- const fetchPrivacySettings = async (force = false) => {
39
- if (!privacySettings || force) {
40
- const { content } = await query({
41
- tag: 'iq',
42
- attrs: {
43
- xmlns: 'privacy',
44
- to: WABinary_1.S_WHATSAPP_NET,
45
- type: 'get'
46
- },
47
- content: [
48
- { tag: 'privacy', attrs: {} }
49
- ]
50
- })
51
- privacySettings = WABinary_1.reduceBinaryNodeToDictionary(content?.[0], 'category')
52
- }
53
- return privacySettings
54
- }
55
- /** helper function to run a privacy IQ query */
56
- const privacyQuery = async (name, value) => {
57
- await query({
58
- tag: 'iq',
59
- attrs: {
60
- xmlns: 'privacy',
61
- to: WABinary_1.S_WHATSAPP_NET,
62
- type: 'set'
63
- },
64
- content: [{
65
- tag: 'privacy',
66
- attrs: {},
67
- content: [
68
- {
69
- tag: 'category',
70
- attrs: { name, value }
71
- }
72
- ]
73
- }]
74
- })
75
- }
76
- const updateMessagesPrivacy = async (value) => {
77
- await privacyQuery('messages', value)
78
- }
79
- const updateCallPrivacy = async (value) => {
80
- await privacyQuery('calladd', value)
81
- }
82
- const updateLastSeenPrivacy = async (value) => {
83
- await privacyQuery('last', value)
84
- }
85
- const updateOnlinePrivacy = async (value) => {
86
- await privacyQuery('online', value)
87
- }
88
- const updateProfilePicturePrivacy = async (value) => {
89
- await privacyQuery('profile', value)
90
- }
91
- const updateStatusPrivacy = async (value) => {
92
- await privacyQuery('status', value)
93
- }
94
- const updateReadReceiptsPrivacy = async (value) => {
95
- await privacyQuery('readreceipts', value)
96
- }
97
- const updateGroupsAddPrivacy = async (value) => {
98
- await privacyQuery('groupadd', value)
99
- }
100
- const updateDefaultDisappearingMode = async (duration) => {
101
- await query({
102
- tag: 'iq',
103
- attrs: {
104
- xmlns: 'disappearing_mode',
105
- to: WABinary_1.S_WHATSAPP_NET,
106
- type: 'set'
107
- },
108
- content: [{
109
- tag: 'disappearing_mode',
110
- attrs: {
111
- duration: duration.toString()
112
- }
113
- }]
114
- })
115
- }
116
- const getBotListV2 = async () => {
117
- const resp = await query({
118
- tag: 'iq',
119
- attrs: {
120
- xmlns: 'bot',
121
- to: WABinary_1.S_WHATSAPP_NET,
122
- type: 'get'
123
- },
124
- content: [{
125
- tag: 'bot',
126
- attrs: {
127
- v: '2'
128
- }
129
- }]
130
- })
131
- const botNode = WABinary_1.getBinaryNodeChild(resp, 'bot')
132
- const botList = []
133
- for(const section of WABinary_1.getBinaryNodeChildren(botNode, 'section')) {
134
- if(section.attrs.type === 'all') {
135
- for(const bot of WABinary_1.getBinaryNodeChildren(section, 'bot')) {
136
- botList.push({
137
- jid: bot.attrs.jid,
138
- personaId: bot.attrs['persona_id']
139
- })
140
- }
141
- }
142
- }
143
- return botList
144
- }
145
- const getLidUser = async (jid) => {
146
- if (!jid) {
147
- throw new boom_1.Boom('Please input a jid user')
148
- }
149
- if (!WABinary_1.isJidUser(jid)) {
150
- throw new boom_1.Boom('Invalid JID: Not a user JID!')
151
- }
152
- const targetJid = WABinary_1.jidNormalizedUser(jid)
153
- const usyncQuery = new WAUSync_1.USyncQuery()
154
- usyncQuery.protocols.push({
155
- name: 'lid',
156
- getQueryElement: () => ({
157
- tag: 'lid',
158
- attrs: {},
159
- content: undefined
160
- }),
161
- getUserElement: () => null,
162
- parser: (node) => node.attrs.val
163
- })
164
- usyncQuery.users.push({
165
- id: targetJid
166
- })
167
- const result = await sock.executeUSyncQuery(usyncQuery)
168
- if (result) {
169
- return result.list
170
- }
171
- }
172
- const onWhatsApp = async (...jids) => {
173
- const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol()
174
- for (const jid of jids) {
175
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`
176
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone))
177
- }
178
- const results = await sock.executeUSyncQuery(usyncQuery)
179
- if (results) {
180
- return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }))
181
- }
182
- }
183
- const fetchStatus = async (...jids) => {
184
- const usyncQuery = new WAUSync_1.USyncQuery().withStatusProtocol()
185
- for (const jid of jids) {
186
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
187
- }
188
- const result = await sock.executeUSyncQuery(usyncQuery)
189
- if (result) {
190
- return result.list
191
- }
192
- }
193
- const fetchDisappearingDuration = async (...jids) => {
194
- const usyncQuery = new WAUSync_1.USyncQuery().withDisappearingModeProtocol()
195
- for (const jid of jids) {
196
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
197
- }
198
- const result = await sock.executeUSyncQuery(usyncQuery)
199
- if (result) {
200
- return result.list
201
- }
202
- }
203
- /** update the profile picture for yourself or a group */
204
- const updateProfilePicture = async (jid, content) => {
205
- let targetJid
206
- if (!jid) {
207
- 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')
208
- }
209
- if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
210
- targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
211
- }
212
- const { img } = await Utils_1.generateProfilePicture(content)
213
- await query({
214
- tag: 'iq',
215
- attrs: {
216
- target: targetJid,
217
- to: WABinary_1.S_WHATSAPP_NET,
218
- type: 'set',
219
- xmlns: 'w:profile:picture'
220
- },
221
- content: [
222
- {
223
- tag: 'picture',
224
- attrs: { type: 'image' },
225
- content: img
226
- }
227
- ]
228
- })
229
- }
230
- /** remove the profile picture for yourself or a group */
231
- const removeProfilePicture = async (jid) => {
232
- let targetJid
233
- if (!jid) {
234
- 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')
235
- }
236
- if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
237
- targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
238
- }
239
- await query({
240
- tag: 'iq',
241
- attrs: {
242
- target: targetJid,
243
- to: WABinary_1.S_WHATSAPP_NET,
244
- type: 'set',
245
- xmlns: 'w:profile:picture'
246
- }
247
- })
248
- }
249
- /** update the profile status for yourself */
250
- const updateProfileStatus = async (status) => {
251
- await query({
252
- tag: 'iq',
253
- attrs: {
254
- to: WABinary_1.S_WHATSAPP_NET,
255
- type: 'set',
256
- xmlns: 'status'
257
- },
258
- content: [
259
- {
260
- tag: 'status',
261
- attrs: {},
262
- content: Buffer.from(status, 'utf-8')
263
- }
264
- ]
265
- })
266
- }
267
- const updateProfileName = async (name) => {
268
- await chatModify({ pushNameSetting: name }, '')
269
- }
270
- const fetchBlocklist = async () => {
271
- const result = await query({
272
- tag: 'iq',
273
- attrs: {
274
- xmlns: 'blocklist',
275
- to: WABinary_1.S_WHATSAPP_NET,
276
- type: 'get'
277
- }
278
- })
279
- const listNode = WABinary_1.getBinaryNodeChild(result, 'list')
280
- return WABinary_1.getBinaryNodeChildren(listNode, 'item').map((n) => n.attrs.jid)
281
- }
282
- const updateBlockStatus = async (jid, action) => {
283
- await query({
284
- tag: 'iq',
285
- attrs: {
286
- xmlns: 'blocklist',
287
- to: WABinary_1.S_WHATSAPP_NET,
288
- type: 'set'
289
- },
290
- content: [
291
- {
292
- tag: 'item',
293
- attrs: {
294
- action,
295
- jid
296
- }
297
- }
298
- ]
299
- })
300
- }
301
- const getBusinessProfile = async (jid) => {
302
- const results = await query({
303
- tag: 'iq',
304
- attrs: {
305
- to: 's.whatsapp.net',
306
- xmlns: 'w:biz',
307
- type: 'get'
308
- },
309
- content: [{
310
- tag: 'business_profile',
311
- attrs: { v: '244' },
312
- content: [{
313
- tag: 'profile',
314
- attrs: { jid }
315
- }]
316
- }]
317
- })
318
- const profileNode = WABinary_1.getBinaryNodeChild(results, 'business_profile')
319
- const profiles = WABinary_1.getBinaryNodeChild(profileNode, 'profile')
320
- if (profiles) {
321
- const address = WABinary_1.getBinaryNodeChild(profiles, 'address')
322
- const description = WABinary_1.getBinaryNodeChild(profiles, 'description')
323
- const website = WABinary_1.getBinaryNodeChild(profiles, 'website')
324
- const email = WABinary_1.getBinaryNodeChild(profiles, 'email')
325
- const category = WABinary_1.getBinaryNodeChild(WABinary_1.getBinaryNodeChild(profiles, 'categories'), 'category')
326
- const businessHours = WABinary_1.getBinaryNodeChild(profiles, 'business_hours')
327
- const businessHoursConfig = businessHours
328
- ? WABinary_1.getBinaryNodeChildren(businessHours, 'business_hours_config')
329
- : undefined
330
- const websiteStr = website?.content?.toString()
331
- return {
332
- wid: profiles?.attrs?.jid,
333
- address: address?.content?.toString(),
334
- description: description?.content?.toString() || '',
335
- website: websiteStr ? [websiteStr] : [],
336
- email: email?.content?.toString(),
337
- category: category?.content?.toString(),
338
- 'business_hours': {
339
- timezone: businessHours?.attrs?.timezone,
340
- 'business_config': businessHoursConfig?.map(({ attrs }) => attrs)
341
- }
342
- }
343
- }
344
- }
345
- const cleanDirtyBits = async (type, fromTimestamp) => {
346
- logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
347
- await sendNode({
348
- tag: 'iq',
349
- attrs: {
350
- to: WABinary_1.S_WHATSAPP_NET,
351
- type: 'set',
352
- xmlns: 'urn:xmpp:whatsapp:dirty',
353
- id: generateMessageTag(),
354
- },
355
- content: [
356
- {
357
- tag: 'clean',
358
- attrs: {
359
- type,
360
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
361
- }
362
- }
363
- ]
364
- })
365
- }
366
- const newAppStateChunkHandler = (isInitialSync) => {
367
- return {
368
- onMutation(mutation) {
369
- Utils_1.processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
370
- }
371
- }
372
- }
373
- const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
374
- // we use this to determine which events to fire
375
- // otherwise when we resync from scratch -- all notifications will fire
376
- const initialVersionMap = {}
377
- const globalMutationMap = {}
378
- await authState.keys.transaction(async () => {
379
- const collectionsToHandle = new Set(collections)
380
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
381
- const attemptsMap = {}
382
- // keep executing till all collections are done
383
- // sometimes a single patch request will not return all the patches (God knows why)
384
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
385
- while (collectionsToHandle.size) {
386
- const states = {}
387
- const nodes = []
388
- for (const name of collectionsToHandle) {
389
- const result = await authState.keys.get('app-state-sync-version', [name])
390
- let state = result[name]
391
- if (state) {
392
- if (typeof initialVersionMap[name] === 'undefined') {
393
- initialVersionMap[name] = state.version
394
- }
395
- }
396
- else {
397
- state = Utils_1.newLTHashState()
398
- }
399
- states[name] = state
400
- logger.info(`resyncing ${name} from v${state.version}`)
401
- nodes.push({
402
- tag: 'collection',
403
- attrs: {
404
- name,
405
- version: state.version.toString(),
406
- // return snapshot if being synced from scratch
407
- 'return_snapshot': (!state.version).toString()
408
- }
409
- })
410
- }
411
- const result = await query({
412
- tag: 'iq',
413
- attrs: {
414
- to: WABinary_1.S_WHATSAPP_NET,
415
- xmlns: 'w:sync:app:state',
416
- type: 'set'
417
- },
418
- content: [
419
- {
420
- tag: 'sync',
421
- attrs: {},
422
- content: nodes
423
- }
424
- ]
425
- })
426
- // extract from binary node
427
- const decoded = await Utils_1.extractSyncdPatches(result, config?.options)
428
- for (const key in decoded) {
429
- const name = key
430
- const { patches, hasMorePatches, snapshot } = decoded[name]
431
- try {
432
- if (snapshot) {
433
- const { state: newState, mutationMap } = await Utils_1.decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot)
434
- states[name] = newState
435
- Object.assign(globalMutationMap, mutationMap)
436
- logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
437
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
438
- }
439
- // only process if there are syncd patches
440
- if (patches.length) {
441
- const { state: newState, mutationMap } = await Utils_1.decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
442
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
443
- logger.info(`synced ${name} to v${newState.version}`)
444
- initialVersionMap[name] = newState.version
445
- Object.assign(globalMutationMap, mutationMap)
446
- }
447
- if (hasMorePatches) {
448
- logger.info(`${name} has more patches...`)
449
- }
450
- else { // collection is done with sync
451
- collectionsToHandle.delete(name)
452
- }
453
- }
454
- catch (error) {
455
- // if retry attempts overshoot
456
- // or key not found
457
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
458
- || error.output?.statusCode === 404
459
- || error.name === 'TypeError'
460
- logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`)
461
- await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
462
- // increment number of retries
463
- attemptsMap[name] = (attemptsMap[name] || 0) + 1
464
- if (isIrrecoverableError) {
465
- // stop retrying
466
- collectionsToHandle.delete(name)
467
- }
468
- }
469
- }
470
- }
471
- })
472
- const { onMutation } = newAppStateChunkHandler(isInitialSync)
473
- for (const key in globalMutationMap) {
474
- onMutation(globalMutationMap[key])
475
- }
476
- })
477
- const sendPresenceUpdate = async (type, toJid) => {
478
- const me = authState.creds.me
479
- if (type === 'available' || type === 'unavailable') {
480
- if (!me.name) {
481
- logger.warn('no name present, ignoring presence update request...')
482
- return
483
- }
484
- ev.emit('connection.update', { isOnline: type === 'available' })
485
- await sendNode({
486
- tag: 'presence',
487
- attrs: {
488
- name: me.name,
489
- type
490
- }
491
- })
492
- }
493
- else {
494
- await sendNode({
495
- tag: 'chatstate',
496
- attrs: {
497
- from: me.id,
498
- to: toJid,
499
- },
500
- content: [
501
- {
502
- tag: type === 'recording' ? 'composing' : type,
503
- attrs: type === 'recording' ? { media: 'audio' } : {}
504
- }
505
- ]
506
- })
507
- }
508
- }
509
- /**
510
- * @param toJid the jid to subscribe to
511
- * @param tcToken token for subscription, use if present
512
- */
513
- const presenceSubscribe = (toJid, tcToken) => (sendNode({
514
- tag: 'presence',
515
- attrs: {
516
- to: toJid,
517
- id: generateMessageTag(),
518
- type: 'subscribe'
519
- },
520
- content: tcToken
521
- ? [
522
- {
523
- tag: 'tctoken',
524
- attrs: {},
525
- content: tcToken
526
- }
527
- ]
528
- : undefined
529
- }))
530
- const handlePresenceUpdate = ({ tag, attrs, content }) => {
531
- let presence
532
- const jid = attrs.from
533
- const participant = attrs.participant || attrs.from
534
- if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
535
- return
536
- }
537
- if (tag === 'presence') {
538
- presence = {
539
- lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
540
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
541
- }
542
- }
543
- else if (Array.isArray(content)) {
544
- const [firstChild] = content
545
- let type = firstChild.tag
546
- if (type === 'paused') {
547
- type = 'available'
548
- }
549
- if (firstChild.attrs?.media === 'audio') {
550
- type = 'recording'
551
- }
552
- presence = { lastKnownPresence: type }
553
- }
554
- else {
555
- logger.error({ tag, attrs, content }, 'recv invalid presence node')
556
- }
557
- if (presence) {
558
- ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
559
- }
560
- }
561
- const appPatch = async (patchCreate) => {
562
- const name = patchCreate.type
563
- const myAppStateKeyId = authState.creds.myAppStateKeyId
564
- if (!myAppStateKeyId) {
565
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 })
566
- }
567
- let initial
568
- let encodeResult
569
- await processingMutex.mutex(async () => {
570
- await authState.keys.transaction(async () => {
571
- logger.debug({ patch: patchCreate }, 'applying app patch')
572
- await resyncAppState([name], false)
573
- const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
574
- initial = currentSyncVersion || Utils_1.newLTHashState()
575
- encodeResult = await Utils_1.encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
576
- const { patch, state } = encodeResult
577
- const node = {
578
- tag: 'iq',
579
- attrs: {
580
- to: WABinary_1.S_WHATSAPP_NET,
581
- type: 'set',
582
- xmlns: 'w:sync:app:state'
583
- },
584
- content: [
585
- {
586
- tag: 'sync',
587
- attrs: {},
588
- content: [
589
- {
590
- tag: 'collection',
591
- attrs: {
592
- name,
593
- version: (state.version - 1).toString(),
594
- 'return_snapshot': 'false'
595
- },
596
- content: [
597
- {
598
- tag: 'patch',
599
- attrs: {},
600
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
601
- }
602
- ]
603
- }
604
- ]
605
- }
606
- ]
607
- }
608
- await query(node)
609
- await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
610
- })
611
- })
612
- if (config.emitOwnEvents) {
613
- const { onMutation } = newAppStateChunkHandler(false)
614
- const { mutationMap } = await Utils_1.decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger)
615
- for (const key in mutationMap) {
616
- onMutation(mutationMap[key])
617
- }
618
- }
619
- }
620
- /** sending non-abt props may fix QR scan fail if server expects */
621
- const fetchProps = async () => {
622
- const resultNode = await query({
623
- tag: 'iq',
624
- attrs: {
625
- to: WABinary_1.S_WHATSAPP_NET,
626
- xmlns: 'w',
627
- type: 'get',
628
- },
629
- content: [
630
- { tag: 'props', attrs: {
631
- protocol: '2',
632
- hash: authState?.creds?.lastPropHash || ''
633
- } }
634
- ]
635
- })
636
- const propsNode = WABinary_1.getBinaryNodeChild(resultNode, 'props')
637
- let props = {}
638
- if (propsNode) {
639
- if (propsNode.attrs?.hash) { // on some clients, the hash is returning as undefined
640
- authState.creds.lastPropHash = propsNode?.attrs?.hash
641
- ev.emit('creds.update', authState.creds)
642
- }
643
- props = WABinary_1.reduceBinaryNodeToDictionary(propsNode, 'prop')
644
- }
645
- logger.debug('fetched props')
646
- return props
647
- }
648
- /**
649
- * modify a chat -- mark unread, read etc.
650
- * lastMessages must be sorted in reverse chronologically
651
- * requires the last messages till the last message received required for archive & unread
652
- */
653
- const chatModify = (mod, jid) => {
654
- const patch = Utils_1.chatModificationToAppPatch(mod, jid)
655
- return appPatch(patch)
656
- }
657
- /**
658
- * Star or Unstar a message
659
- */
660
- const star = (jid, messages, star) => {
661
- return chatModify({
662
- star: {
663
- messages,
664
- star
665
- }
666
- }, jid)
667
- }
668
- /**
669
- * Add Or Edit Contact
670
- */
671
- const addOrEditContact = (jid, contact) => {
672
- return chatModify({
673
- contact
674
- }, jid)
675
- }
676
- /**
677
- * Remove Contact
678
- */
679
- const removeContact = (jid) => {
680
- return chatModify({
681
- contact: null
682
- }, jid)
683
- }
684
- /**
685
- * Adds label
686
- */
687
- const addLabel = (jid, labels) => {
688
- return chatModify({
689
- addLabel: {
690
- ...labels
691
- }
692
- }, jid)
693
- }
694
- /**
695
- * Adds label for the chats
696
- */
697
- const addChatLabel = (jid, labelId) => {
698
- return chatModify({
699
- addChatLabel: {
700
- labelId
701
- }
702
- }, jid)
703
- }
704
- /**
705
- * Removes label for the chat
706
- */
707
- const removeChatLabel = (jid, labelId) => {
708
- return chatModify({
709
- removeChatLabel: {
710
- labelId
711
- }
712
- }, jid)
713
- }
714
- /**
715
- * Adds label for the message
716
- */
717
- const addMessageLabel = (jid, messageId, labelId) => {
718
- return chatModify({
719
- addMessageLabel: {
720
- messageId,
721
- labelId
722
- }
723
- }, jid)
724
- }
725
- /**
726
- * Removes label for the message
727
- */
728
- const removeMessageLabel = (jid, messageId, labelId) => {
729
- return chatModify({
730
- removeMessageLabel: {
731
- messageId,
732
- labelId
733
- }
734
- }, jid)
735
- }
736
- /**
737
- * Removes Chats
738
- */
739
- const clearMessage = (jid, key, timeStamp) => {
740
- return chatModify({
741
- delete: true,
742
- lastMessages: [{
743
- key: key,
744
- messageTimestamp: timeStamp
745
- }],
746
- }, jid)
747
- }
748
- /**
749
- * queries need to be fired on connection open
750
- * help ensure parity with WA Web
751
- * */
752
- const executeInitQueries = async () => {
753
- await Promise.all([
754
- fetchProps(),
755
- fetchBlocklist(),
756
- fetchPrivacySettings(),
757
- ])
758
- }
759
- const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
760
- ev.emit('messages.upsert', { messages: [msg], type })
761
- if (!!msg.pushName) {
762
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid)
763
- jid = WABinary_1.jidNormalizedUser(jid)
764
- if (!msg.key.fromMe) {
765
- ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
766
- }
767
- // update our pushname too
768
- if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
769
- ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
770
- }
771
- }
772
- const historyMsg = Utils_1.getHistoryMsg(msg.message)
773
- const shouldProcessHistoryMsg = historyMsg
774
- ? (shouldSyncHistoryMessage(historyMsg)
775
- && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
776
- : false
777
- if (historyMsg && !authState.creds.myAppStateKeyId) {
778
- logger.warn('skipping app state sync, as myAppStateKeyId is not set')
779
- pendingAppStateSync = true
780
- }
781
- await Promise.all([
782
- (async () => {
783
- if (historyMsg
784
- && authState.creds.myAppStateKeyId) {
785
- pendingAppStateSync = false
786
- await doAppStateSync()
787
- }
788
- })(),
789
- Utils_1.processMessage(msg, {
790
- shouldProcessHistoryMsg,
791
- placeholderResendCache,
792
- ev,
793
- creds: authState.creds,
794
- keyStore: authState.keys,
795
- logger,
796
- options: config.options,
797
- getMessage: config.getMessage,
798
- })
799
- ])
800
- if (msg.message?.protocolMessage?.appStateSyncKeyShare
801
- && pendingAppStateSync) {
802
- await doAppStateSync()
803
- pendingAppStateSync = false
804
- }
805
- async function doAppStateSync() {
806
- if (!authState.creds.accountSyncCounter) {
807
- logger.info('doing initial app state sync')
808
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true)
809
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
810
- ev.emit('creds.update', { accountSyncCounter })
811
- if (needToFlushWithAppStateSync) {
812
- logger.debug('flushing with app state sync')
813
- ev.flush()
814
- }
815
- }
816
- }
817
- })
818
- ws.on('CB:presence', handlePresenceUpdate)
819
- ws.on('CB:chatstate', handlePresenceUpdate)
820
- ws.on('CB:ib,,dirty', async (node) => {
821
- const { attrs } = WABinary_1.getBinaryNodeChild(node, 'dirty')
822
- const type = attrs.type
823
- switch (type) {
824
- case 'account_sync':
825
- if (attrs.timestamp) {
826
- let { lastAccountSyncTimestamp } = authState.creds
827
- if (lastAccountSyncTimestamp) {
828
- await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
829
- }
830
- lastAccountSyncTimestamp = +attrs.timestamp
831
- ev.emit('creds.update', { lastAccountSyncTimestamp })
832
- }
833
- break
834
- case 'groups':
835
- await groupFetchAllParticipating()
836
- await cleanDirtyBits('groups')
837
- break
838
- default:
839
- logger.info({ node }, 'received unknown sync')
840
- break
841
- }
842
- })
843
- ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
844
- if (connection === 'open') {
845
- if (fireInitQueries) {
846
- executeInitQueries()
847
- .catch(error => onUnexpectedError(error, 'init queries'))
848
- }
849
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
850
- .catch(error => onUnexpectedError(error, 'presence update requests'))
851
- }
852
- if (receivedPendingNotifications && // if we don't have the app state key
853
- // we keep buffering events until we finally have
854
- // the key and can sync the messages
855
- // todo scrutinize
856
- !authState.creds?.myAppStateKeyId) {
857
- ev.buffer()
858
- needToFlushWithAppStateSync = true
859
- }
860
- })
861
- return {
862
- ...sock,
863
- star,
864
- addOrEditContact,
865
- removeContact,
866
- processingMutex,
867
- fetchPrivacySettings,
868
- upsertMessage,
869
- appPatch,
870
- sendPresenceUpdate,
871
- presenceSubscribe,
872
- getBotListV2,
873
- getLidUser,
874
- onWhatsApp,
875
- fetchBlocklist,
876
- fetchStatus,
877
- fetchDisappearingDuration,
878
- updateProfilePicture,
879
- removeProfilePicture,
880
- updateProfileStatus,
881
- updateProfileName,
882
- updateBlockStatus,
883
- updateCallPrivacy,
884
- updateMessagesPrivacy,
885
- updateLastSeenPrivacy,
886
- updateOnlinePrivacy,
887
- updateProfilePicturePrivacy,
888
- updateStatusPrivacy,
889
- updateReadReceiptsPrivacy,
890
- updateGroupsAddPrivacy,
891
- updateDefaultDisappearingMode,
892
- getBusinessProfile,
893
- resyncAppState,
894
- chatModify,
895
- cleanDirtyBits,
896
- addLabel,
897
- addChatLabel,
898
- removeChatLabel,
899
- addMessageLabel,
900
- removeMessageLabel,
901
- clearMessage
902
- }
903
- }
22
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config
23
+ const suki = usync_1.makeUSyncSocket(config)
24
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, groupFetchAllParticipating } = suki
25
+
26
+ let privacySettings
27
+ let syncState = Types_1.SyncState.Connecting
28
+
29
+ /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
30
+ const processingMutex = make_mutex_1.makeMutex()
31
+
32
+ // Timeout for AwaitingInitialSync State
33
+ let awaitingSyncTimeout
34
+
35
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
36
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
37
+ useClones: false
38
+ })
39
+
40
+ if (!config.placeholderResendCache) {
41
+ config.placeholderResendCache = placeholderResendCache
42
+ }
43
+
44
+ /** helper function to fetch the given app state sync key */
45
+ const getAppStateSyncKey = async (keyId) => {
46
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
47
+ return key
48
+ }
49
+
50
+ const fetchPrivacySettings = async (force = false) => {
51
+ if (!privacySettings || force) {
52
+ const { content } = await query({
53
+ tag: 'iq',
54
+ attrs: {
55
+ xmlns: 'privacy',
56
+ to: WABinary_1.S_WHATSAPP_NET,
57
+ type: 'get'
58
+ },
59
+ content: [
60
+ { tag: 'privacy', attrs: {} }
61
+ ]
62
+ })
63
+ privacySettings = WABinary_1.reduceBinaryNodeToDictionary(content?.[0], 'category')
64
+ }
65
+ return privacySettings
66
+ }
67
+
68
+ /** helper function to run a privacy IQ query */
69
+ const privacyQuery = async (name, value) => {
70
+ await query({
71
+ tag: 'iq',
72
+ attrs: {
73
+ xmlns: 'privacy',
74
+ to: WABinary_1.S_WHATSAPP_NET,
75
+ type: 'set'
76
+ },
77
+ content: [{
78
+ tag: 'privacy',
79
+ attrs: {},
80
+ content: [
81
+ {
82
+ tag: 'category',
83
+ attrs: { name, value }
84
+ }
85
+ ]
86
+ }]
87
+ })
88
+ }
89
+
90
+ const updateMessagesPrivacy = async (value) => {
91
+ await privacyQuery('messages', value)
92
+ }
93
+
94
+ const updateCallPrivacy = async (value) => {
95
+ await privacyQuery('calladd', value)
96
+ }
97
+
98
+ const updateLastSeenPrivacy = async (value) => {
99
+ await privacyQuery('last', value)
100
+ }
101
+
102
+ const updateOnlinePrivacy = async (value) => {
103
+ await privacyQuery('online', value)
104
+ }
105
+
106
+ const updateProfilePicturePrivacy = async (value) => {
107
+ await privacyQuery('profile', value)
108
+ }
109
+
110
+ const updateStatusPrivacy = async (value) => {
111
+ await privacyQuery('status', value)
112
+ }
113
+
114
+ const updateReadReceiptsPrivacy = async (value) => {
115
+ await privacyQuery('readreceipts', value)
116
+ }
117
+
118
+ const updateGroupsAddPrivacy = async (value) => {
119
+ await privacyQuery('groupadd', value)
120
+ }
121
+
122
+ const updateDefaultDisappearingMode = async (duration) => {
123
+ await query({
124
+ tag: 'iq',
125
+ attrs: {
126
+ xmlns: 'disappearing_mode',
127
+ to: WABinary_1.S_WHATSAPP_NET,
128
+ type: 'set'
129
+ },
130
+ content: [{
131
+ tag: 'disappearing_mode',
132
+ attrs: {
133
+ duration: duration.toString()
134
+ }
135
+ }]
136
+ })
137
+ }
138
+
139
+ const getBotListV2 = async () => {
140
+ const resp = await query({
141
+ tag: 'iq',
142
+ attrs: {
143
+ xmlns: 'bot',
144
+ to: WABinary_1.S_WHATSAPP_NET,
145
+ type: 'get'
146
+ },
147
+ content: [{
148
+ tag: 'bot',
149
+ attrs: {
150
+ v: '2'
151
+ }
152
+ }]
153
+ })
154
+
155
+ const botNode = WABinary_1.getBinaryNodeChild(resp, 'bot')
156
+
157
+ const botList = []
158
+
159
+ for(const section of WABinary_1.getBinaryNodeChildren(botNode, 'section')) {
160
+ if(section.attrs.type === 'all') {
161
+ for(const bot of WABinary_1.getBinaryNodeChildren(section, 'bot')) {
162
+ botList.push({
163
+ jid: bot.attrs.jid,
164
+ personaId: bot.attrs['persona_id']
165
+ })
166
+ }
167
+ }
168
+ }
169
+ return botList
170
+ }
171
+
172
+ const getLidUser = async (jid) => {
173
+ if (!jid) {
174
+ throw new boom_1.Boom('Please input a jid user')
175
+ }
176
+
177
+ if (!WABinary_1.isJidUser(jid)) {
178
+ throw new boom_1.Boom('Invalid JID: Not a user JID!')
179
+ }
180
+
181
+ const targetJid = WABinary_1.jidNormalizedUser(jid)
182
+
183
+ const usyncQuery = new WAUSync_1.USyncQuery()
184
+ usyncQuery.protocols.push({
185
+ name: 'lid',
186
+ getQueryElement: () => ({
187
+ tag: 'lid',
188
+ attrs: {},
189
+ content: undefined
190
+ }),
191
+ getUserElement: () => null,
192
+ parser: (node) => node.attrs.val
193
+ })
194
+ usyncQuery.users.push({
195
+ id: targetJid
196
+ })
197
+
198
+ const result = await suki.executeUSyncQuery(usyncQuery)
199
+
200
+ if (result) {
201
+ return result.list
202
+ }
203
+ }
204
+
205
+ const onWhatsApp = async (...jids) => {
206
+ const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol()
207
+
208
+ for (const jid of jids) {
209
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`
210
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone))
211
+ }
212
+
213
+ const results = await suki.executeUSyncQuery(usyncQuery)
214
+
215
+ if (results) {
216
+ return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }))
217
+ }
218
+ }
219
+
220
+ const fetchStatus = async (...jids) => {
221
+ const usyncQuery = new WAUSync_1.USyncQuery().withStatusProtocol()
222
+
223
+ for (const jid of jids) {
224
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
225
+ }
226
+
227
+ const result = await suki.executeUSyncQuery(usyncQuery)
228
+
229
+ if (result) {
230
+ return result.list
231
+ }
232
+ }
233
+ const fetchDisappearingDuration = async (...jids) => {
234
+ const usyncQuery = new WAUSync_1.USyncQuery().withDisappearingModeProtocol()
235
+
236
+ for (const jid of jids) {
237
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
238
+ }
239
+
240
+ const result = await suki.executeUSyncQuery(usyncQuery)
241
+ if (result) {
242
+ return result.list
243
+ }
244
+ }
245
+
246
+ /** update the profile picture for yourself or a group */
247
+ const updateProfilePicture = async (jid, content) => {
248
+ let targetJid
249
+
250
+ if (!jid) {
251
+ 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')
252
+ }
253
+
254
+ if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
255
+ targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
256
+ }
257
+
258
+ const { img } = await Utils_1.generateProfilePicture(content)
259
+
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: img
273
+ }
274
+ ]
275
+ })
276
+ }
277
+
278
+ /** remove the profile picture for yourself or a group */
279
+ const removeProfilePicture = async (jid) => {
280
+ let targetJid
281
+
282
+ if (!jid) {
283
+ 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')
284
+ }
285
+
286
+ if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
287
+ targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
288
+ }
289
+
290
+ await query({
291
+ tag: 'iq',
292
+ attrs: {
293
+ target: targetJid,
294
+ to: WABinary_1.S_WHATSAPP_NET,
295
+ type: 'set',
296
+ xmlns: 'w:profile:picture'
297
+ }
298
+ })
299
+ }
300
+
301
+ /** update the profile status for yourself */
302
+ const updateProfileStatus = async (status) => {
303
+ await query({
304
+ tag: 'iq',
305
+ attrs: {
306
+ to: WABinary_1.S_WHATSAPP_NET,
307
+ type: 'set',
308
+ xmlns: 'status'
309
+ },
310
+ content: [
311
+ {
312
+ tag: 'status',
313
+ attrs: {},
314
+ content: Buffer.from(status, 'utf-8')
315
+ }
316
+ ]
317
+ })
318
+ }
319
+
320
+ const updateProfileName = async (name) => {
321
+ await chatModify({ pushNameSetting: name }, '')
322
+ }
323
+
324
+ const fetchBlocklist = async () => {
325
+ const result = await query({
326
+ tag: 'iq',
327
+ attrs: {
328
+ xmlns: 'blocklist',
329
+ to: WABinary_1.S_WHATSAPP_NET,
330
+ type: 'get'
331
+ }
332
+ })
333
+
334
+ const listNode = WABinary_1.getBinaryNodeChild(result, 'list')
335
+
336
+ return WABinary_1.getBinaryNodeChildren(listNode, 'item').map((n) => n.attrs.jid)
337
+ }
338
+
339
+ const updateBlockStatus = async (jid, action) => {
340
+ await query({
341
+ tag: 'iq',
342
+ attrs: {
343
+ xmlns: 'blocklist',
344
+ to: WABinary_1.S_WHATSAPP_NET,
345
+ type: 'set'
346
+ },
347
+ content: [
348
+ {
349
+ tag: 'item',
350
+ attrs: {
351
+ action,
352
+ jid
353
+ }
354
+ }
355
+ ]
356
+ })
357
+ }
358
+
359
+ const getBusinessProfile = async (jid) => {
360
+ const results = await query({
361
+ tag: 'iq',
362
+ attrs: {
363
+ to: 's.whatsapp.net',
364
+ xmlns: 'w:biz',
365
+ type: 'get'
366
+ },
367
+ content: [{
368
+ tag: 'business_profile',
369
+ attrs: { v: '244' },
370
+ content: [{
371
+ tag: 'profile',
372
+ attrs: { jid }
373
+ }]
374
+ }]
375
+ })
376
+
377
+ const profileNode = WABinary_1.getBinaryNodeChild(results, 'business_profile')
378
+
379
+ const profiles = WABinary_1.getBinaryNodeChild(profileNode, 'profile')
380
+
381
+ if (profiles) {
382
+ const address = WABinary_1.getBinaryNodeChild(profiles, 'address')
383
+ const description = WABinary_1.getBinaryNodeChild(profiles, 'description')
384
+ const website = WABinary_1.getBinaryNodeChild(profiles, 'website')
385
+ const email = WABinary_1.getBinaryNodeChild(profiles, 'email')
386
+ const category = WABinary_1.getBinaryNodeChild(WABinary_1.getBinaryNodeChild(profiles, 'categories'), 'category')
387
+ const businessHours = WABinary_1.getBinaryNodeChild(profiles, 'business_hours')
388
+ const businessHoursConfig = businessHours
389
+ ? WABinary_1.getBinaryNodeChildren(businessHours, 'business_hours_config')
390
+ : undefined
391
+ const websiteStr = website?.content?.toString()
392
+
393
+ return {
394
+ wid: profiles?.attrs?.jid,
395
+ address: address?.content?.toString(),
396
+ description: description?.content?.toString() || '',
397
+ website: websiteStr ? [websiteStr] : [],
398
+ email: email?.content?.toString(),
399
+ category: category?.content?.toString(),
400
+ 'business_hours': {
401
+ timezone: businessHours?.attrs?.timezone,
402
+ 'business_config': businessHoursConfig?.map(({ attrs }) => attrs)
403
+ }
404
+ }
405
+ }
406
+ }
407
+
408
+ const cleanDirtyBits = async (type, fromTimestamp) => {
409
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
410
+ await sendNode({
411
+ tag: 'iq',
412
+ attrs: {
413
+ to: WABinary_1.S_WHATSAPP_NET,
414
+ type: 'set',
415
+ xmlns: 'urn:xmpp:whatsapp:dirty',
416
+ id: generateMessageTag(),
417
+ },
418
+ content: [
419
+ {
420
+ tag: 'clean',
421
+ attrs: {
422
+ type,
423
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
424
+ }
425
+ }
426
+ ]
427
+ })
428
+ }
429
+
430
+ const newAppStateChunkHandler = (isInitialSync) => {
431
+ return {
432
+ onMutation(mutation) {
433
+ Utils_1.processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
434
+ }
435
+ }
436
+ }
437
+
438
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
439
+ // we use this to determine which events to fire
440
+ // otherwise when we resync from scratch -- all notifications will fire
441
+ const initialVersionMap = {}
442
+ const globalMutationMap = {}
443
+ await authState.keys.transaction(async () => {
444
+ const collectionsToHandle = new Set(collections)
445
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
446
+ const attemptsMap = {}
447
+ // keep executing till all collections are done
448
+ // sometimes a single patch request will not return all the patches (God knows why)
449
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
450
+ while (collectionsToHandle.size) {
451
+ const states = {}
452
+ const nodes = []
453
+
454
+ for (const name of collectionsToHandle) {
455
+ const result = await authState.keys.get('app-state-sync-version', [name])
456
+ let state = result[name]
457
+ if (state) {
458
+ if (typeof initialVersionMap[name] === 'undefined') {
459
+ initialVersionMap[name] = state.version
460
+ }
461
+ }
462
+ else {
463
+ state = Utils_1.newLTHashState()
464
+ }
465
+ states[name] = state
466
+ logger.info(`resyncing ${name} from v${state.version}`)
467
+ nodes.push({
468
+ tag: 'collection',
469
+ attrs: {
470
+ name,
471
+ version: state.version.toString(),
472
+ // return snapshot if being synced from scratch
473
+ 'return_snapshot': (!state.version).toString()
474
+ }
475
+ })
476
+ }
477
+
478
+ const result = await query({
479
+ tag: 'iq',
480
+ attrs: {
481
+ to: WABinary_1.S_WHATSAPP_NET,
482
+ xmlns: 'w:sync:app:state',
483
+ type: 'set'
484
+ },
485
+ content: [
486
+ {
487
+ tag: 'sync',
488
+ attrs: {},
489
+ content: nodes
490
+ }
491
+ ]
492
+ })
493
+
494
+ // extract from binary node
495
+ const decoded = await Utils_1.extractSyncdPatches(result, config?.options)
496
+
497
+ for (const key in decoded) {
498
+ const name = key
499
+ const { patches, hasMorePatches, snapshot } = decoded[name]
500
+ try {
501
+ if (snapshot) {
502
+ const { state: newState, mutationMap } = await Utils_1.decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot)
503
+ states[name] = newState
504
+ Object.assign(globalMutationMap, mutationMap)
505
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
506
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
507
+ }
508
+
509
+ // only process if there are syncd patches
510
+ if (patches.length) {
511
+ const { state: newState, mutationMap } = await Utils_1.decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
512
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
513
+ logger.info(`synced ${name} to v${newState.version}`)
514
+ initialVersionMap[name] = newState.version
515
+ Object.assign(globalMutationMap, mutationMap)
516
+ }
517
+
518
+ if (hasMorePatches) {
519
+ logger.info(`${name} has more patches...`)
520
+ }
521
+ else { // collection is done with sync
522
+ collectionsToHandle.delete(name)
523
+ }
524
+ }
525
+ catch (error) {
526
+ // if retry attempts overshoot
527
+ // or key not found
528
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
529
+ || error.output?.statusCode === 404
530
+ || error.name === 'TypeError'
531
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`)
532
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
533
+ // increment number of retries
534
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
535
+
536
+ if (isIrrecoverableError) {
537
+ // stop retrying
538
+ collectionsToHandle.delete(name)
539
+ }
540
+ }
541
+ }
542
+ }
543
+ })
544
+
545
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
546
+
547
+ for (const key in globalMutationMap) {
548
+ onMutation(globalMutationMap[key])
549
+ }
550
+ })
551
+
552
+ // source: https://github.com/WhiskeySockets/Baileys/pull/1677
553
+ const createCallLink = async (type, event, timeoutMs) => {
554
+ type = type?.toLowerCase()
555
+
556
+ if (!type || (type !== 'audio' && type !== 'video')) {
557
+ throw new Error('Make sure the type is audio or video!')
558
+ }
559
+
560
+ const result = await query({
561
+ tag: 'call',
562
+ attrs: {
563
+ id: generateMessageTag(),
564
+ to: '@call'
565
+ },
566
+ content: [{
567
+ tag: 'link_create',
568
+ attrs: {
569
+ media: type
570
+ },
571
+ content: event ? [{
572
+ tag: 'event',
573
+ attrs: {
574
+ start_time: String(event)
575
+ }
576
+ }] : undefined
577
+ }]
578
+ }, timeoutMs)
579
+
580
+ const child = WABinary_1.getBinaryNodeChild(result, 'link_create')
581
+ const token = child?.attrs?.token
582
+
583
+ return type === 'audio' ? Defaults_1.CALL_AUDIO_PREFIX + token : Defaults_1.CALL_VIDEO_PREFIX + token
584
+ }
585
+
586
+ const sendPresenceUpdate = async (type, toJid) => {
587
+ const me = authState.creds.me
588
+
589
+ if (type === 'available' || type === 'unavailable') {
590
+ if (!me.name) {
591
+ logger.warn('no name present, ignoring presence update request...')
592
+ return
593
+ }
594
+
595
+ ev.emit('connection.update', { isOnline: type === 'available' })
596
+ await sendNode({
597
+ tag: 'presence',
598
+ attrs: {
599
+ name: me.name.replace(/@/g, ''),
600
+ type
601
+ }
602
+ })
603
+ }
604
+ else {
605
+ const { server } = WABinary_1.jidDecode(toJid)
606
+
607
+ await sendNode({
608
+ tag: 'chatstate',
609
+ attrs: {
610
+ from: server === 'lid' ? me.lid : me.id,
611
+ to: toJid
612
+ },
613
+ content: [
614
+ {
615
+ tag: type === 'recording' ? 'composing' : type,
616
+ attrs: type === 'recording' ? { media: 'audio' } : {}
617
+ }
618
+ ]
619
+ })
620
+ }
621
+ }
622
+
623
+ /**
624
+ * @param toJid the jid to subscribe to
625
+ * @param tcToken token for subscription, use if present
626
+ */
627
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
628
+ tag: 'presence',
629
+ attrs: {
630
+ to: toJid,
631
+ id: generateMessageTag(),
632
+ type: 'subscribe'
633
+ },
634
+ content: tcToken
635
+ ? [
636
+ {
637
+ tag: 'tctoken',
638
+ attrs: {},
639
+ content: tcToken
640
+ }
641
+ ]
642
+ : undefined
643
+ }))
644
+
645
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
646
+ let presence
647
+ const jid = attrs.from
648
+ const participant = attrs.participant || attrs.from
649
+
650
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
651
+ return
652
+ }
653
+
654
+ if (tag === 'presence') {
655
+ presence = {
656
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
657
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
658
+ }
659
+ }
660
+
661
+ else if (Array.isArray(content)) {
662
+ const [firstChild] = content
663
+ let type = firstChild.tag
664
+
665
+ if (type === 'paused') {
666
+ type = 'available'
667
+ }
668
+
669
+ if (firstChild.attrs?.media === 'audio') {
670
+ type = 'recording'
671
+ }
672
+
673
+ presence = { lastKnownPresence: type }
674
+ }
675
+
676
+ else {
677
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
678
+ }
679
+
680
+ if (presence) {
681
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
682
+ }
683
+ }
684
+
685
+ const appPatch = async (patchCreate) => {
686
+ const name = patchCreate.type
687
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
688
+
689
+ if (!myAppStateKeyId) {
690
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 })
691
+ }
692
+
693
+ let initial
694
+ let encodeResult
695
+
696
+ await processingMutex.mutex(async () => {
697
+ await authState.keys.transaction(async () => {
698
+ logger.debug({ patch: patchCreate }, 'applying app patch')
699
+ await resyncAppState([name], false)
700
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
701
+ initial = currentSyncVersion || Utils_1.newLTHashState()
702
+ encodeResult = await Utils_1.encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
703
+ const { patch, state } = encodeResult
704
+
705
+ const node = {
706
+ tag: 'iq',
707
+ attrs: {
708
+ to: WABinary_1.S_WHATSAPP_NET,
709
+ type: 'set',
710
+ xmlns: 'w:sync:app:state'
711
+ },
712
+ content: [
713
+ {
714
+ tag: 'sync',
715
+ attrs: {},
716
+ content: [
717
+ {
718
+ tag: 'collection',
719
+ attrs: {
720
+ name,
721
+ version: (state.version - 1).toString(),
722
+ 'return_snapshot': 'false'
723
+ },
724
+ content: [
725
+ {
726
+ tag: 'patch',
727
+ attrs: {},
728
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
729
+ }
730
+ ]
731
+ }
732
+ ]
733
+ }
734
+ ]
735
+ }
736
+ await query(node)
737
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
738
+ })
739
+ })
740
+
741
+ if (config.emitOwnEvents) {
742
+ const { onMutation } = newAppStateChunkHandler(false)
743
+ const { mutationMap } = await Utils_1.decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger)
744
+
745
+ for (const key in mutationMap) {
746
+ onMutation(mutationMap[key])
747
+ }
748
+ }
749
+ }
750
+
751
+ /** sending non-abt props may fix QR scan fail if server expects */
752
+ const fetchProps = async () => {
753
+ const resultNode = await query({
754
+ tag: 'iq',
755
+ attrs: {
756
+ to: WABinary_1.S_WHATSAPP_NET,
757
+ xmlns: 'w',
758
+ type: 'get',
759
+ },
760
+ content: [
761
+ { tag: 'props', attrs: {
762
+ protocol: '2',
763
+ hash: authState?.creds?.lastPropHash || ''
764
+ } }
765
+ ]
766
+ })
767
+
768
+ const propsNode = WABinary_1.getBinaryNodeChild(resultNode, 'props')
769
+ let props = {}
770
+
771
+ if (propsNode) {
772
+ if (propsNode.attrs?.hash) { // on some clients, the hash is returning as undefined
773
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
774
+ ev.emit('creds.update', authState.creds)
775
+ }
776
+
777
+ props = WABinary_1.reduceBinaryNodeToDictionary(propsNode, 'prop')
778
+ }
779
+ logger.debug('fetched props')
780
+ return props
781
+ }
782
+
783
+ /**
784
+ * modify a chat -- mark unread, read etc.
785
+ * lastMessages must be sorted in reverse chronologically
786
+ * requires the last messages till the last message received required for archive & unread
787
+ */
788
+ const chatModify = (mod, jid) => {
789
+ const patch = Utils_1.chatModificationToAppPatch(mod, jid)
790
+ return appPatch(patch)
791
+ }
792
+
793
+ /**
794
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
795
+ */
796
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
797
+ return chatModify({
798
+ disableLinkPreviews: {
799
+ isPreviewsDisabled
800
+ }
801
+ }, '')
802
+ }
803
+
804
+ /**
805
+ * Star or Unstar a message
806
+ */
807
+ const star = (jid, messages, star) => {
808
+ return chatModify({
809
+ star: {
810
+ messages,
811
+ star
812
+ }
813
+ }, jid)
814
+ }
815
+
816
+ /**
817
+ * Add Or Edit Contact
818
+ */
819
+ const addOrEditContact = (jid, contact) => {
820
+ return chatModify({
821
+ contact
822
+ }, jid)
823
+ }
824
+
825
+ /**
826
+ * Remove Contact
827
+ */
828
+ const removeContact = (jid) => {
829
+ return chatModify({
830
+ contact: null
831
+ }, jid)
832
+ }
833
+
834
+ /**
835
+ * Adds label
836
+ */
837
+ const addLabel = (jid, labels) => {
838
+ return chatModify({
839
+ addLabel: {
840
+ ...labels
841
+ }
842
+ }, jid)
843
+ }
844
+
845
+ /**
846
+ * Adds label for the chats
847
+ */
848
+ const addChatLabel = (jid, labelId) => {
849
+ return chatModify({
850
+ addChatLabel: {
851
+ labelId
852
+ }
853
+ }, jid)
854
+ }
855
+
856
+ /**
857
+ * Removes label for the chat
858
+ */
859
+ const removeChatLabel = (jid, labelId) => {
860
+ return chatModify({
861
+ removeChatLabel: {
862
+ labelId
863
+ }
864
+ }, jid)
865
+ }
866
+
867
+ /**
868
+ * Adds label for the message
869
+ */
870
+ const addMessageLabel = (jid, messageId, labelId) => {
871
+ return chatModify({
872
+ addMessageLabel: {
873
+ messageId,
874
+ labelId
875
+ }
876
+ }, jid)
877
+ }
878
+
879
+ /**
880
+ * Removes label for the message
881
+ */
882
+ const removeMessageLabel = (jid, messageId, labelId) => {
883
+ return chatModify({
884
+ removeMessageLabel: {
885
+ messageId,
886
+ labelId
887
+ }
888
+ }, jid)
889
+ }
890
+
891
+ /**
892
+ * Removes Chats
893
+ */
894
+ const clearMessage = (jid, key, timeStamp) => {
895
+ return chatModify({
896
+ delete: true,
897
+ lastMessages: [{
898
+ key: key,
899
+ messageTimestamp: timeStamp
900
+ }],
901
+ }, jid)
902
+ }
903
+
904
+ /**
905
+ * queries need to be fired on connection open
906
+ * help ensure parity with WA Web
907
+ * */
908
+ const executeInitQueries = async () => {
909
+ await Promise.all([
910
+ fetchProps(),
911
+ fetchBlocklist(),
912
+ fetchPrivacySettings(),
913
+ ])
914
+ }
915
+
916
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
917
+ ev.emit('messages.upsert', { messages: [msg], type })
918
+ if (!!msg.pushName) {
919
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid)
920
+ jid = WABinary_1.jidNormalizedUser(jid)
921
+
922
+ if (!msg.key.fromMe) {
923
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
924
+ }
925
+
926
+ // update our pushname too
927
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
928
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
929
+ }
930
+ }
931
+
932
+ const historyMsg = Utils_1.getHistoryMsg(msg.message)
933
+ const shouldProcessHistoryMsg = historyMsg
934
+ ? (shouldSyncHistoryMessage(historyMsg)
935
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
936
+ : false
937
+
938
+ if (historyMsg && syncState === Types_1.SyncState.AwaitingInitialSync) {
939
+ if (awaitingSyncTimeout) {
940
+ clearTimeout(awaitingSyncTimeout)
941
+ awaitingSyncTimeout = undefined
942
+ }
943
+
944
+ if (shouldProcessHistoryMsg) {
945
+ syncState = Types_1.SyncState.Syncing
946
+ logger.info('Transitioned to Syncing state')
947
+ // Let doAppStateSync handle the final flush after it`s done
948
+ } else {
949
+ syncState = Types_1.SyncState.Online
950
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
951
+ ev.flush()
952
+ }
953
+ }
954
+
955
+ const doAppStateSync = async () => {
956
+ if (syncState === Types_1.SyncState.Syncing) {
957
+ logger.info('Doing app state sync')
958
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true)
959
+
960
+ // Sync is complete, go online and flush everything
961
+ syncState = Types_1.SyncState.Online
962
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
963
+ ev.flush()
964
+
965
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
966
+ ev.emit('creds.update', { accountSyncCounter })
967
+ }
968
+ }
969
+
970
+ await Promise.all([
971
+ (async () => {
972
+ if (shouldProcessHistoryMsg) {
973
+ await doAppStateSync()
974
+ }
975
+ })(),
976
+ Utils_1.processMessage(msg, {
977
+ shouldProcessHistoryMsg,
978
+ placeholderResendCache,
979
+ ev,
980
+ creds: authState.creds,
981
+ keyStore: authState.keys,
982
+ logger,
983
+ options: config.options,
984
+ getMessage: config.getMessage,
985
+ })
986
+ ])
987
+
988
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === Types_1.SyncState.Syncing) {
989
+ logger.info('App state sync key arrived, triggering app state sync')
990
+ await doAppStateSync()
991
+ }
992
+ })
993
+
994
+ ws.on('CB:presence', handlePresenceUpdate)
995
+ ws.on('CB:chatstate', handlePresenceUpdate)
996
+ ws.on('CB:ib,,dirty', async (node) => {
997
+ const { attrs } = WABinary_1.getBinaryNodeChild(node, 'dirty')
998
+ const type = attrs.type
999
+
1000
+ switch (type) {
1001
+ case 'account_sync':
1002
+ if (attrs.timestamp) {
1003
+ let { lastAccountSyncTimestamp } = authState.creds
1004
+ if (lastAccountSyncTimestamp) {
1005
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
1006
+ }
1007
+ lastAccountSyncTimestamp = +attrs.timestamp
1008
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
1009
+ }
1010
+ break
1011
+ case 'groups':
1012
+ await groupFetchAllParticipating()
1013
+ await cleanDirtyBits('groups')
1014
+ break
1015
+ default:
1016
+ logger.info({ node }, 'received unknown sync')
1017
+ break
1018
+ }
1019
+ })
1020
+
1021
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1022
+ if (connection === 'open') {
1023
+ if (fireInitQueries) {
1024
+ executeInitQueries()
1025
+ .catch(error => onUnexpectedError(error, 'init queries'))
1026
+ }
1027
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
1028
+ .catch(error => onUnexpectedError(error, 'presence update requests'))
1029
+ }
1030
+
1031
+ if (!receivedPendingNotifications || syncState !== Types_1.SyncState.Connecting) {
1032
+ return
1033
+ }
1034
+
1035
+ syncState = Types_1.AwaitingInitialSync
1036
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
1037
+ ev.buffer()
1038
+
1039
+ const willSyncHistory = shouldSyncHistoryMessage(WAProto_1.proto.Message.HistorySyncNotification.fromObject({
1040
+ syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
1041
+ }))
1042
+
1043
+ if (!willSyncHistory) {
1044
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
1045
+ syncState = Types_1.SyncState.Online
1046
+ setTimeout(() => ev.flush(), 0)
1047
+ return
1048
+ }
1049
+
1050
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.')
1051
+
1052
+ if (awaitingSyncTimeout) {
1053
+ clearTimeout(awaitingSyncTimeout)
1054
+ }
1055
+
1056
+ awaitingSyncTimeout = setTimeout(() => {
1057
+ if (syncState === Types_1.SyncState.AwaitingInitialSync) {
1058
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
1059
+ syncState = Types_1.SyncState.Online
1060
+ ev.flush()
1061
+ }
1062
+ }, 20_000)
1063
+ })
1064
+
1065
+ return {
1066
+ ...suki,
1067
+ star,
1068
+ addOrEditContact,
1069
+ removeContact,
1070
+ processingMutex,
1071
+ fetchPrivacySettings,
1072
+ upsertMessage,
1073
+ appPatch,
1074
+ createCallLink,
1075
+ sendPresenceUpdate,
1076
+ presenceSubscribe,
1077
+ getBotListV2,
1078
+ getLidUser,
1079
+ onWhatsApp,
1080
+ fetchBlocklist,
1081
+ fetchStatus,
1082
+ fetchDisappearingDuration,
1083
+ updateProfilePicture,
1084
+ removeProfilePicture,
1085
+ updateProfileStatus,
1086
+ updateProfileName,
1087
+ updateBlockStatus,
1088
+ updateCallPrivacy,
1089
+ updateMessagesPrivacy,
1090
+ updateLastSeenPrivacy,
1091
+ updateOnlinePrivacy,
1092
+ updateProfilePicturePrivacy,
1093
+ updateStatusPrivacy,
1094
+ updateReadReceiptsPrivacy,
1095
+ updateGroupsAddPrivacy,
1096
+ updateDefaultDisappearingMode,
1097
+ updateDisableLinkPreviewsPrivacy,
1098
+ getBusinessProfile,
1099
+ resyncAppState,
1100
+ chatModify,
1101
+ cleanDirtyBits,
1102
+ addLabel,
1103
+ addChatLabel,
1104
+ removeChatLabel,
1105
+ addMessageLabel,
1106
+ removeMessageLabel,
1107
+ clearMessage
1108
+ }
1109
+ }
1110
+
904
1111
  module.exports = {
905
- makeChatsSocket
1112
+ makeChatsSocket
906
1113
  }