naya-flore 4.7.1

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