@gara31/void-baileys 7.0.0-rc.10

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/index.js +117292 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.js +116 -0
  5. package/lib/Signal/Group/ciphertext-message.js +12 -0
  6. package/lib/Signal/Group/group-session-builder.js +42 -0
  7. package/lib/Signal/Group/group_cipher.js +109 -0
  8. package/lib/Signal/Group/index.js +12 -0
  9. package/lib/Signal/Group/keyhelper.js +18 -0
  10. package/lib/Signal/Group/sender-chain-key.js +32 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  12. package/lib/Signal/Group/sender-key-message.js +80 -0
  13. package/lib/Signal/Group/sender-key-name.js +50 -0
  14. package/lib/Signal/Group/sender-key-record.js +47 -0
  15. package/lib/Signal/Group/sender-key-state.js +105 -0
  16. package/lib/Signal/Group/sender-message-key.js +30 -0
  17. package/lib/Signal/libsignal.js +416 -0
  18. package/lib/Signal/lid-mapping.js +189 -0
  19. package/lib/Socket/Client/index.js +3 -0
  20. package/lib/Socket/Client/types.js +11 -0
  21. package/lib/Socket/Client/websocket.js +61 -0
  22. package/lib/Socket/business.js +404 -0
  23. package/lib/Socket/chats.js +1146 -0
  24. package/lib/Socket/communities.js +505 -0
  25. package/lib/Socket/groups.js +404 -0
  26. package/lib/Socket/index.js +18 -0
  27. package/lib/Socket/messages-recv.js +1600 -0
  28. package/lib/Socket/messages-send.js +1203 -0
  29. package/lib/Socket/mex.js +56 -0
  30. package/lib/Socket/newsletter.js +240 -0
  31. package/lib/Socket/socket.js +1060 -0
  32. package/lib/Types/Auth.js +2 -0
  33. package/lib/Types/Bussines.js +2 -0
  34. package/lib/Types/Call.js +2 -0
  35. package/lib/Types/Chat.js +8 -0
  36. package/lib/Types/Contact.js +2 -0
  37. package/lib/Types/Events.js +2 -0
  38. package/lib/Types/GroupMetadata.js +2 -0
  39. package/lib/Types/Label.js +25 -0
  40. package/lib/Types/LabelAssociation.js +7 -0
  41. package/lib/Types/Message.js +11 -0
  42. package/lib/Types/Newsletter.js +31 -0
  43. package/lib/Types/Product.js +2 -0
  44. package/lib/Types/Signal.js +2 -0
  45. package/lib/Types/Socket.js +3 -0
  46. package/lib/Types/State.js +13 -0
  47. package/lib/Types/USync.js +2 -0
  48. package/lib/Types/index.js +32 -0
  49. package/lib/Utils/auth-utils.js +276 -0
  50. package/lib/Utils/browser-utils.js +32 -0
  51. package/lib/Utils/business.js +262 -0
  52. package/lib/Utils/chat-utils.js +941 -0
  53. package/lib/Utils/crypto.js +179 -0
  54. package/lib/Utils/decode-wa-message.js +333 -0
  55. package/lib/Utils/event-buffer.js +580 -0
  56. package/lib/Utils/generics.js +436 -0
  57. package/lib/Utils/history.js +103 -0
  58. package/lib/Utils/index.js +19 -0
  59. package/lib/Utils/link-preview.js +105 -0
  60. package/lib/Utils/logger.js +3 -0
  61. package/lib/Utils/lt-hash.js +56 -0
  62. package/lib/Utils/make-mutex.js +38 -0
  63. package/lib/Utils/message-retry-manager.js +181 -0
  64. package/lib/Utils/messages-media.js +727 -0
  65. package/lib/Utils/messages.js +1309 -0
  66. package/lib/Utils/noise-handler.js +162 -0
  67. package/lib/Utils/pre-key-manager.js +125 -0
  68. package/lib/Utils/process-message.js +594 -0
  69. package/lib/Utils/signal.js +194 -0
  70. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  71. package/lib/Utils/validate-connection.js +240 -0
  72. package/lib/WABinary/constants.js +1301 -0
  73. package/lib/WABinary/decode.js +240 -0
  74. package/lib/WABinary/encode.js +216 -0
  75. package/lib/WABinary/generic-utils.js +104 -0
  76. package/lib/WABinary/index.js +6 -0
  77. package/lib/WABinary/jid-utils.js +95 -0
  78. package/lib/WABinary/types.js +2 -0
  79. package/lib/WAM/BinaryInfo.js +10 -0
  80. package/lib/WAM/constants.js +22863 -0
  81. package/lib/WAM/encode.js +152 -0
  82. package/lib/WAM/index.js +4 -0
  83. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  84. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  85. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  86. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -0
  87. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +60 -0
  88. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  89. package/lib/WAUSync/Protocols/index.js +5 -0
  90. package/lib/WAUSync/USyncQuery.js +104 -0
  91. package/lib/WAUSync/USyncUser.js +23 -0
  92. package/lib/WAUSync/index.js +4 -0
  93. package/lib/index.js +11 -0
  94. package/package.json +31 -0
  95. package/readme.md +522 -0
