@neelegirl/baileys 1.5.5 → 1.5.7

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 (203) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +183 -10
  3. package/WAProto/WAProto.proto +5007 -0
  4. package/WAProto/index.d.ts +57712 -0
  5. package/WAProto/index.js +178969 -0
  6. package/lib/Defaults/baileys-version.json +3 -0
  7. package/lib/Defaults/index.d.ts +68 -0
  8. package/lib/Defaults/index.js +137 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/WASignalGroup/GroupProtocol.js +1909 -0
  11. package/lib/Signal/WASignalGroup/ciphertext_message.js +16 -0
  12. package/lib/Signal/WASignalGroup/generate-proto.sh +1 -0
  13. package/lib/Signal/WASignalGroup/group.proto +42 -0
  14. package/lib/Signal/WASignalGroup/group_cipher.js +120 -0
  15. package/lib/Signal/WASignalGroup/group_session_builder.js +46 -0
  16. package/lib/Signal/WASignalGroup/index.js +6 -0
  17. package/lib/Signal/WASignalGroup/keyhelper.js +21 -0
  18. package/lib/Signal/WASignalGroup/protobufs.js +3 -0
  19. package/lib/Signal/WASignalGroup/queue_job.js +69 -0
  20. package/lib/Signal/WASignalGroup/readme.md +6 -0
  21. package/lib/Signal/WASignalGroup/sender_chain_key.js +50 -0
  22. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +78 -0
  23. package/lib/Signal/WASignalGroup/sender_key_message.js +92 -0
  24. package/lib/Signal/WASignalGroup/sender_key_name.js +70 -0
  25. package/lib/Signal/WASignalGroup/sender_key_record.js +56 -0
  26. package/lib/Signal/WASignalGroup/sender_key_state.js +129 -0
  27. package/lib/Signal/WASignalGroup/sender_message_key.js +39 -0
  28. package/lib/Signal/libsignal.d.ts +4 -0
  29. package/lib/Signal/libsignal.js +162 -0
  30. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  31. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  32. package/lib/Socket/Client/index.d.ts +2 -0
  33. package/lib/Socket/Client/index.js +22 -0
  34. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  35. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  36. package/lib/Socket/Client/types.d.ts +16 -0
  37. package/lib/Socket/Client/types.js +18 -0
  38. package/lib/Socket/Client/websocket.d.ts +13 -0
  39. package/lib/Socket/Client/websocket.js +62 -0
  40. package/lib/Socket/business.d.ts +187 -0
  41. package/lib/Socket/business.js +268 -0
  42. package/lib/Socket/chats.d.ts +98 -0
  43. package/lib/Socket/chats.js +1113 -0
  44. package/lib/Socket/communities.d.ts +223 -0
  45. package/lib/Socket/communities.js +433 -0
  46. package/lib/Socket/groups.d.ts +131 -0
  47. package/lib/Socket/groups.js +352 -0
  48. package/lib/Socket/index.d.ts +191 -0
  49. package/lib/Socket/index.js +23 -0
  50. package/lib/Socket/messages-recv.d.ts +177 -0
  51. package/lib/Socket/messages-recv.js +1764 -0
  52. package/lib/Socket/messages-send.d.ts +168 -0
  53. package/lib/Socket/messages-send.js +1303 -0
  54. package/lib/Socket/mex.d.ts +2 -0
  55. package/lib/Socket/mex.js +47 -0
  56. package/lib/Socket/newsletter.d.ts +147 -0
  57. package/lib/Socket/newsletter.js +286 -0
  58. package/lib/Socket/registration.d.ts +266 -0
  59. package/lib/Socket/registration.js +166 -0
  60. package/lib/Socket/socket.d.ts +45 -0
  61. package/lib/Socket/socket.js +766 -0
  62. package/lib/Socket/usync.d.ts +37 -0
  63. package/lib/Socket/usync.js +83 -0
  64. package/lib/Store/index.d.ts +4 -0
  65. package/lib/Store/index.js +24 -0
  66. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  67. package/lib/Store/make-cache-manager-store.js +90 -0
  68. package/lib/Store/make-in-memory-store.d.ts +123 -0
  69. package/lib/Store/make-in-memory-store.js +429 -0
  70. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  71. package/lib/Store/make-ordered-dictionary.js +86 -0
  72. package/lib/Store/object-repository.d.ts +10 -0
  73. package/lib/Store/object-repository.js +31 -0
  74. package/lib/Types/Auth.d.ts +120 -0
  75. package/lib/Types/Auth.js +3 -0
  76. package/lib/Types/Call.d.ts +14 -0
  77. package/lib/Types/Call.js +3 -0
  78. package/lib/Types/Chat.d.ts +138 -0
  79. package/lib/Types/Chat.js +9 -0
  80. package/lib/Types/Contact.d.ts +20 -0
  81. package/lib/Types/Contact.js +3 -0
  82. package/lib/Types/Events.d.ts +229 -0
  83. package/lib/Types/Events.js +3 -0
  84. package/lib/Types/GroupMetadata.d.ts +66 -0
  85. package/lib/Types/GroupMetadata.js +3 -0
  86. package/lib/Types/Label.d.ts +48 -0
  87. package/lib/Types/Label.js +31 -0
  88. package/lib/Types/LabelAssociation.d.ts +35 -0
  89. package/lib/Types/LabelAssociation.js +13 -0
  90. package/lib/Types/Message.d.ts +473 -0
  91. package/lib/Types/Message.js +13 -0
  92. package/lib/Types/MexUpdates.d.ts +9 -0
  93. package/lib/Types/MexUpdates.js +18 -0
  94. package/lib/Types/Newsletter.d.ts +109 -0
  95. package/lib/Types/Newsletter.js +40 -0
  96. package/lib/Types/Product.d.ts +92 -0
  97. package/lib/Types/Product.js +3 -0
  98. package/lib/Types/Signal.d.ts +68 -0
  99. package/lib/Types/Signal.js +3 -0
  100. package/lib/Types/Socket.d.ts +122 -0
  101. package/lib/Types/Socket.js +3 -0
  102. package/lib/Types/State.d.ts +41 -0
  103. package/lib/Types/State.js +14 -0
  104. package/lib/Types/USync.d.ts +26 -0
  105. package/lib/Types/USync.js +3 -0
  106. package/lib/Types/index.d.ts +79 -0
  107. package/lib/Types/index.js +48 -0
  108. package/lib/Utils/auth-utils.d.ts +21 -0
  109. package/lib/Utils/auth-utils.js +205 -0
  110. package/lib/Utils/baileys-event-stream.d.ts +18 -0
  111. package/lib/Utils/baileys-event-stream.js +70 -0
  112. package/lib/Utils/business.d.ts +29 -0
  113. package/lib/Utils/business.js +255 -0
  114. package/lib/Utils/chat-utils.d.ts +82 -0
  115. package/lib/Utils/chat-utils.js +781 -0
  116. package/lib/Utils/check-npm-version.d.ts +15 -0
  117. package/lib/Utils/check-npm-version.js +52 -0
  118. package/lib/Utils/crypto.d.ts +56 -0
  119. package/lib/Utils/crypto.js +179 -0
  120. package/lib/Utils/decode-wa-message.d.ts +41 -0
  121. package/lib/Utils/decode-wa-message.js +253 -0
  122. package/lib/Utils/event-buffer.d.ts +39 -0
  123. package/lib/Utils/event-buffer.js +565 -0
  124. package/lib/Utils/generics.d.ts +129 -0
  125. package/lib/Utils/generics.js +618 -0
  126. package/lib/Utils/history.d.ts +23 -0
  127. package/lib/Utils/history.js +110 -0
  128. package/lib/Utils/index.d.ts +19 -0
  129. package/lib/Utils/index.js +41 -0
  130. package/lib/Utils/link-preview.d.ts +23 -0
  131. package/lib/Utils/link-preview.js +120 -0
  132. package/lib/Utils/logger.d.ts +13 -0
  133. package/lib/Utils/logger.js +7 -0
  134. package/lib/Utils/lt-hash.d.ts +14 -0
  135. package/lib/Utils/lt-hash.js +58 -0
  136. package/lib/Utils/make-mutex.d.ts +9 -0
  137. package/lib/Utils/make-mutex.js +49 -0
  138. package/lib/Utils/message-retry-manager.d.ts +82 -0
  139. package/lib/Utils/message-retry-manager.js +177 -0
  140. package/lib/Utils/messages-media.d.ts +129 -0
  141. package/lib/Utils/messages-media.js +806 -0
  142. package/lib/Utils/messages.d.ts +103 -0
  143. package/lib/Utils/messages.js +1579 -0
  144. package/lib/Utils/noise-handler.d.ts +20 -0
  145. package/lib/Utils/noise-handler.js +155 -0
  146. package/lib/Utils/process-message.d.ts +49 -0
  147. package/lib/Utils/process-message.js +428 -0
  148. package/lib/Utils/signal.d.ts +42 -0
  149. package/lib/Utils/signal.js +166 -0
  150. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  151. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  152. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  153. package/lib/Utils/use-multi-file-auth-state.js +238 -0
  154. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  155. package/lib/Utils/use-single-file-auth-state.js +80 -0
  156. package/lib/Utils/validate-connection.d.ts +13 -0
  157. package/lib/Utils/validate-connection.js +187 -0
  158. package/lib/WABinary/constants.d.ts +30 -0
  159. package/lib/WABinary/constants.js +1316 -0
  160. package/lib/WABinary/decode.d.ts +9 -0
  161. package/lib/WABinary/decode.js +288 -0
  162. package/lib/WABinary/encode.d.ts +3 -0
  163. package/lib/WABinary/encode.js +265 -0
  164. package/lib/WABinary/generic-utils.d.ts +28 -0
  165. package/lib/WABinary/generic-utils.js +142 -0
  166. package/lib/WABinary/index.d.ts +5 -0
  167. package/lib/WABinary/index.js +25 -0
  168. package/lib/WABinary/jid-utils.d.ts +53 -0
  169. package/lib/WABinary/jid-utils.js +92 -0
  170. package/lib/WABinary/types.d.ts +22 -0
  171. package/lib/WABinary/types.js +3 -0
  172. package/lib/WAM/BinaryInfo.d.ts +16 -0
  173. package/lib/WAM/BinaryInfo.js +17 -0
  174. package/lib/WAM/constants.d.ts +47 -0
  175. package/lib/WAM/constants.js +15371 -0
  176. package/lib/WAM/encode.d.ts +3 -0
  177. package/lib/WAM/encode.js +165 -0
  178. package/lib/WAM/index.d.ts +3 -0
  179. package/lib/WAM/index.js +23 -0
  180. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  181. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  182. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  183. package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  184. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  185. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  186. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  187. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  188. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  189. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  190. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  191. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  192. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  193. package/lib/WAUSync/Protocols/index.js +26 -0
  194. package/lib/WAUSync/USyncQuery.d.ts +31 -0
  195. package/lib/WAUSync/USyncQuery.js +92 -0
  196. package/lib/WAUSync/USyncUser.d.ts +12 -0
  197. package/lib/WAUSync/USyncUser.js +30 -0
  198. package/lib/WAUSync/index.d.ts +3 -0
  199. package/lib/WAUSync/index.js +23 -0
  200. package/lib/index.d.ts +13 -0
  201. package/lib/index.js +33 -0
  202. package/package.json +88 -10
  203. package/index.js +0 -38
@@ -0,0 +1,1113 @@
1
+ "use strict"
2
+
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod }
5
+ }
6
+
7
+ Object.defineProperty(exports, "__esModule", { value: true })
8
+
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
10
+ const boom_1 = require("@hapi/boom")
11
+ const WAProto_1 = require("../../WAProto")
12
+ const Defaults_1 = require("../Defaults")
13
+ const Types_1 = require("../Types")
14
+ const Utils_1 = require("../Utils")
15
+ const make_mutex_1 = require("../Utils/make-mutex")
16
+ const WABinary_1 = require("../WABinary")
17
+ const WAUSync_1 = require("../WAUSync")
18
+ const usync_1 = require("./usync")
19
+ const MAX_SYNC_ATTEMPTS = 2
20
+
21
+ const makeChatsSocket = (config) => {
22
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config
23
+ const Neele = usync_1.makeUSyncSocket(config)
24
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, groupFetchAllParticipating } = Neele
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 Neele.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 Neele.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 Neele.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 Neele.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
+ ...Neele,
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
+
1111
+ module.exports = {
1112
+ makeChatsSocket
1113
+ }