@skycodee/baileys 8.0.3 → 8.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/package.json +4 -4
  2. package/src/Defaults/baileys-version.json +1 -0
  3. package/src/Defaults/index.ts +149 -0
  4. package/src/Signal/Group/ciphertext-message.ts +9 -0
  5. package/src/Signal/Group/group-session-builder.ts +56 -0
  6. package/src/Signal/Group/group_cipher.ts +117 -0
  7. package/src/Signal/Group/index.ts +11 -0
  8. package/src/Signal/Group/keyhelper.ts +28 -0
  9. package/src/Signal/Group/sender-chain-key.ts +34 -0
  10. package/src/Signal/Group/sender-key-distribution-message.ts +95 -0
  11. package/src/Signal/Group/sender-key-message.ts +96 -0
  12. package/src/Signal/Group/sender-key-name.ts +66 -0
  13. package/src/Signal/Group/sender-key-record.ts +69 -0
  14. package/src/Signal/Group/sender-key-state.ts +134 -0
  15. package/src/Signal/Group/sender-message-key.ts +36 -0
  16. package/src/Signal/libsignal.ts +521 -0
  17. package/src/Signal/lid-mapping.ts +328 -0
  18. package/src/Socket/Client/index.ts +2 -0
  19. package/src/Socket/Client/types.ts +22 -0
  20. package/src/Socket/Client/websocket.ts +63 -0
  21. package/src/Socket/business.ts +424 -0
  22. package/src/Socket/chats.ts +1272 -0
  23. package/src/Socket/communities.ts +477 -0
  24. package/src/Socket/groups.ts +361 -0
  25. package/src/Socket/index.ts +15 -0
  26. package/src/Socket/messages-recv.ts +1668 -0
  27. package/src/Socket/messages-send.ts +1296 -0
  28. package/src/Socket/mex.ts +58 -0
  29. package/src/Socket/newsletter.ts +229 -0
  30. package/src/Socket/socket.ts +1184 -0
  31. package/src/Types/Auth.ts +116 -0
  32. package/src/Types/Bussines.ts +20 -0
  33. package/src/Types/Call.ts +15 -0
  34. package/src/Types/Chat.ts +138 -0
  35. package/src/Types/Contact.ts +24 -0
  36. package/src/Types/Events.ts +159 -0
  37. package/src/Types/GroupMetadata.ts +70 -0
  38. package/src/Types/Label.ts +48 -0
  39. package/src/Types/LabelAssociation.ts +35 -0
  40. package/src/Types/Message.ts +380 -0
  41. package/src/Types/Newsletter.ts +98 -0
  42. package/src/Types/Product.ts +85 -0
  43. package/src/Types/Signal.ts +76 -0
  44. package/src/Types/Socket.ts +150 -0
  45. package/src/Types/State.ts +43 -0
  46. package/src/Types/USync.ts +27 -0
  47. package/src/Types/globals.d.ts +8 -0
  48. package/src/Types/index.ts +67 -0
  49. package/src/Utils/auth-utils.ts +368 -0
  50. package/src/Utils/browser-utils.ts +31 -0
  51. package/src/Utils/business.ts +286 -0
  52. package/src/Utils/chat-utils.ts +974 -0
  53. package/src/Utils/crypto.ts +147 -0
  54. package/src/Utils/decode-wa-message.ts +355 -0
  55. package/src/Utils/event-buffer.ts +692 -0
  56. package/src/Utils/generics.ts +474 -0
  57. package/src/Utils/history.ts +161 -0
  58. package/src/Utils/identity-change-handler.ts +83 -0
  59. package/src/Utils/index.ts +19 -0
  60. package/src/Utils/link-preview.ts +111 -0
  61. package/src/Utils/logger.ts +13 -0
  62. package/src/Utils/lt-hash.ts +8 -0
  63. package/src/Utils/make-mutex.ts +42 -0
  64. package/src/Utils/message-retry-manager.ts +295 -0
  65. package/src/Utils/messages-media.ts +984 -0
  66. package/src/Utils/messages.ts +1097 -0
  67. package/src/Utils/noise-handler.ts +268 -0
  68. package/src/Utils/pre-key-manager.ts +126 -0
  69. package/src/Utils/process-message.ts +670 -0
  70. package/src/Utils/reporting-utils.ts +344 -0
  71. package/src/Utils/signal.ts +214 -0
  72. package/src/Utils/sync-action-utils.ts +74 -0
  73. package/src/Utils/tc-token-utils.ts +34 -0
  74. package/src/Utils/use-multi-file-auth-state.ts +136 -0
  75. package/src/Utils/validate-connection.ts +253 -0
  76. package/src/WABinary/constants.ts +1305 -0
  77. package/src/WABinary/decode.ts +308 -0
  78. package/src/WABinary/encode.ts +258 -0
  79. package/src/WABinary/generic-utils.ts +141 -0
  80. package/src/WABinary/index.ts +5 -0
  81. package/src/WABinary/jid-utils.ts +128 -0
  82. package/src/WABinary/types.ts +17 -0
  83. package/src/WAM/BinaryInfo.ts +12 -0
  84. package/src/WAM/constants.ts +22889 -0
  85. package/src/WAM/encode.ts +169 -0
  86. package/src/WAM/index.ts +3 -0
  87. package/src/WAUSync/Protocols/USyncContactProtocol.ts +32 -0
  88. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +78 -0
  89. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +35 -0
  90. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +44 -0
  91. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +76 -0
  92. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +33 -0
  93. package/src/WAUSync/Protocols/index.ts +4 -0
  94. package/src/WAUSync/USyncQuery.ts +133 -0
  95. package/src/WAUSync/USyncUser.ts +32 -0
  96. package/src/WAUSync/index.ts +3 -0
  97. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +22 -0
  98. package/src/__tests__/Signal/lid-mapping.test.ts +47 -0
  99. package/src/__tests__/Socket/identity-change-handling.test.ts +207 -0
  100. package/src/__tests__/TestUtils/session.ts +47 -0
  101. package/src/__tests__/Utils/generics.test.ts +70 -0
  102. package/src/__tests__/Utils/history.test.ts +362 -0
  103. package/src/__tests__/Utils/messages-media.test.ts +405 -0
  104. package/src/__tests__/Utils/noise-handler.test.ts +339 -0
  105. package/src/__tests__/Utils/process-message.test.ts +138 -0
  106. package/src/__tests__/Utils/process-sync-action.test.ts +359 -0
  107. package/src/__tests__/Utils/reporting-utils.test.ts +160 -0
  108. package/src/__tests__/Utils/signal.test.ts +69 -0
  109. package/src/__tests__/Utils/sync-action-utils.test.ts +183 -0
  110. package/src/__tests__/binary/connection-deadlock.test.ts +54 -0
  111. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +60 -0
  112. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +644 -0
  113. package/src/__tests__/proto-tojson-long.test.ts +31 -0
  114. package/src/index.ts +13 -0