@@ -0,0 +1,436 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { createHash, randomBytes } from "crypto";
3
+ import { proto } from "../../WAProto/index.js";
4
+ const baileysVersion = [2, 3000, 1027934701];
5
+ import { DisconnectReason } from "../Types/index.js";
6
+ import { getAllBinaryNodeChildren, jidDecode } from "../WABinary/index.js";
7
+ import { sha256 } from "./crypto.js";
8
+ export const BufferJSON = {
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ replacer: (k, value) => {
11
+ if (
12
+ Buffer.isBuffer(value) ||
13
+ value instanceof Uint8Array ||
14
+ value?.type === "Buffer"
15
+ ) {
16
+ return {
17
+ type: "Buffer",
18
+ data: Buffer.from(value?.data || value).toString("base64"),
19
+ };
20
+ }
21
+ return value;
22
+ },
23
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
+ reviver: (_, value) => {
25
+ if (
26
+ typeof value === "object" &&
27
+ value !== null &&
28
+ value.type === "Buffer" &&
29
+ typeof value.data === "string"
30
+ ) {
31
+ return Buffer.from(value.data, "base64");
32
+ }
33
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
34
+ const keys = Object.keys(value);
35
+ if (keys.length > 0 && keys.every((k) => !isNaN(parseInt(k, 10)))) {
36
+ const values = Object.values(value);
37
+ if (values.every((v) => typeof v === "number")) {
38
+ return Buffer.from(values);
39
+ }
40
+ }
41
+ }
42
+ return value;
43
+ },
44
+ };
45
+ export const getKeyAuthor = (key, meId = "me") =>
46
+ (key?.fromMe
47
+ ? meId
48
+ : key?.participantAlt ||
49
+ key?.remoteJidAlt ||
50
+ key?.participant ||
51
+ key?.remoteJid) || "";
52
+ export const writeRandomPadMax16 = (msg) => {
53
+ const pad = randomBytes(1);
54
+ const padLength = (pad[0] & 0x0f) + 1;
55
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
56
+ };
57
+ export const unpadRandomMax16 = (e) => {
58
+ const t = new Uint8Array(e);
59
+ if (0 === t.length) {
60
+ throw new Error("unpadPkcs7 given empty bytes");
61
+ }
62
+ var r = t[t.length - 1];
63
+ if (r > t.length) {
64
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
65
+ }
66
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
67
+ };
68
+ // code is inspired by whatsmeow
69
+ export const generateParticipantHashV2 = (participants) => {
70
+ participants.sort();
71
+ const sha256Hash = sha256(Buffer.from(participants.join(""))).toString(
72
+ "base64",
73
+ );
74
+ return "2:" + sha256Hash.slice(0, 6);
75
+ };
76
+ export const encodeWAMessage = (message) =>
77
+ writeRandomPadMax16(proto.Message.encode(message).finish());
78
+ export const generateRegistrationId = () => {
79
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
80
+ };
81
+ export const encodeBigEndian = (e, t = 4) => {
82
+ let r = e;
83
+ const a = new Uint8Array(t);
84
+ for (let i = t - 1; i >= 0; i--) {
85
+ a[i] = 255 & r;
86
+ r >>>= 8;
87
+ }
88
+ return a;
89
+ };
90
+ export const toNumber = (t) =>
91
+ typeof t === "object" && t
92
+ ? "toNumber" in t
93
+ ? t.toNumber()
94
+ : t.low
95
+ : t || 0;
96
+ /** unix timestamp of a date in seconds */
97
+ export const unixTimestampSeconds = (date = new Date()) =>
98
+ Math.floor(date.getTime() / 1000);
99
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
100
+ let timeout;
101
+ return {
102
+ start: (newIntervalMs, newTask) => {
103
+ task = newTask || task;
104
+ intervalMs = newIntervalMs || intervalMs;
105
+ timeout && clearTimeout(timeout);
106
+ timeout = setTimeout(() => task?.(), intervalMs);
107
+ },
108
+ cancel: () => {
109
+ timeout && clearTimeout(timeout);
110
+ timeout = undefined;
111
+ },
112
+ setTask: (newTask) => (task = newTask),
113
+ setInterval: (newInterval) => (intervalMs = newInterval),
114
+ };
115
+ };
116
+ export const delay = (ms) => delayCancellable(ms).delay;
117
+ export const delayCancellable = (ms) => {
118
+ const stack = new Error().stack;
119
+ let timeout;
120
+ let reject;
121
+ const delay = new Promise((resolve, _reject) => {
122
+ timeout = setTimeout(resolve, ms);
123
+ reject = _reject;
124
+ });
125
+ const cancel = () => {
126
+ clearTimeout(timeout);
127
+ reject(
128
+ new Boom("Cancelled", {
129
+ statusCode: 500,
130
+ data: {
131
+ stack,
132
+ },
133
+ }),
134
+ );
135
+ };
136
+ return { delay, cancel };
137
+ };
138
+ export async function promiseTimeout(ms, promise) {
139
+ if (!ms) {
140
+ return new Promise(promise);
141
+ }
142
+ const stack = new Error().stack;
143
+ // Create a promise that rejects in <ms> milliseconds
144
+ const { delay, cancel } = delayCancellable(ms);
145
+ const p = new Promise((resolve, reject) => {
146
+ delay
147
+ .then(() =>
148
+ reject(
149
+ new Boom("Timed Out", {
150
+ statusCode: DisconnectReason.timedOut,
151
+ data: {
152
+ stack,
153
+ },
154
+ }),
155
+ ),
156
+ )
157
+ .catch((err) => reject(err));
158
+ promise(resolve, reject);
159
+ }).finally(cancel);
160
+ return p;
161
+ }
162
+ // inspired from whatsmeow code
163
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
164
+ export const generateMessageIDV2 = (userId) => {
165
+ const data = Buffer.alloc(8 + 20 + 16);
166
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
167
+ if (userId) {
168
+ const id = jidDecode(userId);
169
+ if (id?.user) {
170
+ data.write(id.user, 8);
171
+ data.write("@c.us", 8 + id.user.length);
172
+ }
173
+ }
174
+ const random = randomBytes(16);
175
+ random.copy(data, 28);
176
+ const hash = createHash("sha256").update(data).digest();
177
+ return "3EB0" + hash.toString("hex").toUpperCase().substring(0, 18);
178
+ };
179
+ // generate a random ID to attach to a message
180
+ export const generateMessageID = () =>
181
+ "3EB0" + randomBytes(18).toString("hex").toUpperCase();
182
+ export function bindWaitForEvent(ev, event) {
183
+ return async (check, timeoutMs) => {
184
+ let listener;
185
+ let closeListener;
186
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
187
+ closeListener = ({ connection, lastDisconnect }) => {
188
+ if (connection === "close") {
189
+ reject(
190
+ lastDisconnect?.error ||
191
+ new Boom("Connection Closed", {
192
+ statusCode: DisconnectReason.connectionClosed,
193
+ }),
194
+ );
195
+ }
196
+ };
197
+ ev.on("connection.update", closeListener);
198
+ listener = async (update) => {
199
+ if (await check(update)) {
200
+ resolve();
201
+ }
202
+ };
203
+ ev.on(event, listener);
204
+ }).finally(() => {
205
+ ev.off(event, listener);
206
+ ev.off("connection.update", closeListener);
207
+ });
208
+ };
209
+ }
210
+ export const bindWaitForConnectionUpdate = (ev) =>
211
+ bindWaitForEvent(ev, "connection.update");
212
+ /**
213
+ * utility that fetches latest baileys version from the master branch.
214
+ * Use to ensure your WA connection is always on the latest version
215
+ */
216
+ export const fetchLatestBaileysVersion = async (options = {}) => {
217
+ const URL =
218
+ "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
219
+ try {
220
+ const response = await fetch(URL, {
221
+ dispatcher: options.dispatcher,
222
+ method: "GET",
223
+ headers: options.headers,
224
+ });
225
+ if (!response.ok) {
226
+ throw new Boom(
227
+ `Failed to fetch latest Baileys version: ${response.statusText}`,
228
+ { statusCode: response.status },
229
+ );
230
+ }
231
+ const text = await response.text();
232
+ // Extract version from line 7 (const version = [...])
233
+ const lines = text.split("\n");
234
+ const versionLine = lines[6]; // Line 7 (0-indexed)
235
+ const versionMatch = versionLine.match(
236
+ /const version = \[(\d+),\s*(\d+),\s*(\d+)\]/,
237
+ );
238
+ if (versionMatch) {
239
+ const version = [
240
+ parseInt(versionMatch[1]),
241
+ parseInt(versionMatch[2]),
242
+ parseInt(versionMatch[3]),
243
+ ];
244
+ return {
245
+ version,
246
+ isLatest: true,
247
+ };
248
+ } else {
249
+ throw new Error("Could not parse version from Defaults/index.ts");
250
+ }
251
+ } catch (error) {
252
+ return {
253
+ version: baileysVersion,
254
+ isLatest: false,
255
+ error,
256
+ };
257
+ }
258
+ };
259
+ /**
260
+ * A utility that fetches the latest web version of whatsapp.
261
+ * Use to ensure your WA connection is always on the latest version
262
+ */
263
+ export const fetchLatestWaWebVersion = async (options = {}) => {
264
+ try {
265
+ // Absolute minimal headers required to bypass anti-bot detection
266
+ const defaultHeaders = {
267
+ "sec-fetch-site": "none",
268
+ "user-agent":
269
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
270
+ };
271
+ const headers = { ...defaultHeaders, ...options.headers };
272
+ const response = await fetch("https://web.whatsapp.com/sw.js", {
273
+ ...options,
274
+ method: "GET",
275
+ headers,
276
+ });
277
+ if (!response.ok) {
278
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, {
279
+ statusCode: response.status,
280
+ });
281
+ }
282
+ const data = await response.text();
283
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
284
+ const match = data.match(regex);
285
+ if (!match?.[1]) {
286
+ return {
287
+ version: baileysVersion,
288
+ isLatest: false,
289
+ error: {
290
+ message: "Could not find client revision in the fetched content",
291
+ },
292
+ };
293
+ }
294
+ const clientRevision = match[1];
295
+ return {
296
+ version: [2, 3000, +clientRevision],
297
+ isLatest: true,
298
+ };
299
+ } catch (error) {
300
+ return {
301
+ version: baileysVersion,
302
+ isLatest: false,
303
+ error,
304
+ };
305
+ }
306
+ };
307
+ /** unique message tag prefix for MD clients */
308
+ export const generateMdTagPrefix = () => {
309
+ const bytes = randomBytes(4);
310
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
311
+ };
312
+ const STATUS_MAP = {
313
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
314
+ played: proto.WebMessageInfo.Status.PLAYED,
315
+ read: proto.WebMessageInfo.Status.READ,
316
+ "read-self": proto.WebMessageInfo.Status.READ,
317
+ };
318
+ /**
319
+ * Given a type of receipt, returns what the new status of the message should be
320
+ * @param type type from receipt
321
+ */
322
+ export const getStatusFromReceiptType = (type) => {
323
+ const status = STATUS_MAP[type];
324
+ if (typeof type === "undefined") {
325
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
326
+ }
327
+ return status;
328
+ };
329
+ const CODE_MAP = {
330
+ conflict: DisconnectReason.connectionReplaced,
331
+ };
332
+ /**
333
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
334
+ * @param reason the string reason given, eg. "conflict"
335
+ */
336
+ export const getErrorCodeFromStreamError = (node) => {
337
+ const [reasonNode] = getAllBinaryNodeChildren(node);
338
+ let reason = reasonNode?.tag || "unknown";
339
+ const statusCode = +(
340
+ node.attrs.code ||
341
+ CODE_MAP[reason] ||
342
+ DisconnectReason.badSession
343
+ );
344
+ if (statusCode === DisconnectReason.restartRequired) {
345
+ reason = "restart required";
346
+ }
347
+ return {
348
+ reason,
349
+ statusCode,
350
+ };
351
+ };
352
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
353
+ let status;
354
+ switch (tag) {
355
+ case "offer":
356
+ case "offer_notice":
357
+ status = "offer";
358
+ break;
359
+ case "terminate":
360
+ if (attrs.reason === "timeout") {
361
+ status = "timeout";
362
+ } else {
363
+ //fired when accepted/rejected/timeout/caller hangs up
364
+ status = "terminate";
365
+ }
366
+ break;
367
+ case "reject":
368
+ status = "reject";
369
+ break;
370
+ case "accept":
371
+ status = "accept";
372
+ break;
373
+ default:
374
+ status = "ringing";
375
+ break;
376
+ }
377
+ return status;
378
+ };
379
+ const UNEXPECTED_SERVER_CODE_TEXT = "Unexpected server response: ";
380
+ export const getCodeFromWSError = (error) => {
381
+ let statusCode = 500;
382
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
383
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
384
+ if (!Number.isNaN(code) && code >= 400) {
385
+ statusCode = code;
386
+ }
387
+ } else if (
388
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
389
+ error?.code?.startsWith("E") ||
390
+ error?.message?.includes("timed out")
391
+ ) {
392
+ // handle ETIMEOUT, ENOTFOUND etc
393
+ statusCode = 408;
394
+ }
395
+ return statusCode;
396
+ };
397
+ /**
398
+ * Is the given platform WA business
399
+ * @param platform AuthenticationCreds.platform
400
+ */
401
+ export const isWABusinessPlatform = (platform) => {
402
+ return platform === "smbi" || platform === "smba";
403
+ };
404
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
405
+ export function trimUndefined(obj) {
406
+ for (const key in obj) {
407
+ if (typeof obj[key] === "undefined") {
408
+ delete obj[key];
409
+ }
410
+ }
411
+ return obj;
412
+ }
413
+ const CROCKFORD_CHARACTERS = "123456789ABCDEFGHJKLMNPQRSTVWXYZ";
414
+ export function bytesToCrockford(buffer) {
415
+ let value = 0;
416
+ let bitCount = 0;
417
+ const crockford = [];
418
+ for (const element of buffer) {
419
+ value = (value << 8) | (element & 0xff);
420
+ bitCount += 8;
421
+ while (bitCount >= 5) {
422
+ crockford.push(
423
+ CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31),
424
+ );
425
+ bitCount -= 5;
426
+ }
427
+ }
428
+ if (bitCount > 0) {
429
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
430
+ }
431
+ return crockford.join("");
432
+ }
433
+ export function encodeNewsletterMessage(message) {
434
+ return proto.Message.encode(message).finish();
435
+ }
436
+ //# sourceMappingURL=generics.js.map
@@ -0,0 +1,103 @@
1
+ import { promisify } from "util";
2
+ import { inflate } from "zlib";
3
+ import { proto } from "../../WAProto/index.js";
4
+ import { WAMessageStubType } from "../Types/index.js";
5
+ import { toNumber } from "./generics.js";
6
+ import { normalizeMessageContent } from "./messages.js";
7
+ import { downloadContentFromMessage } from "./messages-media.js";
8
+ const inflatePromise = promisify(inflate);
9
+ export const downloadHistory = async (msg, options) => {
10
+ const stream = await downloadContentFromMessage(msg, "md-msg-hist", {
11
+ options,
12
+ });
13
+ const bufferArray = [];
14
+ for await (const chunk of stream) {
15
+ bufferArray.push(chunk);
16
+ }
17
+ let buffer = Buffer.concat(bufferArray);
18
+ // decompress buffer
19
+ buffer = await inflatePromise(buffer);
20
+ const syncData = proto.HistorySync.decode(buffer);
21
+ return syncData;
22
+ };
23
+ export const processHistoryMessage = (item) => {
24
+ const messages = [];
25
+ const contacts = [];
26
+ const chats = [];
27
+ switch (item.syncType) {
28
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
29
+ case proto.HistorySync.HistorySyncType.RECENT:
30
+ case proto.HistorySync.HistorySyncType.FULL:
31
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
32
+ for (const chat of item.conversations) {
33
+ contacts.push({
34
+ id: chat.id,
35
+ name: chat.name || undefined,
36
+ lid: chat.lidJid || undefined,
37
+ phoneNumber: chat.pnJid || undefined,
38
+ });
39
+ const msgs = chat.messages || [];
40
+ delete chat.messages;
41
+ for (const item of msgs) {
42
+ const message = item.message;
43
+ messages.push(message);
44
+ if (!chat.messages?.length) {
45
+ // keep only the most recent message in the chat array
46
+ chat.messages = [{ message }];
47
+ }
48
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
49
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
50
+ }
51
+ if (
52
+ (message.messageStubType ===
53
+ WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
54
+ message.messageStubType ===
55
+ WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
56
+ message.messageStubParameters?.[0]
57
+ ) {
58
+ contacts.push({
59
+ id: message.key.participant || message.key.remoteJid,
60
+ verifiedName: message.messageStubParameters?.[0],
61
+ });
62
+ }
63
+ }
64
+ chats.push({ ...chat });
65
+ }
66
+ break;
67
+ case 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
+ syncType: item.syncType,
78
+ progress: item.progress,
79
+ };
80
+ };
81
+ export const downloadAndProcessHistorySyncNotification = async (
82
+ msg,
83
+ options,
84
+ ) => {
85
+ let historyMsg;
86
+ if (msg.initialHistBootstrapInlinePayload) {
87
+ historyMsg = proto.HistorySync.decode(
88
+ await inflatePromise(msg.initialHistBootstrapInlinePayload),
89
+ );
90
+ } else {
91
+ historyMsg = await downloadHistory(msg, options);
92
+ }
93
+ return processHistoryMessage(historyMsg);
94
+ };
95
+ export const getHistoryMsg = (message) => {
96
+ const normalizedContent = !!message
97
+ ? normalizeMessageContent(message)
98
+ : undefined;
99
+ const anyHistoryMsg =
100
+ normalizedContent?.protocolMessage?.historySyncNotification;
101
+ return anyHistoryMsg;
102
+ };
103
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,19 @@
1
+ export * from "./generics.js";
2
+ export * from "./decode-wa-message.js";
3
+ export * from "./messages.js";
4
+ export * from "./messages-media.js";
5
+ export * from "./validate-connection.js";
6
+ export * from "./crypto.js";
7
+ export * from "./signal.js";
8
+ export * from "./noise-handler.js";
9
+ export * from "./history.js";
10
+ export * from "./chat-utils.js";
11
+ export * from "./lt-hash.js";
12
+ export * from "./auth-utils.js";
13
+ export * from "./use-multi-file-auth-state.js";
14
+ export * from "./link-preview.js";
15
+ export * from "./event-buffer.js";
16
+ export * from "./process-message.js";
17
+ export * from "./message-retry-manager.js";
18
+ export * from "./browser-utils.js";
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,105 @@
1
+ import { prepareWAMessageMedia } from "./messages.js";
2
+ import { extractImageThumb, getHttpStream } from "./messages-media.js";
3
+
4
+ const THUMBNAIL_WIDTH_PX = 192;
5
+
6
+ /** Fetches an image and generates a thumbnail for it */
7
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
8
+ const stream = await getHttpStream(url, fetchOpts);
9
+ const result = await extractImageThumb(stream, thumbnailWidth);
10
+ return result;
11
+ };
12
+
13
+ /**
14
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
15
+ * Return undefined if the fetch failed or no URL was found
16
+ * @param text first matched URL in text
17
+ * @returns the URL info required to generate link preview
18
+ */
19
+ export const getUrlInfo = async (
20
+ text,
21
+ opts = {
22
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
23
+ fetchOpts: { timeout: 3000 },
24
+ },
25
+ ) => {
26
+ try {
27
+ // retries
28
+ let retries = 0;
29
+ const maxRetry = 5;
30
+
31
+ const { getLinkPreview } = await import("link-preview-js");
32
+ let previewLink = text;
33
+ if (!text.startsWith("https://") && !text.startsWith("http://")) {
34
+ previewLink = "https://" + previewLink;
35
+ }
36
+
37
+ const info = await getLinkPreview(previewLink, {
38
+ ...opts.fetchOpts,
39
+ followRedirects: "follow",
40
+ handleRedirects: (baseURL, forwardedURL) => {
41
+ const urlObj = new URL(baseURL);
42
+ const forwardedURLObj = new URL(forwardedURL);
43
+ if (retries >= maxRetry) {
44
+ return false;
45
+ }
46
+
47
+ if (
48
+ forwardedURLObj.hostname === urlObj.hostname ||
49
+ forwardedURLObj.hostname === "www." + urlObj.hostname ||
50
+ "www." + forwardedURLObj.hostname === urlObj.hostname
51
+ ) {
52
+ retries += 1;
53
+ return true;
54
+ } else {
55
+ return false;
56
+ }
57
+ },
58
+ headers: opts.fetchOpts?.headers,
59
+ });
60
+
61
+ if (info && "title" in info && info.title) {
62
+ const [image] = info.images;
63
+
64
+ const urlInfo = {
65
+ "canonical-url": info.url,
66
+ "matched-text": text,
67
+ title: info.title,
68
+ description: info.description,
69
+ originalThumbnailUrl: image,
70
+ };
71
+
72
+ if (opts.uploadImage) {
73
+ const { imageMessage } = await prepareWAMessageMedia(
74
+ { image: { url: image } },
75
+ {
76
+ upload: opts.uploadImage,
77
+ mediaTypeOverride: "thumbnail-link",
78
+ options: opts.fetchOpts,
79
+ },
80
+ );
81
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail
82
+ ? Buffer.from(imageMessage.jpegThumbnail)
83
+ : undefined;
84
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
85
+ } else {
86
+ try {
87
+ urlInfo.jpegThumbnail = image
88
+ ? (await getCompressedJpegThumbnail(image, opts)).buffer
89
+ : undefined;
90
+ } catch (error) {
91
+ opts.logger?.debug(
92
+ { err: error.stack, url: previewLink },
93
+ "error in generating thumbnail",
94
+ );
95
+ }
96
+ }
97
+
98
+ return urlInfo;
99
+ }
100
+ } catch (error) {
101
+ if (!error.message.includes("receive a valid")) {
102
+ throw error;
103
+ }
104
+ }
105
+ };
@@ -0,0 +1,3 @@
1
+ import P from "pino";
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
3
+ //# sourceMappingURL=logger.js.map