@periskope/baileys 6.7.10-alpha.0

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