ndikzv1 26.0.12

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