@fr3xtoy/baileys 1.1.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.
- package/LICENSE +21 -0
- package/README.md +415 -0
- package/WAProto/index.js +169661 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +53 -0
- package/lib/Defaults/index.js +147 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
- package/lib/Signal/Group/ciphertext-message.js +15 -0
- package/lib/Signal/Group/group-session-builder.d.ts +14 -0
- package/lib/Signal/Group/group-session-builder.js +64 -0
- package/lib/Signal/Group/group_cipher.d.ts +17 -0
- package/lib/Signal/Group/group_cipher.js +96 -0
- package/lib/Signal/Group/index.d.ts +11 -0
- package/lib/Signal/Group/index.js +57 -0
- package/lib/Signal/Group/keyhelper.d.ts +10 -0
- package/lib/Signal/Group/keyhelper.js +55 -0
- package/lib/Signal/Group/queue-job.d.ts +1 -0
- package/lib/Signal/Group/queue-job.js +57 -0
- package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
- package/lib/Signal/Group/sender-chain-key.js +34 -0
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.d.ts +18 -0
- package/lib/Signal/Group/sender-key-message.js +69 -0
- package/lib/Signal/Group/sender-key-name.d.ts +17 -0
- package/lib/Signal/Group/sender-key-name.js +51 -0
- package/lib/Signal/Group/sender-key-record.d.ts +30 -0
- package/lib/Signal/Group/sender-key-record.js +53 -0
- package/lib/Signal/Group/sender-key-state.d.ts +38 -0
- package/lib/Signal/Group/sender-key-state.js +99 -0
- package/lib/Signal/Group/sender-message-key.d.ts +11 -0
- package/lib/Signal/Group/sender-message-key.js +29 -0
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +174 -0
- package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
- package/lib/Socket/Client/abstract-socket-client.js +13 -0
- package/lib/Socket/Client/index.d.ts +3 -0
- package/lib/Socket/Client/index.js +19 -0
- package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
- package/lib/Socket/Client/mobile-socket-client.js +65 -0
- package/lib/Socket/Client/web-socket-client.d.ts +12 -0
- package/lib/Socket/Client/web-socket-client.js +62 -0
- package/lib/Socket/business.d.ts +171 -0
- package/lib/Socket/business.js +260 -0
- package/lib/Socket/chats.d.ts +267 -0
- package/lib/Socket/chats.js +983 -0
- package/lib/Socket/dugong.d.ts +254 -0
- package/lib/Socket/dugong.js +480 -0
- package/lib/Socket/groups.d.ts +115 -0
- package/lib/Socket/groups.js +316 -0
- package/lib/Socket/index.d.ts +173 -0
- package/lib/Socket/index.js +11 -0
- package/lib/Socket/messages-recv.d.ts +161 -0
- package/lib/Socket/messages-recv.js +1110 -0
- package/lib/Socket/messages-send.d.ts +149 -0
- package/lib/Socket/messages-send.js +909 -0
- package/lib/Socket/newsletter.d.ts +134 -0
- package/lib/Socket/newsletter.js +336 -0
- package/lib/Socket/registration.d.ts +267 -0
- package/lib/Socket/registration.js +166 -0
- package/lib/Socket/socket.d.ts +43 -0
- package/lib/Socket/socket.js +665 -0
- package/lib/Socket/usync.d.ts +36 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/make-cache-manager-store.d.ts +13 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/lib/Store/make-in-memory-store.js +427 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.d.ts +110 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +102 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.d.ts +19 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +157 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +55 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +35 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.d.ts +29 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.d.ts +273 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/Newsletter.d.ts +103 -0
- package/lib/Types/Newsletter.js +38 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.d.ts +57 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +111 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +57 -0
- package/lib/Types/index.js +42 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/lib/Utils/auth-utils.js +206 -0
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.d.ts +22 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/chat-utils.d.ts +71 -0
- package/lib/Utils/chat-utils.js +729 -0
- package/lib/Utils/crypto.d.ts +41 -0
- package/lib/Utils/crypto.js +151 -0
- package/lib/Utils/decode-wa-message.d.ts +19 -0
- package/lib/Utils/decode-wa-message.js +198 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/lib/Utils/event-buffer.js +514 -0
- package/lib/Utils/generics.d.ts +72 -0
- package/lib/Utils/generics.js +405 -0
- package/lib/Utils/history.d.ts +15 -0
- package/lib/Utils/history.js +96 -0
- package/lib/Utils/index.d.ts +17 -0
- package/lib/Utils/index.js +33 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/lib/Utils/link-preview.js +93 -0
- package/lib/Utils/logger.d.ts +4 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +43 -0
- package/lib/Utils/messages-media.d.ts +116 -0
- package/lib/Utils/messages-media.js +819 -0
- package/lib/Utils/messages.d.ts +77 -0
- package/lib/Utils/messages.js +767 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.js +155 -0
- package/lib/Utils/process-message.d.ts +41 -0
- package/lib/Utils/process-message.js +321 -0
- package/lib/Utils/signal.d.ts +32 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
- package/lib/Utils/use-multi-file-auth-state.js +119 -0
- package/lib/Utils/validate-connection.d.ts +11 -0
- package/lib/Utils/validate-connection.js +229 -0
- package/lib/WABinary/constants.d.ts +30 -0
- package/lib/WABinary/constants.js +40 -0
- package/lib/WABinary/decode.d.ts +7 -0
- package/lib/WABinary/decode.js +252 -0
- package/lib/WABinary/encode.d.ts +3 -0
- package/lib/WABinary/encode.js +265 -0
- package/lib/WABinary/generic-utils.d.ts +17 -0
- package/lib/WABinary/generic-utils.js +198 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.d.ts +31 -0
- package/lib/WABinary/jid-utils.js +62 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +17 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.d.ts +38 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.d.ts +3 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.d.ts +4 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.d.ts +28 -0
- package/lib/WAUSync/USyncQuery.js +89 -0
- package/lib/WAUSync/USyncUser.d.ts +12 -0
- package/lib/WAUSync/USyncUser.js +26 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +60 -0
- package/package.json +101 -0
|
@@ -0,0 +1,405 @@
|
|
|
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.bytesToCrockford = exports.trimUndefined = 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.generateMessageIDV2 = 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;
|
|
7
|
+
const boom_1 = require("@hapi/boom");
|
|
8
|
+
const axios_1 = __importDefault(require("axios"));
|
|
9
|
+
const crypto_1 = require("crypto");
|
|
10
|
+
const os_1 = require("os");
|
|
11
|
+
const fetch_1 = require("node-fetch")
|
|
12
|
+
const WAProto_1 = require("../../WAProto");
|
|
13
|
+
const baileys_version_json_1 = require("../Defaults/baileys-version.json");
|
|
14
|
+
const Types_1 = require("../Types");
|
|
15
|
+
const WABinary_1 = require("../WABinary");
|
|
16
|
+
const baileysVersion = [2, 3000, 1029030078]
|
|
17
|
+
const PLATFORM_MAP = {
|
|
18
|
+
'aix': 'AIX',
|
|
19
|
+
'darwin': 'Mac OS',
|
|
20
|
+
'win32': 'Windows',
|
|
21
|
+
'android': 'Android',
|
|
22
|
+
'freebsd': 'FreeBSD',
|
|
23
|
+
'openbsd': 'OpenBSD',
|
|
24
|
+
'sunos': 'Solaris',
|
|
25
|
+
'linux': undefined,
|
|
26
|
+
'haiku': undefined,
|
|
27
|
+
'cygwin': undefined,
|
|
28
|
+
'netbsd': undefined
|
|
29
|
+
};
|
|
30
|
+
exports.Browsers = (browser) => {
|
|
31
|
+
const osName = PLATFORM_MAP[os_1.platform()] || 'Ubuntu';
|
|
32
|
+
const osRelease = os_1.release();
|
|
33
|
+
return [osName, browser, osRelease];
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const getPlatformId = (browser) => {
|
|
37
|
+
const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
|
|
38
|
+
return platformType ? platformType.toString() : '1'; //chrome
|
|
39
|
+
};
|
|
40
|
+
exports.getPlatformId = getPlatformId;
|
|
41
|
+
exports.BufferJSON = {
|
|
42
|
+
replacer: (k, value) => {
|
|
43
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
|
|
44
|
+
return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
},
|
|
48
|
+
reviver: (_, value) => {
|
|
49
|
+
if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
|
|
50
|
+
const val = value.data || value.value;
|
|
51
|
+
return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
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)) || '');
|
|
57
|
+
exports.getKeyAuthor = getKeyAuthor;
|
|
58
|
+
const writeRandomPadMax16 = (msg) => {
|
|
59
|
+
const pad = (0, crypto_1.randomBytes)(1);
|
|
60
|
+
pad[0] &= 0xf;
|
|
61
|
+
if (!pad[0]) {
|
|
62
|
+
pad[0] = 0xf;
|
|
63
|
+
}
|
|
64
|
+
return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
|
|
65
|
+
};
|
|
66
|
+
exports.writeRandomPadMax16 = writeRandomPadMax16;
|
|
67
|
+
const unpadRandomMax16 = (e) => {
|
|
68
|
+
const t = new Uint8Array(e);
|
|
69
|
+
if (0 === t.length) {
|
|
70
|
+
throw new Error('unpadPkcs7 given empty bytes');
|
|
71
|
+
}
|
|
72
|
+
var r = t[t.length - 1];
|
|
73
|
+
if (r > t.length) {
|
|
74
|
+
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
|
|
75
|
+
}
|
|
76
|
+
return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
|
|
77
|
+
};
|
|
78
|
+
exports.unpadRandomMax16 = unpadRandomMax16;
|
|
79
|
+
const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
|
|
80
|
+
exports.encodeWAMessage = encodeWAMessage;
|
|
81
|
+
const generateRegistrationId = () => {
|
|
82
|
+
return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
|
|
83
|
+
};
|
|
84
|
+
exports.generateRegistrationId = generateRegistrationId;
|
|
85
|
+
const encodeBigEndian = (e, t = 4) => {
|
|
86
|
+
let r = e;
|
|
87
|
+
const a = new Uint8Array(t);
|
|
88
|
+
for (let i = t - 1; i >= 0; i--) {
|
|
89
|
+
a[i] = 255 & r;
|
|
90
|
+
r >>>= 8;
|
|
91
|
+
}
|
|
92
|
+
return a;
|
|
93
|
+
};
|
|
94
|
+
exports.encodeBigEndian = encodeBigEndian;
|
|
95
|
+
const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
|
|
96
|
+
exports.toNumber = toNumber;
|
|
97
|
+
|
|
98
|
+
const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
|
|
99
|
+
exports.unixTimestampSeconds = unixTimestampSeconds;
|
|
100
|
+
const debouncedTimeout = (intervalMs = 1000, task) => {
|
|
101
|
+
let timeout;
|
|
102
|
+
return {
|
|
103
|
+
start: (newIntervalMs, newTask) => {
|
|
104
|
+
task = newTask || task;
|
|
105
|
+
intervalMs = newIntervalMs || intervalMs;
|
|
106
|
+
timeout && clearTimeout(timeout);
|
|
107
|
+
timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
|
|
108
|
+
},
|
|
109
|
+
cancel: () => {
|
|
110
|
+
timeout && clearTimeout(timeout);
|
|
111
|
+
timeout = undefined;
|
|
112
|
+
},
|
|
113
|
+
setTask: (newTask) => task = newTask,
|
|
114
|
+
setInterval: (newInterval) => intervalMs = newInterval
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
exports.debouncedTimeout = debouncedTimeout;
|
|
118
|
+
const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
|
|
119
|
+
exports.delay = delay;
|
|
120
|
+
const delayCancellable = (ms) => {
|
|
121
|
+
const stack = new Error().stack;
|
|
122
|
+
let timeout;
|
|
123
|
+
let reject;
|
|
124
|
+
const delay = new Promise((resolve, _reject) => {
|
|
125
|
+
timeout = setTimeout(resolve, ms);
|
|
126
|
+
reject = _reject;
|
|
127
|
+
});
|
|
128
|
+
const cancel = () => {
|
|
129
|
+
clearTimeout(timeout);
|
|
130
|
+
reject(new boom_1.Boom('Cancelled', {
|
|
131
|
+
statusCode: 500,
|
|
132
|
+
data: {
|
|
133
|
+
stack
|
|
134
|
+
}
|
|
135
|
+
}));
|
|
136
|
+
};
|
|
137
|
+
return { delay, cancel };
|
|
138
|
+
};
|
|
139
|
+
exports.delayCancellable = delayCancellable;
|
|
140
|
+
async function promiseTimeout(ms, promise) {
|
|
141
|
+
if (!ms) {
|
|
142
|
+
return new Promise(promise);
|
|
143
|
+
}
|
|
144
|
+
const stack = new Error().stack;
|
|
145
|
+
const { delay, cancel } = (0, exports.delayCancellable)(ms);
|
|
146
|
+
const p = new Promise((resolve, reject) => {
|
|
147
|
+
delay
|
|
148
|
+
.then(() => reject(new boom_1.Boom('Timed Out', {
|
|
149
|
+
statusCode: Types_1.DisconnectReason.timedOut,
|
|
150
|
+
data: {
|
|
151
|
+
stack
|
|
152
|
+
}
|
|
153
|
+
})))
|
|
154
|
+
.catch(err => reject(err));
|
|
155
|
+
promise(resolve, reject);
|
|
156
|
+
})
|
|
157
|
+
.finally(cancel);
|
|
158
|
+
return p;
|
|
159
|
+
}
|
|
160
|
+
exports.promiseTimeout = promiseTimeout;
|
|
161
|
+
const generateMessageIDV2 = (userId) => {
|
|
162
|
+
const data = Buffer.alloc(8 + 20 + 16);
|
|
163
|
+
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
|
|
164
|
+
if (userId) {
|
|
165
|
+
const id = (0, WABinary_1.jidDecode)(userId);
|
|
166
|
+
if (id === null || id === void 0 ? void 0 : id.user) {
|
|
167
|
+
data.write(id.user, 8);
|
|
168
|
+
data.write('@c.us', 8 + id.user.length);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const random = (0, crypto_1.randomBytes)(16);
|
|
172
|
+
random.copy(data, 28);
|
|
173
|
+
const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
|
|
174
|
+
return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
|
|
175
|
+
};
|
|
176
|
+
exports.generateMessageIDV2 = generateMessageIDV2;
|
|
177
|
+
|
|
178
|
+
const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
|
|
179
|
+
exports.generateMessageID = generateMessageID;
|
|
180
|
+
function bindWaitForEvent(ev, event) {
|
|
181
|
+
return async (check, timeoutMs) => {
|
|
182
|
+
let listener;
|
|
183
|
+
let closeListener;
|
|
184
|
+
await (promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
185
|
+
closeListener = ({ connection, lastDisconnect }) => {
|
|
186
|
+
if (connection === 'close') {
|
|
187
|
+
reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
|
|
188
|
+
|| new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
ev.on('connection.update', closeListener);
|
|
192
|
+
listener = (update) => {
|
|
193
|
+
if (check(update)) {
|
|
194
|
+
resolve();
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
ev.on(event, listener);
|
|
198
|
+
})
|
|
199
|
+
.finally(() => {
|
|
200
|
+
ev.off(event, listener);
|
|
201
|
+
ev.off('connection.update', closeListener);
|
|
202
|
+
}));
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
exports.bindWaitForEvent = bindWaitForEvent;
|
|
206
|
+
const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
|
|
207
|
+
exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
|
|
208
|
+
const printQRIfNecessaryListener = (ev, logger) => {
|
|
209
|
+
ev.on('connection.update', async ({ qr }) => {
|
|
210
|
+
if (qr) {
|
|
211
|
+
const QR = await import('qrcode-terminal')
|
|
212
|
+
.then(m => m.default || m)
|
|
213
|
+
.catch(() => {
|
|
214
|
+
logger.error('QR code terminal not added as dependency');
|
|
215
|
+
});
|
|
216
|
+
QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
};
|
|
220
|
+
exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
|
|
221
|
+
|
|
222
|
+
const fetchLatestWaWebVersion = async (options = {}) => {
|
|
223
|
+
try {
|
|
224
|
+
const defaultHeaders = {
|
|
225
|
+
'User-Agent':
|
|
226
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
|
227
|
+
'Accept': '*/*'
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const headers = { ...defaultHeaders, ...options.headers }
|
|
231
|
+
|
|
232
|
+
const response = await fetch_1('https://web.whatsapp.com/sw.js', {
|
|
233
|
+
method: 'GET',
|
|
234
|
+
headers
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
if (!response.ok) {
|
|
238
|
+
throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const data = await response.text()
|
|
242
|
+
const regex = /"client_revision":\s*(\d+)/
|
|
243
|
+
const match = data.match(regex)
|
|
244
|
+
|
|
245
|
+
if (!match || !match[1]) {
|
|
246
|
+
return {
|
|
247
|
+
version: baileysVersion,
|
|
248
|
+
isLatest: false,
|
|
249
|
+
error: { message: 'Client revision not found' }
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const clientRevision = match[1]
|
|
254
|
+
return {
|
|
255
|
+
version: [2, 3000, +clientRevision],
|
|
256
|
+
isLatest: true
|
|
257
|
+
}
|
|
258
|
+
} catch (error) {
|
|
259
|
+
return {
|
|
260
|
+
version: baileysVersion,
|
|
261
|
+
isLatest: false,
|
|
262
|
+
error
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
|
|
267
|
+
|
|
268
|
+
const fetchLatestBaileysVersion = async (options = {}) => {
|
|
269
|
+
const URL = 'https://raw.githubusercontent.com/fr3newera/baileys/master/src/Defaults/baileys-version.json';
|
|
270
|
+
try {
|
|
271
|
+
const result = await axios_1.default.get(URL, {
|
|
272
|
+
...options,
|
|
273
|
+
responseType: 'json'
|
|
274
|
+
});
|
|
275
|
+
return {
|
|
276
|
+
version: result.data.version,
|
|
277
|
+
isLatest: true
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
return {
|
|
282
|
+
version: baileys_version_json_1.version,
|
|
283
|
+
isLatest: false,
|
|
284
|
+
error
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
|
|
289
|
+
const generateMdTagPrefix = () => {
|
|
290
|
+
const bytes = (0, crypto_1.randomBytes)(4);
|
|
291
|
+
return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
|
|
292
|
+
};
|
|
293
|
+
exports.generateMdTagPrefix = generateMdTagPrefix;
|
|
294
|
+
const STATUS_MAP = {
|
|
295
|
+
'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
|
|
296
|
+
'read': WAProto_1.proto.WebMessageInfo.Status.READ,
|
|
297
|
+
'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const getStatusFromReceiptType = (type) => {
|
|
301
|
+
const status = STATUS_MAP[type];
|
|
302
|
+
if (typeof type === 'undefined') {
|
|
303
|
+
return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
|
|
304
|
+
}
|
|
305
|
+
return status;
|
|
306
|
+
};
|
|
307
|
+
exports.getStatusFromReceiptType = getStatusFromReceiptType;
|
|
308
|
+
const CODE_MAP = {
|
|
309
|
+
conflict: Types_1.DisconnectReason.connectionReplaced
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
const getErrorCodeFromStreamError = (node) => {
|
|
313
|
+
const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
|
|
314
|
+
let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
|
|
315
|
+
const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
|
|
316
|
+
if (statusCode === Types_1.DisconnectReason.restartRequired) {
|
|
317
|
+
reason = 'restart required';
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
reason,
|
|
321
|
+
statusCode
|
|
322
|
+
};
|
|
323
|
+
};
|
|
324
|
+
exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
|
|
325
|
+
const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
326
|
+
let status;
|
|
327
|
+
switch (tag) {
|
|
328
|
+
case 'offer':
|
|
329
|
+
case 'offer_notice':
|
|
330
|
+
status = 'offer';
|
|
331
|
+
break;
|
|
332
|
+
case 'terminate':
|
|
333
|
+
if (attrs.reason === 'timeout') {
|
|
334
|
+
status = 'timeout';
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
status = 'reject';
|
|
338
|
+
}
|
|
339
|
+
break;
|
|
340
|
+
case 'reject':
|
|
341
|
+
status = 'reject';
|
|
342
|
+
break;
|
|
343
|
+
case 'accept':
|
|
344
|
+
status = 'accept';
|
|
345
|
+
break;
|
|
346
|
+
default:
|
|
347
|
+
status = 'ringing';
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
return status;
|
|
351
|
+
};
|
|
352
|
+
exports.getCallStatusFromNode = getCallStatusFromNode;
|
|
353
|
+
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
|
|
354
|
+
const getCodeFromWSError = (error) => {
|
|
355
|
+
var _a, _b, _c;
|
|
356
|
+
let statusCode = 500;
|
|
357
|
+
if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
|
358
|
+
const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
|
|
359
|
+
if (!Number.isNaN(code) && code >= 400) {
|
|
360
|
+
statusCode = code;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
|
|
364
|
+
|| ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
|
|
365
|
+
statusCode = 408;
|
|
366
|
+
}
|
|
367
|
+
return statusCode;
|
|
368
|
+
};
|
|
369
|
+
exports.getCodeFromWSError = getCodeFromWSError;
|
|
370
|
+
const isWABusinessPlatform = (platform) => {
|
|
371
|
+
return platform === 'smbi' || platform === 'smba';
|
|
372
|
+
};
|
|
373
|
+
exports.isWABusinessPlatform = isWABusinessPlatform;
|
|
374
|
+
function trimUndefined(obj) {
|
|
375
|
+
for (const key in obj) {
|
|
376
|
+
if (typeof obj[key] === 'undefined') {
|
|
377
|
+
delete obj[key];
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return obj;
|
|
381
|
+
}
|
|
382
|
+
exports.trimUndefined = trimUndefined;
|
|
383
|
+
const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
|
|
384
|
+
function bytesToCrockford(buffer) {
|
|
385
|
+
let value = 0;
|
|
386
|
+
let bitCount = 0;
|
|
387
|
+
const crockford = [];
|
|
388
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
389
|
+
value = (value << 8) | (buffer[i] & 0xff);
|
|
390
|
+
bitCount += 8;
|
|
391
|
+
while (bitCount >= 5) {
|
|
392
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
|
|
393
|
+
bitCount -= 5;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (bitCount > 0) {
|
|
397
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
|
|
398
|
+
}
|
|
399
|
+
return crockford.join('');
|
|
400
|
+
}
|
|
401
|
+
exports.bytesToCrockford = bytesToCrockford;
|
|
402
|
+
const encodeNewsletterMessage = (message) => {
|
|
403
|
+
return WAProto_1.proto.Message.encode(message).finish()
|
|
404
|
+
}
|
|
405
|
+
exports.encodeNewsletterMessage = encodeNewsletterMessage;
|
|
@@ -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,96 @@
|
|
|
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({
|
|
37
|
+
id: chat.id,
|
|
38
|
+
name: chat.name || undefined,
|
|
39
|
+
lid: chat.lidJid || undefined,
|
|
40
|
+
jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
|
|
41
|
+
});
|
|
42
|
+
const msgs = chat.messages || [];
|
|
43
|
+
delete chat.messages;
|
|
44
|
+
delete chat.archived;
|
|
45
|
+
delete chat.muteEndTime;
|
|
46
|
+
delete chat.pinned;
|
|
47
|
+
for (const item of msgs) {
|
|
48
|
+
const message = item.message;
|
|
49
|
+
messages.push(message);
|
|
50
|
+
if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
|
|
51
|
+
// keep only the most recent message in the chat array
|
|
52
|
+
chat.messages = [{ message }];
|
|
53
|
+
}
|
|
54
|
+
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
|
55
|
+
chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
|
|
56
|
+
}
|
|
57
|
+
if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
|
|
58
|
+
|| message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
|
|
59
|
+
&& ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
|
|
60
|
+
contacts.push({
|
|
61
|
+
id: message.key.participant || message.key.remoteJid,
|
|
62
|
+
verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
|
|
67
|
+
delete chat.readOnly;
|
|
68
|
+
}
|
|
69
|
+
chats.push({ ...chat });
|
|
70
|
+
}
|
|
71
|
+
break;
|
|
72
|
+
case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
73
|
+
for (const c of item.pushnames) {
|
|
74
|
+
contacts.push({ id: c.id, notify: c.pushname });
|
|
75
|
+
}
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
chats,
|
|
80
|
+
contacts,
|
|
81
|
+
messages,
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
exports.processHistoryMessage = processHistoryMessage;
|
|
85
|
+
const downloadAndProcessHistorySyncNotification = async (msg, options) => {
|
|
86
|
+
const historyMsg = await (0, exports.downloadHistory)(msg, options);
|
|
87
|
+
return (0, exports.processHistoryMessage)(historyMsg);
|
|
88
|
+
};
|
|
89
|
+
exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
|
|
90
|
+
const getHistoryMsg = (message) => {
|
|
91
|
+
var _a;
|
|
92
|
+
const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
|
|
93
|
+
const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
|
|
94
|
+
return anyHistoryMsg;
|
|
95
|
+
};
|
|
96
|
+
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 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,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getUrlInfo = void 0;
|
|
4
|
+
const messages_1 = require("./messages");
|
|
5
|
+
const messages_media_1 = require("./messages-media");
|
|
6
|
+
const THUMBNAIL_WIDTH_PX = 192;
|
|
7
|
+
/** Fetches an image and generates a thumbnail for it */
|
|
8
|
+
const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
|
|
9
|
+
const stream = await (0, messages_media_1.getHttpStream)(url, fetchOpts);
|
|
10
|
+
const result = await (0, messages_media_1.extractImageThumb)(stream, thumbnailWidth);
|
|
11
|
+
return result;
|
|
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
|
+
const getUrlInfo = async (text, opts = {
|
|
20
|
+
thumbnailWidth: THUMBNAIL_WIDTH_PX,
|
|
21
|
+
fetchOpts: { timeout: 3000 }
|
|
22
|
+
}) => {
|
|
23
|
+
var _a;
|
|
24
|
+
try {
|
|
25
|
+
// retries
|
|
26
|
+
const retries = 0;
|
|
27
|
+
const maxRetry = 5;
|
|
28
|
+
const { getLinkPreview } = await import('link-preview-js');
|
|
29
|
+
let previewLink = text;
|
|
30
|
+
if (!text.startsWith('https://') && !text.startsWith('http://')) {
|
|
31
|
+
previewLink = 'https://' + previewLink;
|
|
32
|
+
}
|
|
33
|
+
const info = await getLinkPreview(previewLink, {
|
|
34
|
+
...opts.fetchOpts,
|
|
35
|
+
followRedirects: 'follow',
|
|
36
|
+
handleRedirects: (baseURL, forwardedURL) => {
|
|
37
|
+
const urlObj = new URL(baseURL);
|
|
38
|
+
const forwardedURLObj = new URL(forwardedURL);
|
|
39
|
+
if (retries >= maxRetry) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
if (forwardedURLObj.hostname === urlObj.hostname
|
|
43
|
+
|| forwardedURLObj.hostname === 'www.' + urlObj.hostname
|
|
44
|
+
|| 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
|
|
45
|
+
retries + 1;
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
headers: opts.fetchOpts
|
|
53
|
+
});
|
|
54
|
+
if (info && 'title' in info && info.title) {
|
|
55
|
+
const [image] = info.images;
|
|
56
|
+
const urlInfo = {
|
|
57
|
+
'canonical-url': info.url,
|
|
58
|
+
'matched-text': text,
|
|
59
|
+
title: info.title,
|
|
60
|
+
description: info.description,
|
|
61
|
+
originalThumbnailUrl: image
|
|
62
|
+
};
|
|
63
|
+
if (opts.uploadImage) {
|
|
64
|
+
const { imageMessage } = await (0, messages_1.prepareWAMessageMedia)({ image: { url: image } }, {
|
|
65
|
+
upload: opts.uploadImage,
|
|
66
|
+
mediaTypeOverride: 'thumbnail-link',
|
|
67
|
+
options: opts.fetchOpts
|
|
68
|
+
});
|
|
69
|
+
urlInfo.jpegThumbnail = (imageMessage === null || imageMessage === void 0 ? void 0 : imageMessage.jpegThumbnail)
|
|
70
|
+
? Buffer.from(imageMessage.jpegThumbnail)
|
|
71
|
+
: undefined;
|
|
72
|
+
urlInfo.highQualityThumbnail = imageMessage || undefined;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
try {
|
|
76
|
+
urlInfo.jpegThumbnail = image
|
|
77
|
+
? (await getCompressedJpegThumbnail(image, opts)).buffer
|
|
78
|
+
: undefined;
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
(_a = opts.logger) === null || _a === void 0 ? void 0 : _a.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return urlInfo;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (!error.message.includes('receive a valid')) {
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
exports.getUrlInfo = getUrlInfo;
|