lordceaser-baileys 2.0.12 → 2.0.13

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