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