@prototypevip/baileys 0.0.1

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