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