@@ -0,0 +1,1272 @@
1
+ import NodeCache from '@cacheable/node-cache'
2
+ import { Boom } from '@hapi/boom'
3
+ import { proto } from '../../WAProto/index.js'
4
+ import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults'
5
+ import type {
6
+ BotListInfo,
7
+ CacheStore,
8
+ ChatModification,
9
+ ChatMutation,
10
+ LTHashState,
11
+ MessageUpsertType,
12
+ PresenceData,
13
+ SocketConfig,
14
+ WABusinessHoursConfig,
15
+ WABusinessProfile,
16
+ WAMediaUpload,
17
+ WAMessage,
18
+ WAPatchCreate,
19
+ WAPatchName,
20
+ WAPresence,
21
+ WAPrivacyCallValue,
22
+ WAPrivacyGroupAddValue,
23
+ WAPrivacyMessagesValue,
24
+ WAPrivacyOnlineValue,
25
+ WAPrivacyValue,
26
+ WAReadReceiptsValue
27
+ } from '../Types'
28
+ import { ALL_WA_PATCH_NAMES } from '../Types'
29
+ import type { QuickReplyAction } from '../Types/Bussines.js'
30
+ import type { LabelActionBody } from '../Types/Label'
31
+ import { SyncState } from '../Types/State'
32
+ import {
33
+ chatModificationToAppPatch,
34
+ type ChatMutationMap,
35
+ decodePatches,
36
+ decodeSyncdSnapshot,
37
+ encodeSyncdPatch,
38
+ extractSyncdPatches,
39
+ generateProfilePicture,
40
+ getHistoryMsg,
41
+ newLTHashState,
42
+ processSyncAction
43
+ } from '../Utils'
44
+ import { makeMutex } from '../Utils/make-mutex'
45
+ import processMessage from '../Utils/process-message'
46
+ import { buildTcTokenFromJid } from '../Utils/tc-token-utils'
47
+ import {
48
+ type BinaryNode,
49
+ getBinaryNodeChild,
50
+ getBinaryNodeChildren,
51
+ jidDecode,
52
+ jidNormalizedUser,
53
+ reduceBinaryNodeToDictionary,
54
+ S_WHATSAPP_NET
55
+ } from '../WABinary'
56
+ import { USyncQuery, USyncUser } from '../WAUSync'
57
+ import { makeSocket } from './socket.js'
58
+ const MAX_SYNC_ATTEMPTS = 2
59
+
60
+ export const makeChatsSocket = (config: SocketConfig) => {
61
+ const {
62
+ logger,
63
+ markOnlineOnConnect,
64
+ fireInitQueries,
65
+ appStateMacVerification,
66
+ shouldIgnoreJid,
67
+ shouldSyncHistoryMessage,
68
+ getMessage
69
+ } = config
70
+ const sock = makeSocket(config)
71
+ const {
72
+ ev,
73
+ ws,
74
+ authState,
75
+ generateMessageTag,
76
+ sendNode,
77
+ query,
78
+ signalRepository,
79
+ onUnexpectedError,
80
+ sendUnifiedSession
81
+ } = sock
82
+
83
+ let privacySettings: { [_: string]: string } | undefined
84
+
85
+ let syncState: SyncState = SyncState.Connecting
86
+
87
+ /** this mutex ensures that messages are processed in order */
88
+ const messageMutex = makeMutex()
89
+
90
+ /** this mutex ensures that receipts are processed in order */
91
+ const receiptMutex = makeMutex()
92
+
93
+ /** this mutex ensures that app state patches are processed in order */
94
+ const appStatePatchMutex = makeMutex()
95
+
96
+ /** this mutex ensures that notifications are processed in order */
97
+ const notificationMutex = makeMutex()
98
+
99
+ // Timeout for AwaitingInitialSync state
100
+ let awaitingSyncTimeout: NodeJS.Timeout | undefined
101
+
102
+ const placeholderResendCache =
103
+ config.placeholderResendCache ||
104
+ (new NodeCache<number>({
105
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
106
+ useClones: false
107
+ }) as CacheStore)
108
+
109
+ if (!config.placeholderResendCache) {
110
+ config.placeholderResendCache = placeholderResendCache
111
+ }
112
+
113
+ /** helper function to fetch the given app state sync key */
114
+ const getAppStateSyncKey = async (keyId: string) => {
115
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
116
+ return key
117
+ }
118
+
119
+ const fetchPrivacySettings = async (force = false) => {
120
+ if (!privacySettings || force) {
121
+ const { content } = await query({
122
+ tag: 'iq',
123
+ attrs: {
124
+ xmlns: 'privacy',
125
+ to: S_WHATSAPP_NET,
126
+ type: 'get'
127
+ },
128
+ content: [{ tag: 'privacy', attrs: {} }]
129
+ })
130
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0] as BinaryNode, 'category')
131
+ }
132
+
133
+ return privacySettings
134
+ }
135
+
136
+ /** helper function to run a privacy IQ query */
137
+ const privacyQuery = async (name: string, value: string) => {
138
+ await query({
139
+ tag: 'iq',
140
+ attrs: {
141
+ xmlns: 'privacy',
142
+ to: S_WHATSAPP_NET,
143
+ type: 'set'
144
+ },
145
+ content: [
146
+ {
147
+ tag: 'privacy',
148
+ attrs: {},
149
+ content: [
150
+ {
151
+ tag: 'category',
152
+ attrs: { name, value }
153
+ }
154
+ ]
155
+ }
156
+ ]
157
+ })
158
+ }
159
+
160
+ const updateMessagesPrivacy = async (value: WAPrivacyMessagesValue) => {
161
+ await privacyQuery('messages', value)
162
+ }
163
+
164
+ const updateCallPrivacy = async (value: WAPrivacyCallValue) => {
165
+ await privacyQuery('calladd', value)
166
+ }
167
+
168
+ const updateLastSeenPrivacy = async (value: WAPrivacyValue) => {
169
+ await privacyQuery('last', value)
170
+ }
171
+
172
+ const updateOnlinePrivacy = async (value: WAPrivacyOnlineValue) => {
173
+ await privacyQuery('online', value)
174
+ }
175
+
176
+ const updateProfilePicturePrivacy = async (value: WAPrivacyValue) => {
177
+ await privacyQuery('profile', value)
178
+ }
179
+
180
+ const updateStatusPrivacy = async (value: WAPrivacyValue) => {
181
+ await privacyQuery('status', value)
182
+ }
183
+
184
+ const updateReadReceiptsPrivacy = async (value: WAReadReceiptsValue) => {
185
+ await privacyQuery('readreceipts', value)
186
+ }
187
+
188
+ const updateGroupsAddPrivacy = async (value: WAPrivacyGroupAddValue) => {
189
+ await privacyQuery('groupadd', value)
190
+ }
191
+
192
+ const updateDefaultDisappearingMode = async (duration: number) => {
193
+ await query({
194
+ tag: 'iq',
195
+ attrs: {
196
+ xmlns: 'disappearing_mode',
197
+ to: S_WHATSAPP_NET,
198
+ type: 'set'
199
+ },
200
+ content: [
201
+ {
202
+ tag: 'disappearing_mode',
203
+ attrs: {
204
+ duration: duration.toString()
205
+ }
206
+ }
207
+ ]
208
+ })
209
+ }
210
+
211
+ const getBotListV2 = async () => {
212
+ const resp = await query({
213
+ tag: 'iq',
214
+ attrs: {
215
+ xmlns: 'bot',
216
+ to: S_WHATSAPP_NET,
217
+ type: 'get'
218
+ },
219
+ content: [
220
+ {
221
+ tag: 'bot',
222
+ attrs: {
223
+ v: '2'
224
+ }
225
+ }
226
+ ]
227
+ })
228
+
229
+ const botNode = getBinaryNodeChild(resp, 'bot')
230
+
231
+ const botList: BotListInfo[] = []
232
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
233
+ if (section.attrs.type === 'all') {
234
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
235
+ botList.push({
236
+ jid: bot.attrs.jid!,
237
+ personaId: bot.attrs['persona_id']!
238
+ })
239
+ }
240
+ }
241
+ }
242
+
243
+ return botList
244
+ }
245
+
246
+ const fetchStatus = async (...jids: string[]) => {
247
+ const usyncQuery = new USyncQuery().withStatusProtocol()
248
+
249
+ for (const jid of jids) {
250
+ usyncQuery.withUser(new USyncUser().withId(jid))
251
+ }
252
+
253
+ const result = await sock.executeUSyncQuery(usyncQuery)
254
+ if (result) {
255
+ return result.list
256
+ }
257
+ }
258
+
259
+ const fetchDisappearingDuration = async (...jids: string[]) => {
260
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
261
+
262
+ for (const jid of jids) {
263
+ usyncQuery.withUser(new USyncUser().withId(jid))
264
+ }
265
+
266
+ const result = await sock.executeUSyncQuery(usyncQuery)
267
+ if (result) {
268
+ return result.list
269
+ }
270
+ }
271
+
272
+ /** update the profile picture for yourself or a group */
273
+ const updateProfilePicture = async (
274
+ jid: string,
275
+ content: WAMediaUpload,
276
+ dimensions?: { width: number; height: number }
277
+ ) => {
278
+ let targetJid
279
+ if (!jid) {
280
+ throw new Boom(
281
+ 'Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update'
282
+ )
283
+ }
284
+
285
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me!.id)) {
286
+ targetJid = jidNormalizedUser(jid) // in case it is someone other than us
287
+ } else {
288
+ targetJid = undefined
289
+ }
290
+
291
+ const { img } = await generateProfilePicture(content, dimensions)
292
+ await query({
293
+ tag: 'iq',
294
+ attrs: {
295
+ to: S_WHATSAPP_NET,
296
+ type: 'set',
297
+ xmlns: 'w:profile:picture',
298
+ ...(targetJid ? { target: targetJid } : {})
299
+ },
300
+ content: [
301
+ {
302
+ tag: 'picture',
303
+ attrs: { type: 'image' },
304
+ content: img
305
+ }
306
+ ]
307
+ })
308
+ }
309
+
310
+ /** remove the profile picture for yourself or a group */
311
+ const removeProfilePicture = async (jid: string) => {
312
+ let targetJid
313
+ if (!jid) {
314
+ throw new Boom(
315
+ 'Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update'
316
+ )
317
+ }
318
+
319
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me!.id)) {
320
+ targetJid = jidNormalizedUser(jid) // in case it is someone other than us
321
+ } else {
322
+ targetJid = undefined
323
+ }
324
+
325
+ await query({
326
+ tag: 'iq',
327
+ attrs: {
328
+ to: S_WHATSAPP_NET,
329
+ type: 'set',
330
+ xmlns: 'w:profile:picture',
331
+ ...(targetJid ? { target: targetJid } : {})
332
+ }
333
+ })
334
+ }
335
+
336
+ /** update the profile status for yourself */
337
+ const updateProfileStatus = async (status: string) => {
338
+ await query({
339
+ tag: 'iq',
340
+ attrs: {
341
+ to: S_WHATSAPP_NET,
342
+ type: 'set',
343
+ xmlns: 'status'
344
+ },
345
+ content: [
346
+ {
347
+ tag: 'status',
348
+ attrs: {},
349
+ content: Buffer.from(status, 'utf-8')
350
+ }
351
+ ]
352
+ })
353
+ }
354
+
355
+ const updateProfileName = async (name: string) => {
356
+ await chatModify({ pushNameSetting: name }, '')
357
+ }
358
+
359
+ const fetchBlocklist = async () => {
360
+ const result = await query({
361
+ tag: 'iq',
362
+ attrs: {
363
+ xmlns: 'blocklist',
364
+ to: S_WHATSAPP_NET,
365
+ type: 'get'
366
+ }
367
+ })
368
+
369
+ const listNode = getBinaryNodeChild(result, 'list')
370
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid)
371
+ }
372
+
373
+ const updateBlockStatus = async (jid: string, action: 'block' | 'unblock') => {
374
+ await query({
375
+ tag: 'iq',
376
+ attrs: {
377
+ xmlns: 'blocklist',
378
+ to: S_WHATSAPP_NET,
379
+ type: 'set'
380
+ },
381
+ content: [
382
+ {
383
+ tag: 'item',
384
+ attrs: {
385
+ action,
386
+ jid
387
+ }
388
+ }
389
+ ]
390
+ })
391
+ }
392
+
393
+ const getBusinessProfile = async (jid: string): Promise<WABusinessProfile | void> => {
394
+ const results = await query({
395
+ tag: 'iq',
396
+ attrs: {
397
+ to: 's.whatsapp.net',
398
+ xmlns: 'w:biz',
399
+ type: 'get'
400
+ },
401
+ content: [
402
+ {
403
+ tag: 'business_profile',
404
+ attrs: { v: '244' },
405
+ content: [
406
+ {
407
+ tag: 'profile',
408
+ attrs: { jid }
409
+ }
410
+ ]
411
+ }
412
+ ]
413
+ })
414
+
415
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
416
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
417
+ if (profiles) {
418
+ const address = getBinaryNodeChild(profiles, 'address')
419
+ const description = getBinaryNodeChild(profiles, 'description')
420
+ const website = getBinaryNodeChild(profiles, 'website')
421
+ const email = getBinaryNodeChild(profiles, 'email')
422
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
423
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
424
+ const businessHoursConfig = businessHours
425
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
426
+ : undefined
427
+ const websiteStr = website?.content?.toString()
428
+ return {
429
+ wid: profiles.attrs?.jid,
430
+ address: address?.content?.toString(),
431
+ description: description?.content?.toString() || '',
432
+ website: websiteStr ? [websiteStr] : [],
433
+ email: email?.content?.toString(),
434
+ category: category?.content?.toString(),
435
+ business_hours: {
436
+ timezone: businessHours?.attrs?.timezone,
437
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs as unknown as WABusinessHoursConfig)
438
+ }
439
+ }
440
+ }
441
+ }
442
+
443
+ const cleanDirtyBits = async (type: 'account_sync' | 'groups', fromTimestamp?: number | string) => {
444
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
445
+ await sendNode({
446
+ tag: 'iq',
447
+ attrs: {
448
+ to: S_WHATSAPP_NET,
449
+ type: 'set',
450
+ xmlns: 'urn:xmpp:whatsapp:dirty',
451
+ id: generateMessageTag()
452
+ },
453
+ content: [
454
+ {
455
+ tag: 'clean',
456
+ attrs: {
457
+ type,
458
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
459
+ }
460
+ }
461
+ ]
462
+ })
463
+ }
464
+
465
+ const newAppStateChunkHandler = (isInitialSync: boolean) => {
466
+ return {
467
+ onMutation(mutation: ChatMutation) {
468
+ processSyncAction(
469
+ mutation,
470
+ ev,
471
+ authState.creds.me!,
472
+ isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined,
473
+ logger
474
+ )
475
+ }
476
+ }
477
+ }
478
+
479
+ const resyncAppState = ev.createBufferedFunction(
480
+ async (collections: readonly WAPatchName[], isInitialSync: boolean) => {
481
+ const appStateSyncKeyCache = new Map<string, proto.Message.IAppStateSyncKeyData | null>()
482
+
483
+ const getCachedAppStateSyncKey = async (
484
+ keyId: string
485
+ ): Promise<proto.Message.IAppStateSyncKeyData | null | undefined> => {
486
+ if (appStateSyncKeyCache.has(keyId)) {
487
+ return appStateSyncKeyCache.get(keyId) ?? undefined
488
+ }
489
+
490
+ const key = await getAppStateSyncKey(keyId)
491
+ appStateSyncKeyCache.set(keyId, key ?? null)
492
+ return key
493
+ }
494
+
495
+ // we use this to determine which events to fire
496
+ // otherwise when we resync from scratch -- all notifications will fire
497
+ const initialVersionMap: { [T in WAPatchName]?: number } = {}
498
+ const globalMutationMap: ChatMutationMap = {}
499
+
500
+ await authState.keys.transaction(async () => {
501
+ const collectionsToHandle = new Set<string>(collections)
502
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
503
+ const attemptsMap: { [T in WAPatchName]?: number } = {}
504
+ // keep executing till all collections are done
505
+ // sometimes a single patch request will not return all the patches (God knows why)
506
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
507
+ while (collectionsToHandle.size) {
508
+ const states = {} as { [T in WAPatchName]: LTHashState }
509
+ const nodes: BinaryNode[] = []
510
+
511
+ for (const name of collectionsToHandle as Set<WAPatchName>) {
512
+ const result = await authState.keys.get('app-state-sync-version', [name])
513
+ let state = result[name]
514
+
515
+ if (state) {
516
+ if (typeof initialVersionMap[name] === 'undefined') {
517
+ initialVersionMap[name] = state.version
518
+ }
519
+ } else {
520
+ state = newLTHashState()
521
+ }
522
+
523
+ states[name] = state
524
+
525
+ logger.info(`resyncing ${name} from v${state.version}`)
526
+
527
+ nodes.push({
528
+ tag: 'collection',
529
+ attrs: {
530
+ name,
531
+ version: state.version.toString(),
532
+ // return snapshot if being synced from scratch
533
+ return_snapshot: (!state.version).toString()
534
+ }
535
+ })
536
+ }
537
+
538
+ const result = await query({
539
+ tag: 'iq',
540
+ attrs: {
541
+ to: S_WHATSAPP_NET,
542
+ xmlns: 'w:sync:app:state',
543
+ type: 'set'
544
+ },
545
+ content: [
546
+ {
547
+ tag: 'sync',
548
+ attrs: {},
549
+ content: nodes
550
+ }
551
+ ]
552
+ })
553
+
554
+ // extract from binary node
555
+ const decoded = await extractSyncdPatches(result, config?.options)
556
+ for (const key in decoded) {
557
+ const name = key as WAPatchName
558
+ const { patches, hasMorePatches, snapshot } = decoded[name]
559
+ try {
560
+ if (snapshot) {
561
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(
562
+ name,
563
+ snapshot,
564
+ getCachedAppStateSyncKey,
565
+ initialVersionMap[name],
566
+ appStateMacVerification.snapshot
567
+ )
568
+ states[name] = newState
569
+ Object.assign(globalMutationMap, mutationMap)
570
+
571
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
572
+
573
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
574
+ }
575
+
576
+ // only process if there are syncd patches
577
+ if (patches.length) {
578
+ const { state: newState, mutationMap } = await decodePatches(
579
+ name,
580
+ patches,
581
+ states[name],
582
+ getCachedAppStateSyncKey,
583
+ config.options,
584
+ initialVersionMap[name],
585
+ logger,
586
+ appStateMacVerification.patch
587
+ )
588
+
589
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
590
+
591
+ logger.info(`synced ${name} to v${newState.version}`)
592
+ initialVersionMap[name] = newState.version
593
+
594
+ Object.assign(globalMutationMap, mutationMap)
595
+ }
596
+
597
+ if (hasMorePatches) {
598
+ logger.info(`${name} has more patches...`)
599
+ } else {
600
+ // collection is done with sync
601
+ collectionsToHandle.delete(name)
602
+ }
603
+ } catch (error: any) {
604
+ // if retry attempts overshoot
605
+ // or key not found
606
+ const isIrrecoverableError =
607
+ attemptsMap[name]! >= MAX_SYNC_ATTEMPTS ||
608
+ error.output?.statusCode === 404 ||
609
+ error.name === 'TypeError'
610
+ logger.info(
611
+ { name, error: error.stack },
612
+ `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`
613
+ )
614
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
615
+ // increment number of retries
616
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
617
+
618
+ if (isIrrecoverableError) {
619
+ // stop retrying
620
+ collectionsToHandle.delete(name)
621
+ }
622
+ }
623
+ }
624
+ }
625
+ }, authState?.creds?.me?.id || 'resync-app-state')
626
+
627
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
628
+ for (const key in globalMutationMap) {
629
+ onMutation(globalMutationMap[key]!)
630
+ }
631
+ }
632
+ )
633
+
634
+ /**
635
+ * fetch the profile picture of a user/group
636
+ * type = "preview" for a low res picture
637
+ * type = "image for the high res picture"
638
+ */
639
+ const profilePictureUrl = async (jid: string, type: 'preview' | 'image' = 'preview', timeoutMs?: number) => {
640
+ const baseContent: BinaryNode[] = [{ tag: 'picture', attrs: { type, query: 'url' } }]
641
+
642
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent })
643
+
644
+ jid = jidNormalizedUser(jid)
645
+ const result = await query(
646
+ {
647
+ tag: 'iq',
648
+ attrs: {
649
+ target: jid,
650
+ to: S_WHATSAPP_NET,
651
+ type: 'get',
652
+ xmlns: 'w:profile:picture'
653
+ },
654
+ content: tcTokenContent
655
+ },
656
+ timeoutMs
657
+ )
658
+ const child = getBinaryNodeChild(result, 'picture')
659
+ return child?.attrs?.url
660
+ }
661
+
662
+ const createCallLink = async (type: 'audio' | 'video', event?: { startTime: number }, timeoutMs?: number) => {
663
+ const result = await query(
664
+ {
665
+ tag: 'call',
666
+ attrs: {
667
+ id: generateMessageTag(),
668
+ to: '@call'
669
+ },
670
+ content: [
671
+ {
672
+ tag: 'link_create',
673
+ attrs: { media: type },
674
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
675
+ }
676
+ ]
677
+ },
678
+ timeoutMs
679
+ )
680
+ const child = getBinaryNodeChild(result, 'link_create')
681
+ return child?.attrs?.token
682
+ }
683
+
684
+ const sendPresenceUpdate = async (type: WAPresence, toJid?: string) => {
685
+ const me = authState.creds.me!
686
+ const isAvailableType = type === 'available'
687
+ if (isAvailableType || type === 'unavailable') {
688
+ if (!me.name) {
689
+ logger.warn('no name present, ignoring presence update request...')
690
+ return
691
+ }
692
+
693
+ ev.emit('connection.update', { isOnline: isAvailableType })
694
+
695
+ if (isAvailableType) {
696
+ void sendUnifiedSession()
697
+ }
698
+
699
+ await sendNode({
700
+ tag: 'presence',
701
+ attrs: {
702
+ name: me.name.replace(/@/g, ''),
703
+ type
704
+ }
705
+ })
706
+ } else {
707
+ const { server } = jidDecode(toJid)!
708
+ const isLid = server === 'lid'
709
+
710
+ await sendNode({
711
+ tag: 'chatstate',
712
+ attrs: {
713
+ from: isLid ? me.lid! : me.id,
714
+ to: toJid!
715
+ },
716
+ content: [
717
+ {
718
+ tag: type === 'recording' ? 'composing' : type,
719
+ attrs: type === 'recording' ? { media: 'audio' } : {}
720
+ }
721
+ ]
722
+ })
723
+ }
724
+ }
725
+
726
+ /**
727
+ * @param toJid the jid to subscribe to
728
+ * @param tcToken token for subscription, use if present
729
+ */
730
+ const presenceSubscribe = async (toJid: string) => {
731
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid })
732
+
733
+ return sendNode({
734
+ tag: 'presence',
735
+ attrs: {
736
+ to: toJid,
737
+ id: generateMessageTag(),
738
+ type: 'subscribe'
739
+ },
740
+ content: tcTokenContent
741
+ })
742
+ }
743
+
744
+ const handlePresenceUpdate = ({ tag, attrs, content }: BinaryNode) => {
745
+ let presence: PresenceData | undefined
746
+ const jid = attrs.from
747
+ const participant = attrs.participant || attrs.from
748
+
749
+ if (shouldIgnoreJid(jid!) && jid !== S_WHATSAPP_NET) {
750
+ return
751
+ }
752
+
753
+ if (tag === 'presence') {
754
+ presence = {
755
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
756
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
757
+ }
758
+ } else if (Array.isArray(content)) {
759
+ const [firstChild] = content
760
+ let type = firstChild!.tag as WAPresence
761
+ if (type === 'paused') {
762
+ type = 'available'
763
+ }
764
+
765
+ if (firstChild!.attrs?.media === 'audio') {
766
+ type = 'recording'
767
+ }
768
+
769
+ presence = { lastKnownPresence: type }
770
+ } else {
771
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
772
+ }
773
+
774
+ if (presence) {
775
+ ev.emit('presence.update', { id: jid!, presences: { [participant!]: presence } })
776
+ }
777
+ }
778
+
779
+ const appPatch = async (patchCreate: WAPatchCreate) => {
780
+ const name = patchCreate.type
781
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
782
+ if (!myAppStateKeyId) {
783
+ throw new Boom('App state key not present!', { statusCode: 400 })
784
+ }
785
+
786
+ let initial: LTHashState
787
+ let encodeResult: { patch: proto.ISyncdPatch; state: LTHashState }
788
+
789
+ await appStatePatchMutex.mutex(async () => {
790
+ await authState.keys.transaction(async () => {
791
+ logger.debug({ patch: patchCreate }, 'applying app patch')
792
+
793
+ await resyncAppState([name], false)
794
+
795
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
796
+ initial = currentSyncVersion || newLTHashState()
797
+
798
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
799
+ const { patch, state } = encodeResult
800
+
801
+ const node: BinaryNode = {
802
+ tag: 'iq',
803
+ attrs: {
804
+ to: S_WHATSAPP_NET,
805
+ type: 'set',
806
+ xmlns: 'w:sync:app:state'
807
+ },
808
+ content: [
809
+ {
810
+ tag: 'sync',
811
+ attrs: {},
812
+ content: [
813
+ {
814
+ tag: 'collection',
815
+ attrs: {
816
+ name,
817
+ version: (state.version - 1).toString(),
818
+ return_snapshot: 'false'
819
+ },
820
+ content: [
821
+ {
822
+ tag: 'patch',
823
+ attrs: {},
824
+ content: proto.SyncdPatch.encode(patch).finish()
825
+ }
826
+ ]
827
+ }
828
+ ]
829
+ }
830
+ ]
831
+ }
832
+ await query(node)
833
+
834
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
835
+ }, authState?.creds?.me?.id || 'app-patch')
836
+ })
837
+
838
+ if (config.emitOwnEvents) {
839
+ const { onMutation } = newAppStateChunkHandler(false)
840
+ const { mutationMap } = await decodePatches(
841
+ name,
842
+ [{ ...encodeResult!.patch, version: { version: encodeResult!.state.version } }],
843
+ initial!,
844
+ getAppStateSyncKey,
845
+ config.options,
846
+ undefined,
847
+ logger
848
+ )
849
+ for (const key in mutationMap) {
850
+ onMutation(mutationMap[key]!)
851
+ }
852
+ }
853
+ }
854
+
855
+ /** sending non-abt props may fix QR scan fail if server expects */
856
+ const fetchProps = async () => {
857
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
858
+ const resultNode = await query({
859
+ tag: 'iq',
860
+ attrs: {
861
+ to: S_WHATSAPP_NET,
862
+ xmlns: 'w',
863
+ type: 'get'
864
+ },
865
+ content: [
866
+ {
867
+ tag: 'props',
868
+ attrs: {
869
+ protocol: '2',
870
+ hash: authState?.creds?.lastPropHash || ''
871
+ }
872
+ }
873
+ ]
874
+ })
875
+
876
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
877
+
878
+ let props: { [_: string]: string } = {}
879
+ if (propsNode) {
880
+ if (propsNode.attrs?.hash) {
881
+ // on some clients, the hash is returning as undefined
882
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
883
+ ev.emit('creds.update', authState.creds)
884
+ }
885
+
886
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
887
+ }
888
+
889
+ logger.debug('fetched props')
890
+
891
+ return props
892
+ }
893
+
894
+ /**
895
+ * modify a chat -- mark unread, read etc.
896
+ * lastMessages must be sorted in reverse chronologically
897
+ * requires the last messages till the last message received; required for archive & unread
898
+ */
899
+ const chatModify = (mod: ChatModification, jid: string) => {
900
+ const patch = chatModificationToAppPatch(mod, jid)
901
+ return appPatch(patch)
902
+ }
903
+
904
+ /**
905
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
906
+ */
907
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled: boolean) => {
908
+ return chatModify(
909
+ {
910
+ disableLinkPreviews: { isPreviewsDisabled }
911
+ },
912
+ ''
913
+ )
914
+ }
915
+
916
+ /**
917
+ * Star or Unstar a message
918
+ */
919
+ const star = (jid: string, messages: { id: string; fromMe?: boolean }[], star: boolean) => {
920
+ return chatModify(
921
+ {
922
+ star: {
923
+ messages,
924
+ star
925
+ }
926
+ },
927
+ jid
928
+ )
929
+ }
930
+
931
+ /**
932
+ * Add or Edit Contact
933
+ */
934
+ const addOrEditContact = (jid: string, contact: proto.SyncActionValue.IContactAction) => {
935
+ return chatModify(
936
+ {
937
+ contact
938
+ },
939
+ jid
940
+ )
941
+ }
942
+
943
+ /**
944
+ * Remove Contact
945
+ */
946
+ const removeContact = (jid: string) => {
947
+ return chatModify(
948
+ {
949
+ contact: null
950
+ },
951
+ jid
952
+ )
953
+ }
954
+
955
+ /**
956
+ * Adds label
957
+ */
958
+ const addLabel = (jid: string, labels: LabelActionBody) => {
959
+ return chatModify(
960
+ {
961
+ addLabel: {
962
+ ...labels
963
+ }
964
+ },
965
+ jid
966
+ )
967
+ }
968
+
969
+ /**
970
+ * Adds label for the chats
971
+ */
972
+ const addChatLabel = (jid: string, labelId: string) => {
973
+ return chatModify(
974
+ {
975
+ addChatLabel: {
976
+ labelId
977
+ }
978
+ },
979
+ jid
980
+ )
981
+ }
982
+
983
+ /**
984
+ * Removes label for the chat
985
+ */
986
+ const removeChatLabel = (jid: string, labelId: string) => {
987
+ return chatModify(
988
+ {
989
+ removeChatLabel: {
990
+ labelId
991
+ }
992
+ },
993
+ jid
994
+ )
995
+ }
996
+
997
+ /**
998
+ * Adds label for the message
999
+ */
1000
+ const addMessageLabel = (jid: string, messageId: string, labelId: string) => {
1001
+ return chatModify(
1002
+ {
1003
+ addMessageLabel: {
1004
+ messageId,
1005
+ labelId
1006
+ }
1007
+ },
1008
+ jid
1009
+ )
1010
+ }
1011
+
1012
+ /**
1013
+ * Removes label for the message
1014
+ */
1015
+ const removeMessageLabel = (jid: string, messageId: string, labelId: string) => {
1016
+ return chatModify(
1017
+ {
1018
+ removeMessageLabel: {
1019
+ messageId,
1020
+ labelId
1021
+ }
1022
+ },
1023
+ jid
1024
+ )
1025
+ }
1026
+
1027
+ /**
1028
+ * Add or Edit Quick Reply
1029
+ */
1030
+ const addOrEditQuickReply = (quickReply: QuickReplyAction) => {
1031
+ return chatModify(
1032
+ {
1033
+ quickReply
1034
+ },
1035
+ ''
1036
+ )
1037
+ }
1038
+
1039
+ /**
1040
+ * Remove Quick Reply
1041
+ */
1042
+ const removeQuickReply = (timestamp: string) => {
1043
+ return chatModify(
1044
+ {
1045
+ quickReply: { timestamp, deleted: true }
1046
+ },
1047
+ ''
1048
+ )
1049
+ }
1050
+
1051
+ /**
1052
+ * queries need to be fired on connection open
1053
+ * help ensure parity with WA Web
1054
+ * */
1055
+ const executeInitQueries = async () => {
1056
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()])
1057
+ }
1058
+
1059
+ const upsertMessage = ev.createBufferedFunction(async (msg: WAMessage, type: MessageUpsertType) => {
1060
+ ev.emit('messages.upsert', { messages: [msg], type })
1061
+
1062
+ if (!!msg.pushName) {
1063
+ let jid = msg.key.fromMe ? authState.creds.me!.id : msg.key.participant || msg.key.remoteJid
1064
+ jid = jidNormalizedUser(jid!)
1065
+
1066
+ if (!msg.key.fromMe) {
1067
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName! }])
1068
+ }
1069
+
1070
+ // update our pushname too
1071
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
1072
+ ev.emit('creds.update', { me: { ...authState.creds.me!, name: msg.pushName } })
1073
+ }
1074
+ }
1075
+
1076
+ const historyMsg = getHistoryMsg(msg.message!)
1077
+ const shouldProcessHistoryMsg = historyMsg
1078
+ ? shouldSyncHistoryMessage(historyMsg) &&
1079
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType! as proto.HistorySync.HistorySyncType)
1080
+ : false
1081
+
1082
+ // State machine: decide on sync and flush
1083
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
1084
+ if (awaitingSyncTimeout) {
1085
+ clearTimeout(awaitingSyncTimeout)
1086
+ awaitingSyncTimeout = undefined
1087
+ }
1088
+
1089
+ if (shouldProcessHistoryMsg) {
1090
+ syncState = SyncState.Syncing
1091
+ logger.info('Transitioned to Syncing state')
1092
+ // Let doAppStateSync handle the final flush after it's done
1093
+ } else {
1094
+ syncState = SyncState.Online
1095
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
1096
+ ev.flush()
1097
+ }
1098
+ }
1099
+
1100
+ const doAppStateSync = async () => {
1101
+ if (syncState === SyncState.Syncing) {
1102
+ logger.info('Doing app state sync')
1103
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
1104
+
1105
+ // Sync is complete, go online and flush everything
1106
+ syncState = SyncState.Online
1107
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
1108
+ ev.flush()
1109
+
1110
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
1111
+ ev.emit('creds.update', { accountSyncCounter })
1112
+ }
1113
+ }
1114
+
1115
+ await Promise.all([
1116
+ (async () => {
1117
+ if (shouldProcessHistoryMsg) {
1118
+ await doAppStateSync()
1119
+ }
1120
+ })(),
1121
+ processMessage(msg, {
1122
+ signalRepository,
1123
+ shouldProcessHistoryMsg,
1124
+ placeholderResendCache,
1125
+ ev,
1126
+ creds: authState.creds,
1127
+ keyStore: authState.keys,
1128
+ logger,
1129
+ options: config.options,
1130
+ getMessage
1131
+ })
1132
+ ])
1133
+
1134
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1135
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1136
+ logger.info('App state sync key arrived, triggering app state sync')
1137
+ await doAppStateSync()
1138
+ }
1139
+ })
1140
+
1141
+ ws.on('CB:presence', handlePresenceUpdate)
1142
+ ws.on('CB:chatstate', handlePresenceUpdate)
1143
+
1144
+ ws.on('CB:ib,,dirty', async (node: BinaryNode) => {
1145
+ const { attrs } = getBinaryNodeChild(node, 'dirty')!
1146
+ const type = attrs.type
1147
+ switch (type) {
1148
+ case 'account_sync':
1149
+ if (attrs.timestamp) {
1150
+ let { lastAccountSyncTimestamp } = authState.creds
1151
+ if (lastAccountSyncTimestamp) {
1152
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
1153
+ }
1154
+
1155
+ lastAccountSyncTimestamp = +attrs.timestamp
1156
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
1157
+ }
1158
+
1159
+ break
1160
+ case 'groups':
1161
+ // handled in groups.ts
1162
+ break
1163
+ default:
1164
+ logger.info({ node }, 'received unknown sync')
1165
+ break
1166
+ }
1167
+ })
1168
+
1169
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1170
+ if (connection === 'open') {
1171
+ if (fireInitQueries) {
1172
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
1173
+ }
1174
+
1175
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error =>
1176
+ onUnexpectedError(error, 'presence update requests')
1177
+ )
1178
+ }
1179
+
1180
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1181
+ return
1182
+ }
1183
+
1184
+ syncState = SyncState.AwaitingInitialSync
1185
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
1186
+ ev.buffer()
1187
+
1188
+ const willSyncHistory = shouldSyncHistoryMessage(
1189
+ proto.Message.HistorySyncNotification.create({
1190
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1191
+ })
1192
+ )
1193
+
1194
+ if (!willSyncHistory) {
1195
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
1196
+ syncState = SyncState.Online
1197
+ setTimeout(() => ev.flush(), 0)
1198
+ return
1199
+ }
1200
+
1201
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.')
1202
+
1203
+ if (awaitingSyncTimeout) {
1204
+ clearTimeout(awaitingSyncTimeout)
1205
+ }
1206
+
1207
+ awaitingSyncTimeout = setTimeout(() => {
1208
+ if (syncState === SyncState.AwaitingInitialSync) {
1209
+ // TODO: investigate
1210
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
1211
+ syncState = SyncState.Online
1212
+ ev.flush()
1213
+ }
1214
+ }, 20_000)
1215
+ })
1216
+
1217
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1218
+ try {
1219
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }])
1220
+ } catch (error) {
1221
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping')
1222
+ }
1223
+ })
1224
+
1225
+ return {
1226
+ ...sock,
1227
+ createCallLink,
1228
+ getBotListV2,
1229
+ messageMutex,
1230
+ receiptMutex,
1231
+ appStatePatchMutex,
1232
+ notificationMutex,
1233
+ fetchPrivacySettings,
1234
+ upsertMessage,
1235
+ appPatch,
1236
+ sendPresenceUpdate,
1237
+ presenceSubscribe,
1238
+ profilePictureUrl,
1239
+ fetchBlocklist,
1240
+ fetchStatus,
1241
+ fetchDisappearingDuration,
1242
+ updateProfilePicture,
1243
+ removeProfilePicture,
1244
+ updateProfileStatus,
1245
+ updateProfileName,
1246
+ updateBlockStatus,
1247
+ updateDisableLinkPreviewsPrivacy,
1248
+ updateCallPrivacy,
1249
+ updateMessagesPrivacy,
1250
+ updateLastSeenPrivacy,
1251
+ updateOnlinePrivacy,
1252
+ updateProfilePicturePrivacy,
1253
+ updateStatusPrivacy,
1254
+ updateReadReceiptsPrivacy,
1255
+ updateGroupsAddPrivacy,
1256
+ updateDefaultDisappearingMode,
1257
+ getBusinessProfile,
1258
+ resyncAppState,
1259
+ chatModify,
1260
+ cleanDirtyBits,
1261
+ addOrEditContact,
1262
+ removeContact,
1263
+ addLabel,
1264
+ addChatLabel,
1265
+ removeChatLabel,
1266
+ addMessageLabel,
1267
+ removeMessageLabel,
1268
+ star,
1269
+ addOrEditQuickReply,
1270
+ removeQuickReply
1271
+ }
1272
+ }