@d0v3riz/baileys 6.3.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 (147) hide show
  1. package/README.md +956 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +2845 -0
  4. package/WAProto/index.d.ts +32006 -0
  5. package/WAProto/index.js +87184 -0
  6. package/WASignalGroup/GroupProtocol.js +1697 -0
  7. package/WASignalGroup/ciphertext_message.js +16 -0
  8. package/WASignalGroup/group_cipher.js +106 -0
  9. package/WASignalGroup/group_session_builder.js +46 -0
  10. package/WASignalGroup/index.js +5 -0
  11. package/WASignalGroup/keyhelper.js +21 -0
  12. package/WASignalGroup/protobufs.js +3 -0
  13. package/WASignalGroup/readme.md +6 -0
  14. package/WASignalGroup/sender_chain_key.js +50 -0
  15. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  16. package/WASignalGroup/sender_key_message.js +92 -0
  17. package/WASignalGroup/sender_key_name.js +70 -0
  18. package/WASignalGroup/sender_key_record.js +54 -0
  19. package/WASignalGroup/sender_key_state.js +129 -0
  20. package/WASignalGroup/sender_message_key.js +39 -0
  21. package/lib/Defaults/baileys-version.json +3 -0
  22. package/lib/Defaults/index.d.ts +284 -0
  23. package/lib/Defaults/index.js +115 -0
  24. package/lib/Defaults/phonenumber-mcc.json +223 -0
  25. package/lib/Signal/libsignal.d.ts +3 -0
  26. package/lib/Signal/libsignal.js +151 -0
  27. package/lib/Socket/Client/abstract-socket-client.d.ts +16 -0
  28. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  29. package/lib/Socket/Client/index.d.ts +3 -0
  30. package/lib/Socket/Client/index.js +19 -0
  31. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  32. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  33. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  34. package/lib/Socket/Client/web-socket-client.js +62 -0
  35. package/lib/Socket/business.d.ts +124 -0
  36. package/lib/Socket/business.js +259 -0
  37. package/lib/Socket/chats.d.ts +74 -0
  38. package/lib/Socket/chats.js +838 -0
  39. package/lib/Socket/groups.d.ts +105 -0
  40. package/lib/Socket/groups.js +291 -0
  41. package/lib/Socket/index.d.ts +126 -0
  42. package/lib/Socket/index.js +10 -0
  43. package/lib/Socket/messages-recv.d.ts +112 -0
  44. package/lib/Socket/messages-recv.js +641 -0
  45. package/lib/Socket/messages-send.d.ts +110 -0
  46. package/lib/Socket/messages-send.js +648 -0
  47. package/lib/Socket/registration.d.ts +211 -0
  48. package/lib/Socket/registration.js +166 -0
  49. package/lib/Socket/socket.d.ts +42 -0
  50. package/lib/Socket/socket.js +527 -0
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/index.js +10 -0
  53. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  54. package/lib/Store/make-cache-manager-store.js +83 -0
  55. package/lib/Store/make-in-memory-store.d.ts +117 -0
  56. package/lib/Store/make-in-memory-store.js +435 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +106 -0
  62. package/lib/Types/Auth.js +2 -0
  63. package/lib/Types/Call.d.ts +12 -0
  64. package/lib/Types/Call.js +2 -0
  65. package/lib/Types/Chat.d.ts +102 -0
  66. package/lib/Types/Chat.js +4 -0
  67. package/lib/Types/Contact.d.ts +18 -0
  68. package/lib/Types/Contact.js +2 -0
  69. package/lib/Types/Events.d.ts +152 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.d.ts +42 -0
  72. package/lib/Types/GroupMetadata.js +2 -0
  73. package/lib/Types/Label.d.ts +35 -0
  74. package/lib/Types/Label.js +27 -0
  75. package/lib/Types/LabelAssociation.d.ts +29 -0
  76. package/lib/Types/LabelAssociation.js +9 -0
  77. package/lib/Types/Message.d.ts +245 -0
  78. package/lib/Types/Message.js +9 -0
  79. package/lib/Types/Product.d.ts +78 -0
  80. package/lib/Types/Product.js +2 -0
  81. package/lib/Types/Signal.d.ts +57 -0
  82. package/lib/Types/Signal.js +2 -0
  83. package/lib/Types/Socket.d.ts +106 -0
  84. package/lib/Types/Socket.js +2 -0
  85. package/lib/Types/State.d.ts +27 -0
  86. package/lib/Types/State.js +2 -0
  87. package/lib/Types/index.d.ts +54 -0
  88. package/lib/Types/index.js +39 -0
  89. package/lib/Utils/auth-utils.d.ts +18 -0
  90. package/lib/Utils/auth-utils.js +202 -0
  91. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  92. package/lib/Utils/baileys-event-stream.js +63 -0
  93. package/lib/Utils/business.d.ts +22 -0
  94. package/lib/Utils/business.js +234 -0
  95. package/lib/Utils/chat-utils.d.ts +71 -0
  96. package/lib/Utils/chat-utils.js +710 -0
  97. package/lib/Utils/crypto.d.ts +38 -0
  98. package/lib/Utils/crypto.js +137 -0
  99. package/lib/Utils/decode-wa-message.d.ts +19 -0
  100. package/lib/Utils/decode-wa-message.js +160 -0
  101. package/lib/Utils/event-buffer.d.ts +35 -0
  102. package/lib/Utils/event-buffer.js +514 -0
  103. package/lib/Utils/generics.d.ts +92 -0
  104. package/lib/Utils/generics.js +368 -0
  105. package/lib/Utils/history.d.ts +15 -0
  106. package/lib/Utils/history.js +91 -0
  107. package/lib/Utils/index.d.ts +17 -0
  108. package/lib/Utils/index.js +33 -0
  109. package/lib/Utils/link-preview.d.ts +21 -0
  110. package/lib/Utils/link-preview.js +116 -0
  111. package/lib/Utils/logger.d.ts +4 -0
  112. package/lib/Utils/logger.js +7 -0
  113. package/lib/Utils/lt-hash.d.ts +12 -0
  114. package/lib/Utils/lt-hash.js +51 -0
  115. package/lib/Utils/make-mutex.d.ts +7 -0
  116. package/lib/Utils/make-mutex.js +43 -0
  117. package/lib/Utils/messages-media.d.ts +101 -0
  118. package/lib/Utils/messages-media.js +632 -0
  119. package/lib/Utils/messages.d.ts +75 -0
  120. package/lib/Utils/messages.js +738 -0
  121. package/lib/Utils/noise-handler.d.ts +20 -0
  122. package/lib/Utils/noise-handler.js +142 -0
  123. package/lib/Utils/process-message.d.ts +41 -0
  124. package/lib/Utils/process-message.js +297 -0
  125. package/lib/Utils/signal.d.ts +32 -0
  126. package/lib/Utils/signal.js +151 -0
  127. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  128. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  129. package/lib/Utils/validate-connection.d.ts +11 -0
  130. package/lib/Utils/validate-connection.js +188 -0
  131. package/lib/WABinary/constants.d.ts +27 -0
  132. package/lib/WABinary/constants.js +40 -0
  133. package/lib/WABinary/decode.d.ts +7 -0
  134. package/lib/WABinary/decode.js +252 -0
  135. package/lib/WABinary/encode.d.ts +3 -0
  136. package/lib/WABinary/encode.js +228 -0
  137. package/lib/WABinary/generic-utils.d.ts +15 -0
  138. package/lib/WABinary/generic-utils.js +110 -0
  139. package/lib/WABinary/index.d.ts +5 -0
  140. package/lib/WABinary/index.js +21 -0
  141. package/lib/WABinary/jid-utils.d.ts +27 -0
  142. package/lib/WABinary/jid-utils.js +56 -0
  143. package/lib/WABinary/types.d.ts +18 -0
  144. package/lib/WABinary/types.js +2 -0
  145. package/lib/index.d.ts +9 -0
  146. package/lib/index.js +27 -0
  147. package/package.json +100 -0
