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