@@ -0,0 +1,368 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.trimUndefineds = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
30
+ const boom_1 = require("@hapi/boom");
31
+ const axios_1 = __importDefault(require("axios"));
32
+ const crypto_1 = require("crypto");
33
+ const os_1 = require("os");
34
+ const WAProto_1 = require("../../WAProto");
35
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
36
+ const Types_1 = require("../Types");
37
+ const WABinary_1 = require("../WABinary");
38
+ const PLATFORM_MAP = {
39
+ 'aix': 'AIX',
40
+ 'darwin': 'Mac OS',
41
+ 'win32': 'Windows',
42
+ 'android': 'Android'
43
+ };
44
+ exports.Browsers = {
45
+ ubuntu: browser => ['Ubuntu', browser, '20.0.04'],
46
+ macOS: browser => ['Mac OS', browser, '10.15.7'],
47
+ baileys: browser => ['Baileys', browser, '4.0.0'],
48
+ /** The appropriate browser based on your OS & release */
49
+ appropriate: browser => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
50
+ };
51
+ exports.BufferJSON = {
52
+ replacer: (k, value) => {
53
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
54
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
55
+ }
56
+ return value;
57
+ },
58
+ reviver: (_, value) => {
59
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
60
+ const val = value.data || value.value;
61
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
62
+ }
63
+ return value;
64
+ }
65
+ };
66
+ const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
67
+ exports.getKeyAuthor = getKeyAuthor;
68
+ const writeRandomPadMax16 = (msg) => {
69
+ const pad = (0, crypto_1.randomBytes)(1);
70
+ pad[0] &= 0xf;
71
+ if (!pad[0]) {
72
+ pad[0] = 0xf;
73
+ }
74
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
75
+ };
76
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
77
+ const unpadRandomMax16 = (e) => {
78
+ const t = new Uint8Array(e);
79
+ if (0 === t.length) {
80
+ throw new Error('unpadPkcs7 given empty bytes');
81
+ }
82
+ var r = t[t.length - 1];
83
+ if (r > t.length) {
84
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
85
+ }
86
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
87
+ };
88
+ exports.unpadRandomMax16 = unpadRandomMax16;
89
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
90
+ exports.encodeWAMessage = encodeWAMessage;
91
+ const generateRegistrationId = () => {
92
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
93
+ };
94
+ exports.generateRegistrationId = generateRegistrationId;
95
+ const encodeBigEndian = (e, t = 4) => {
96
+ let r = e;
97
+ const a = new Uint8Array(t);
98
+ for (let i = t - 1; i >= 0; i--) {
99
+ a[i] = 255 & r;
100
+ r >>>= 8;
101
+ }
102
+ return a;
103
+ };
104
+ exports.encodeBigEndian = encodeBigEndian;
105
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
106
+ exports.toNumber = toNumber;
107
+ /** unix timestamp of a date in seconds */
108
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
109
+ exports.unixTimestampSeconds = unixTimestampSeconds;
110
+ const debouncedTimeout = (intervalMs = 1000, task) => {
111
+ let timeout;
112
+ return {
113
+ start: (newIntervalMs, newTask) => {
114
+ task = newTask || task;
115
+ intervalMs = newIntervalMs || intervalMs;
116
+ timeout && clearTimeout(timeout);
117
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
118
+ },
119
+ cancel: () => {
120
+ timeout && clearTimeout(timeout);
121
+ timeout = undefined;
122
+ },
123
+ setTask: (newTask) => task = newTask,
124
+ setInterval: (newInterval) => intervalMs = newInterval
125
+ };
126
+ };
127
+ exports.debouncedTimeout = debouncedTimeout;
128
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
129
+ exports.delay = delay;
130
+ const delayCancellable = (ms) => {
131
+ const stack = new Error().stack;
132
+ let timeout;
133
+ let reject;
134
+ const delay = new Promise((resolve, _reject) => {
135
+ timeout = setTimeout(resolve, ms);
136
+ reject = _reject;
137
+ });
138
+ const cancel = () => {
139
+ clearTimeout(timeout);
140
+ reject(new boom_1.Boom('Cancelled', {
141
+ statusCode: 500,
142
+ data: {
143
+ stack
144
+ }
145
+ }));
146
+ };
147
+ return { delay, cancel };
148
+ };
149
+ exports.delayCancellable = delayCancellable;
150
+ async function promiseTimeout(ms, promise) {
151
+ if (!ms) {
152
+ return new Promise(promise);
153
+ }
154
+ const stack = new Error().stack;
155
+ // Create a promise that rejects in <ms> milliseconds
156
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
157
+ const p = new Promise((resolve, reject) => {
158
+ delay
159
+ .then(() => reject(new boom_1.Boom('Timed Out', {
160
+ statusCode: Types_1.DisconnectReason.timedOut,
161
+ data: {
162
+ stack
163
+ }
164
+ })))
165
+ .catch(err => reject(err));
166
+ promise(resolve, reject);
167
+ })
168
+ .finally(cancel);
169
+ return p;
170
+ }
171
+ exports.promiseTimeout = promiseTimeout;
172
+ // generate a random ID to attach to a message
173
+ const generateMessageID = () => 'WHPI' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
174
+ exports.generateMessageID = generateMessageID;
175
+ function bindWaitForEvent(ev, event) {
176
+ return async (check, timeoutMs) => {
177
+ let listener;
178
+ let closeListener;
179
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
180
+ closeListener = ({ connection, lastDisconnect }) => {
181
+ if (connection === 'close') {
182
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
183
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
184
+ }
185
+ };
186
+ ev.on('connection.update', closeListener);
187
+ listener = (update) => {
188
+ if (check(update)) {
189
+ resolve();
190
+ }
191
+ };
192
+ ev.on(event, listener);
193
+ })
194
+ .finally(() => {
195
+ ev.off(event, listener);
196
+ ev.off('connection.update', closeListener);
197
+ }));
198
+ };
199
+ }
200
+ exports.bindWaitForEvent = bindWaitForEvent;
201
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
202
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
203
+ const printQRIfNecessaryListener = (ev, logger) => {
204
+ ev.on('connection.update', async ({ qr }) => {
205
+ if (qr) {
206
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).catch(() => {
207
+ logger.error('QR code terminal not added as dependency');
208
+ });
209
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
210
+ }
211
+ });
212
+ };
213
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
214
+ /**
215
+ * utility that fetches latest baileys version from the master branch.
216
+ * Use to ensure your WA connection is always on the latest version
217
+ */
218
+ const fetchLatestBaileysVersion = async (options = {}) => {
219
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
220
+ try {
221
+ const result = await axios_1.default.get(URL, {
222
+ ...options,
223
+ responseType: 'json'
224
+ });
225
+ return {
226
+ version: result.data.version,
227
+ isLatest: true
228
+ };
229
+ }
230
+ catch (error) {
231
+ return {
232
+ version: baileys_version_json_1.version,
233
+ isLatest: false,
234
+ error
235
+ };
236
+ }
237
+ };
238
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
239
+ /**
240
+ * A utility that fetches the latest web version of whatsapp.
241
+ * Use to ensure your WA connection is always on the latest version
242
+ */
243
+ const fetchLatestWaWebVersion = async (options) => {
244
+ try {
245
+ const result = await axios_1.default.get('https://web.whatsapp.com/check-update?version=1&platform=web', {
246
+ ...options,
247
+ responseType: 'json'
248
+ });
249
+ const version = result.data.currentVersion.split('.');
250
+ return {
251
+ version: [+version[0], +version[1], +version[2]],
252
+ isLatest: true
253
+ };
254
+ }
255
+ catch (error) {
256
+ return {
257
+ version: baileys_version_json_1.version,
258
+ isLatest: false,
259
+ error
260
+ };
261
+ }
262
+ };
263
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
264
+ /** unique message tag prefix for MD clients */
265
+ const generateMdTagPrefix = () => {
266
+ const bytes = (0, crypto_1.randomBytes)(4);
267
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
268
+ };
269
+ exports.generateMdTagPrefix = generateMdTagPrefix;
270
+ const STATUS_MAP = {
271
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
272
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
273
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
274
+ };
275
+ /**
276
+ * Given a type of receipt, returns what the new status of the message should be
277
+ * @param type type from receipt
278
+ */
279
+ const getStatusFromReceiptType = (type) => {
280
+ const status = STATUS_MAP[type];
281
+ if (typeof type === 'undefined') {
282
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
283
+ }
284
+ return status;
285
+ };
286
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
287
+ const CODE_MAP = {
288
+ conflict: Types_1.DisconnectReason.connectionReplaced
289
+ };
290
+ /**
291
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
292
+ * @param reason the string reason given, eg. "conflict"
293
+ */
294
+ const getErrorCodeFromStreamError = (node) => {
295
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
296
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
297
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
298
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
299
+ reason = 'restart required';
300
+ }
301
+ return {
302
+ reason,
303
+ statusCode
304
+ };
305
+ };
306
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
307
+ const getCallStatusFromNode = ({ tag, attrs }) => {
308
+ let status;
309
+ switch (tag) {
310
+ case 'offer':
311
+ case 'offer_notice':
312
+ status = 'offer';
313
+ break;
314
+ case 'terminate':
315
+ if (attrs.reason === 'timeout') {
316
+ status = 'timeout';
317
+ }
318
+ else {
319
+ status = 'reject';
320
+ }
321
+ break;
322
+ case 'reject':
323
+ status = 'reject';
324
+ break;
325
+ case 'accept':
326
+ status = 'accept';
327
+ break;
328
+ default:
329
+ status = 'ringing';
330
+ break;
331
+ }
332
+ return status;
333
+ };
334
+ exports.getCallStatusFromNode = getCallStatusFromNode;
335
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
336
+ const getCodeFromWSError = (error) => {
337
+ var _a, _b, _c;
338
+ let statusCode = 500;
339
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
340
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
341
+ if (!Number.isNaN(code) && code >= 400) {
342
+ statusCode = code;
343
+ }
344
+ }
345
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
346
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
347
+ statusCode = 408;
348
+ }
349
+ return statusCode;
350
+ };
351
+ exports.getCodeFromWSError = getCodeFromWSError;
352
+ /**
353
+ * Is the given platform WA business
354
+ * @param platform AuthenticationCreds.platform
355
+ */
356
+ const isWABusinessPlatform = (platform) => {
357
+ return platform === 'smbi' || platform === 'smba';
358
+ };
359
+ exports.isWABusinessPlatform = isWABusinessPlatform;
360
+ function trimUndefineds(obj) {
361
+ for (const key in obj) {
362
+ if (typeof obj[key] === 'undefined') {
363
+ delete obj[key];
364
+ }
365
+ }
366
+ return obj;
367
+ }
368
+ exports.trimUndefineds = trimUndefineds;
@@ -0,0 +1,15 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { proto } from '../../WAProto';
3
+ import { Chat, Contact } from '../Types';
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<proto.HistorySync>;
5
+ export declare const processHistoryMessage: (item: proto.IHistorySync) => {
6
+ chats: Chat[];
7
+ contacts: Contact[];
8
+ messages: proto.IWebMessageInfo[];
9
+ };
10
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
11
+ chats: Chat[];
12
+ contacts: Contact[];
13
+ messages: proto.IWebMessageInfo[];
14
+ }>;
15
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
+ const util_1 = require("util");
5
+ const zlib_1 = require("zlib");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const Types_1 = require("../Types");
8
+ const WABinary_1 = require("../WABinary");
9
+ const generics_1 = require("./generics");
10
+ const messages_1 = require("./messages");
11
+ const messages_media_1 = require("./messages-media");
12
+ const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
+ const downloadHistory = async (msg, options) => {
14
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
15
+ const bufferArray = [];
16
+ for await (const chunk of stream) {
17
+ bufferArray.push(chunk);
18
+ }
19
+ let buffer = Buffer.concat(bufferArray);
20
+ // decompress buffer
21
+ buffer = await inflatePromise(buffer);
22
+ const syncData = WAProto_1.proto.HistorySync.decode(buffer);
23
+ return syncData;
24
+ };
25
+ exports.downloadHistory = downloadHistory;
26
+ const processHistoryMessage = (item) => {
27
+ var _a, _b, _c;
28
+ const messages = [];
29
+ const contacts = [];
30
+ const chats = [];
31
+ switch (item.syncType) {
32
+ case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
+ case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
+ case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
35
+ for (const chat of item.conversations) {
36
+ contacts.push({ id: chat.id, name: chat.name || undefined });
37
+ const msgs = chat.messages || [];
38
+ delete chat.messages;
39
+ delete chat.archived;
40
+ delete chat.muteEndTime;
41
+ delete chat.pinned;
42
+ for (const item of msgs) {
43
+ const message = item.message;
44
+ messages.push(message);
45
+ if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
46
+ // keep only the most recent message in the chat array
47
+ chat.messages = [{ message }];
48
+ }
49
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
50
+ chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
51
+ }
52
+ if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
53
+ || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
54
+ && ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
55
+ contacts.push({
56
+ id: message.key.participant || message.key.remoteJid,
57
+ verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
58
+ });
59
+ }
60
+ }
61
+ if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
62
+ delete chat.readOnly;
63
+ }
64
+ chats.push({ ...chat });
65
+ }
66
+ break;
67
+ case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
68
+ for (const c of item.pushnames) {
69
+ contacts.push({ id: c.id, notify: c.pushname });
70
+ }
71
+ break;
72
+ }
73
+ return {
74
+ chats,
75
+ contacts,
76
+ messages,
77
+ };
78
+ };
79
+ exports.processHistoryMessage = processHistoryMessage;
80
+ const downloadAndProcessHistorySyncNotification = async (msg, options) => {
81
+ const historyMsg = await (0, exports.downloadHistory)(msg, options);
82
+ return (0, exports.processHistoryMessage)(historyMsg);
83
+ };
84
+ exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
85
+ const getHistoryMsg = (message) => {
86
+ var _a;
87
+ const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
88
+ const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
89
+ return anyHistoryMsg;
90
+ };
91
+ exports.getHistoryMsg = getHistoryMsg;
@@ -0,0 +1,17 @@
1
+ export * from './generics';
2
+ export * from './decode-wa-message';
3
+ export * from './messages';
4
+ export * from './messages-media';
5
+ export * from './validate-connection';
6
+ export * from './crypto';
7
+ export * from './signal';
8
+ export * from './noise-handler';
9
+ export * from './history';
10
+ export * from './chat-utils';
11
+ export * from './lt-hash';
12
+ export * from './auth-utils';
13
+ export * from './baileys-event-stream';
14
+ export * from './use-multi-file-auth-state';
15
+ export * from './link-preview';
16
+ export * from './event-buffer';
17
+ export * from './process-message';
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./generics"), exports);
18
+ __exportStar(require("./decode-wa-message"), exports);
19
+ __exportStar(require("./messages"), exports);
20
+ __exportStar(require("./messages-media"), exports);
21
+ __exportStar(require("./validate-connection"), exports);
22
+ __exportStar(require("./crypto"), exports);
23
+ __exportStar(require("./signal"), exports);
24
+ __exportStar(require("./noise-handler"), exports);
25
+ __exportStar(require("./history"), exports);
26
+ __exportStar(require("./chat-utils"), exports);
27
+ __exportStar(require("./lt-hash"), exports);
28
+ __exportStar(require("./auth-utils"), exports);
29
+ __exportStar(require("./baileys-event-stream"), exports);
30
+ __exportStar(require("./use-multi-file-auth-state"), exports);
31
+ __exportStar(require("./link-preview"), exports);
32
+ __exportStar(require("./event-buffer"), exports);
33
+ __exportStar(require("./process-message"), exports);
@@ -0,0 +1,21 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { Logger } from 'pino';
3
+ import { WAMediaUploadFunction, WAUrlInfo } from '../Types';
4
+ export declare type URLGenerationOptions = {
5
+ thumbnailWidth: number;
6
+ fetchOpts: {
7
+ /** Timeout in ms */
8
+ timeout: number;
9
+ proxyUrl?: string;
10
+ headers?: AxiosRequestConfig<{}>['headers'];
11
+ };
12
+ uploadImage?: WAMediaUploadFunction;
13
+ logger?: Logger;
14
+ };
15
+ /**
16
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
17
+ * Return undefined if the fetch failed or no URL was found
18
+ * @param text first matched URL in text
19
+ * @returns the URL info required to generate link preview
20
+ */
21
+ export declare const getUrlInfo: (text: string, opts?: URLGenerationOptions) => Promise<WAUrlInfo | undefined>;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getUrlInfo = void 0;
27
+ const messages_1 = require("./messages");
28
+ const messages_media_1 = require("./messages-media");
29
+ const THUMBNAIL_WIDTH_PX = 192;
30
+ /** Fetches an image and generates a thumbnail for it */
31
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
32
+ const stream = await (0, messages_media_1.getHttpStream)(url, fetchOpts);
33
+ const result = await (0, messages_media_1.extractImageThumb)(stream, thumbnailWidth);
34
+ return result;
35
+ };
36
+ /**
37
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
38
+ * Return undefined if the fetch failed or no URL was found
39
+ * @param text first matched URL in text
40
+ * @returns the URL info required to generate link preview
41
+ */
42
+ const getUrlInfo = async (text, opts = {
43
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
44
+ fetchOpts: { timeout: 3000 }
45
+ }) => {
46
+ var _a;
47
+ try {
48
+ // retries
49
+ const retries = 0;
50
+ const maxRetry = 5;
51
+ const { getLinkPreview } = await Promise.resolve().then(() => __importStar(require('link-preview-js')));
52
+ let previewLink = text;
53
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
54
+ previewLink = 'https://' + previewLink;
55
+ }
56
+ const info = await getLinkPreview(previewLink, {
57
+ ...opts.fetchOpts,
58
+ followRedirects: 'manual',
59
+ handleRedirects: (baseURL, forwardedURL) => {
60
+ const urlObj = new URL(baseURL);
61
+ const forwardedURLObj = new URL(forwardedURL);
62
+ if (retries >= maxRetry) {
63
+ return false;
64
+ }
65
+ if (forwardedURLObj.hostname === urlObj.hostname
66
+ || forwardedURLObj.hostname === 'www.' + urlObj.hostname
67
+ || 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
68
+ retries + 1;
69
+ return true;
70
+ }
71
+ else {
72
+ return false;
73
+ }
74
+ },
75
+ headers: opts.fetchOpts
76
+ });
77
+ if (info && 'title' in info && info.title) {
78
+ const [image] = info.images;
79
+ const urlInfo = {
80
+ 'canonical-url': info.url,
81
+ 'matched-text': text,
82
+ title: info.title,
83
+ description: info.description,
84
+ originalThumbnailUrl: image
85
+ };
86
+ if (opts.uploadImage) {
87
+ const { imageMessage } = await (0, messages_1.prepareWAMessageMedia)({ image: { url: image } }, {
88
+ upload: opts.uploadImage,
89
+ mediaTypeOverride: 'thumbnail-link',
90
+ options: opts.fetchOpts
91
+ });
92
+ urlInfo.jpegThumbnail = (imageMessage === null || imageMessage === void 0 ? void 0 : imageMessage.jpegThumbnail)
93
+ ? Buffer.from(imageMessage.jpegThumbnail)
94
+ : undefined;
95
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
96
+ }
97
+ else {
98
+ try {
99
+ urlInfo.jpegThumbnail = image
100
+ ? (await getCompressedJpegThumbnail(image, opts)).buffer
101
+ : undefined;
102
+ }
103
+ catch (error) {
104
+ (_a = opts.logger) === null || _a === void 0 ? void 0 : _a.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
105
+ }
106
+ }
107
+ return urlInfo;
108
+ }
109
+ }
110
+ catch (error) {
111
+ if (!error.message.includes('receive a valid')) {
112
+ throw error;
113
+ }
114
+ }
115
+ };
116
+ exports.getUrlInfo = getUrlInfo;
@@ -0,0 +1,4 @@
1
+ declare const _default: import("pino").Logger<{
2
+ timestamp: () => string;
3
+ }>;
4
+ export default _default;
@@ -0,0 +1,7 @@
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
+ const pino_1 = __importDefault(require("pino"));
7
+ exports.default = (0, pino_1.default)({ timestamp: () => `,"time":"${new Date().toJSON()}"` });