@oxidezap/baileyrs 0.3.7 → 0.3.8
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/README.md +48 -8
- package/lib/Bridge/history-sync-wire.d.ts +2 -2
- package/lib/Bridge/history-sync-wire.js +4 -4
- package/lib/Bridge/schema.js +7 -1
- package/lib/Bridge/types.d.ts +7 -1
- package/lib/Compatibility/auth-state.d.ts +30 -0
- package/lib/Compatibility/auth-state.js +96 -0
- package/lib/Compatibility/encode-proto-core.d.ts +31 -0
- package/lib/Compatibility/encode-proto-core.js +51 -0
- package/lib/Compatibility/encode-proto.d.ts +0 -29
- package/lib/Compatibility/encode-proto.js +3 -50
- package/lib/Compatibility/host-auth-state.d.ts +6 -0
- package/lib/Compatibility/host-auth-state.js +162 -0
- package/lib/Compatibility/internal/auth-state.d.ts +3 -7
- package/lib/Compatibility/internal/auth-state.js +34 -1
- package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
- package/lib/Compatibility/internal/host-auth-state.js +14 -0
- package/lib/Compatibility/legacy-store/device.js +5 -5
- package/lib/Compatibility/message-ids.d.ts +17 -0
- package/lib/Compatibility/message-ids.js +47 -0
- package/lib/Compatibility/message-relay.d.ts +2 -2
- package/lib/Compatibility/message-relay.js +4 -4
- package/lib/Compatibility/proto-runtime.js +33 -11
- package/lib/Compatibility/socket-results.d.ts +1 -1
- package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
- package/lib/Compatibility/tagged-message-waiter.js +5 -5
- package/lib/Compatibility/usync/adapter.d.ts +1 -1
- package/lib/Compatibility/websocket-client.d.ts +11 -3
- package/lib/Compatibility/websocket-client.js +84 -11
- package/lib/Defaults/index.d.ts +8 -8
- package/lib/Defaults/index.js +8 -8
- package/lib/Media/content.d.ts +28 -0
- package/lib/Media/content.js +129 -0
- package/lib/Media/core.d.ts +34 -0
- package/lib/Media/core.js +120 -0
- package/lib/Media/mutations.d.ts +24 -0
- package/lib/Media/mutations.js +38 -0
- package/lib/Runtime/aes-gcm.d.ts +4 -0
- package/lib/Runtime/aes-gcm.js +11 -0
- package/lib/Runtime/bridge.d.ts +44 -0
- package/lib/Runtime/bridge.js +76 -0
- package/lib/Runtime/buffer.d.ts +9 -0
- package/lib/Runtime/buffer.js +22 -0
- package/lib/Runtime/bytes.d.ts +61 -0
- package/lib/Runtime/bytes.js +270 -0
- package/lib/Runtime/host.d.ts +22 -0
- package/lib/Runtime/host.js +43 -0
- package/lib/Runtime/long.d.ts +33 -0
- package/lib/Runtime/long.js +64 -0
- package/lib/Runtime/node-media-processors.d.ts +4 -0
- package/lib/Runtime/node-media-processors.js +29 -0
- package/lib/Runtime/node-media.d.ts +28 -0
- package/lib/Runtime/node-media.js +115 -0
- package/lib/Runtime/node.d.ts +14 -0
- package/lib/Runtime/node.js +81 -0
- package/lib/Runtime/paths.d.ts +4 -0
- package/lib/Runtime/paths.js +7 -0
- package/lib/Runtime/stream.d.ts +11 -0
- package/lib/Runtime/stream.js +25 -0
- package/lib/Runtime/types.d.ts +98 -0
- package/lib/Runtime/types.js +13 -0
- package/lib/Socket/core.d.ts +312 -0
- package/lib/Socket/core.js +1122 -0
- package/lib/Socket/events-core.d.ts +75 -0
- package/lib/Socket/events-core.js +1058 -0
- package/lib/Socket/events.d.ts +1 -63
- package/lib/Socket/events.js +4 -1047
- package/lib/Socket/groups.js +4 -3
- package/lib/Socket/index.d.ts +521 -103
- package/lib/Socket/index.js +10 -1007
- package/lib/Socket/messages-core.d.ts +41 -0
- package/lib/Socket/messages-core.js +270 -0
- package/lib/Socket/messages.d.ts +9 -36
- package/lib/Socket/messages.js +3 -260
- package/lib/Socket/newsletter.js +3 -3
- package/lib/Socket/profile.js +1 -1
- package/lib/Socket/terminal-close-reporter.d.ts +2 -0
- package/lib/Socket/terminal-close-reporter.js +3 -3
- package/lib/Socket/transport.d.ts +2 -0
- package/lib/Socket/transport.js +16 -1
- package/lib/Socket/types.d.ts +2 -0
- package/lib/Types/Auth.d.ts +11 -0
- package/lib/Types/Message.d.ts +1 -1
- package/lib/Types/Socket.d.ts +2 -2
- package/lib/Types/index.d.ts +6 -1
- package/lib/Utils/browser-utils.d.ts +4 -0
- package/lib/Utils/browser-utils.js +53 -2
- package/lib/Utils/crypto.d.ts +1 -0
- package/lib/Utils/crypto.js +1 -0
- package/lib/Utils/event-buffer.d.ts +6 -1
- package/lib/Utils/event-buffer.js +28 -27
- package/lib/Utils/link-preview.d.ts +4 -3
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.js +35 -6
- package/lib/Utils/messages-core.d.ts +174 -0
- package/lib/Utils/messages-core.js +1042 -0
- package/lib/Utils/messages-media-core.d.ts +73 -0
- package/lib/Utils/messages-media-core.js +319 -0
- package/lib/Utils/messages-media.d.ts +1 -72
- package/lib/Utils/messages-media.js +9 -358
- package/lib/Utils/messages.d.ts +1 -166
- package/lib/Utils/messages.js +7 -1040
- package/lib/Utils/optional-peer.js +14 -5
- package/lib/Utils/process-history-message-core.d.ts +36 -0
- package/lib/Utils/process-history-message-core.js +187 -0
- package/lib/Utils/process-history-message.d.ts +5 -43
- package/lib/Utils/process-history-message.js +11 -197
- package/lib/Utils/process-message-core.d.ts +29 -0
- package/lib/Utils/process-message-core.js +112 -0
- package/lib/Utils/process-message.d.ts +4 -24
- package/lib/Utils/process-message.js +6 -111
- package/lib/WABinary/generic-utils.js +7 -5
- package/lib/host-shared.d.ts +74 -0
- package/lib/host-shared.js +15 -0
- package/lib/host-socket-operations.d.ts +3 -0
- package/lib/host-socket-operations.js +2 -0
- package/lib/host-surface.d.ts +21 -0
- package/lib/host-surface.js +35 -0
- package/lib/host-types.d.ts +356 -0
- package/lib/host-types.js +2 -0
- package/lib/host.d.ts +33 -0
- package/lib/host.js +31 -0
- package/lib/node-surface.d.ts +9 -0
- package/lib/node-surface.js +15 -0
- package/lib/surface.d.ts +5 -0
- package/lib/surface.js +6 -0
- package/lib/wasm.d.ts +27 -0
- package/lib/wasm.js +27 -0
- package/package.json +18 -6
|
@@ -1,361 +1,12 @@
|
|
|
1
|
-
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
-
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
-
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
-
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
-
});
|
|
6
|
-
}
|
|
7
|
-
return path;
|
|
8
|
-
};
|
|
9
|
-
import { Buffer } from 'node:buffer';
|
|
10
|
-
import { execFile } from 'node:child_process';
|
|
11
|
-
import { randomBytes } from 'node:crypto';
|
|
12
|
-
import { createReadStream, promises as fs } from 'node:fs';
|
|
13
|
-
import { tmpdir } from 'node:os';
|
|
14
|
-
import { join } from 'node:path';
|
|
15
|
-
import { Readable } from 'node:stream';
|
|
16
|
-
import { MEDIA_HKDF_KEY_MAPPING } from '../Defaults/index.js';
|
|
17
|
-
import { proto } from '../WAProto/runtime.js';
|
|
18
|
-
import { getBinaryNodeChild, getBinaryNodeChildBuffer } from '../WABinary/generic-utils.js';
|
|
19
|
-
import { jidNormalizedUser } from '../WABinary/jid-utils.js';
|
|
20
|
-
import { Boom } from './boom.js';
|
|
21
|
-
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
|
|
22
|
-
const randomId = () => globalThis.crypto.randomUUID();
|
|
23
|
-
const getTmpFilesDirectory = () => tmpdir();
|
|
24
|
-
const getImageProcessingLibrary = async () => {
|
|
25
|
-
//@ts-ignore
|
|
26
|
-
const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
|
|
27
|
-
if (sharp) {
|
|
28
|
-
return { sharp };
|
|
29
|
-
}
|
|
30
|
-
if (jimp) {
|
|
31
|
-
return { jimp };
|
|
32
|
-
}
|
|
33
|
-
throw new Boom('No image processing library available');
|
|
34
|
-
};
|
|
35
|
-
export const hkdfInfoKey = (type) => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`;
|
|
36
|
-
export async function getMediaKeys(buffer, mediaType) {
|
|
37
|
-
if (!buffer)
|
|
38
|
-
throw new Boom('Cannot derive from empty media key');
|
|
39
|
-
if (typeof buffer === 'string')
|
|
40
|
-
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
|
41
|
-
const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
|
|
42
|
-
return {
|
|
43
|
-
iv: expandedMediaKey.slice(0, 16),
|
|
44
|
-
cipherKey: expandedMediaKey.slice(16, 48),
|
|
45
|
-
macKey: expandedMediaKey.slice(48, 80)
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
/** Extracts video thumb using FFMPEG */
|
|
49
|
-
const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
|
|
50
|
-
execFile('ffmpeg', ['-ss', time, '-i', path, '-y', '-vf', `scale=${size.width}:-1`, '-vframes', '1', '-f', 'image2', destPath], err => {
|
|
51
|
-
if (err) {
|
|
52
|
-
reject(err);
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
resolve();
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
|
60
|
-
// TODO: Move entirely to sharp, removing jimp as it supports readable streams
|
|
61
|
-
// This will have positive speed and performance impacts as well as minimizing RAM usage.
|
|
62
|
-
if (bufferOrFilePath instanceof Readable) {
|
|
63
|
-
bufferOrFilePath = await toBuffer(bufferOrFilePath);
|
|
64
|
-
}
|
|
65
|
-
const lib = await getImageProcessingLibrary();
|
|
66
|
-
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
67
|
-
const img = lib.sharp.default(bufferOrFilePath);
|
|
68
|
-
const dimensions = await img.metadata();
|
|
69
|
-
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
|
|
70
|
-
return {
|
|
71
|
-
buffer,
|
|
72
|
-
original: {
|
|
73
|
-
width: dimensions.width,
|
|
74
|
-
height: dimensions.height
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
|
|
79
|
-
const JimpClass = lib.jimp.Jimp;
|
|
80
|
-
const jimp = await JimpClass.read(bufferOrFilePath);
|
|
81
|
-
const dimensions = {
|
|
82
|
-
width: jimp.width,
|
|
83
|
-
height: jimp.height
|
|
84
|
-
};
|
|
85
|
-
const buffer = await jimp
|
|
86
|
-
.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
|
|
87
|
-
.getBuffer('image/jpeg', { quality: 50 });
|
|
88
|
-
return {
|
|
89
|
-
buffer,
|
|
90
|
-
original: dimensions
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
throw new Boom('No image processing library available');
|
|
95
|
-
}
|
|
96
|
-
};
|
|
97
|
-
export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''));
|
|
98
|
-
export const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
99
|
-
const buffer = Buffer.isBuffer(mediaUpload) ? mediaUpload : await toBuffer((await getStream(mediaUpload)).stream);
|
|
100
|
-
const { width = 640, height = 640 } = dimensions || {};
|
|
101
|
-
const lib = await getImageProcessingLibrary();
|
|
102
|
-
if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
|
|
103
|
-
return { img: await lib.sharp.default(buffer).resize(width, height).jpeg({ quality: 50 }).toBuffer() };
|
|
104
|
-
}
|
|
105
|
-
if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
|
|
106
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
107
|
-
const jimp = await lib.jimp.Jimp.read(buffer);
|
|
108
|
-
const min = Math.min(jimp.width, jimp.height);
|
|
109
|
-
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
|
|
110
|
-
return {
|
|
111
|
-
img: await cropped
|
|
112
|
-
.resize({ w: width, h: height, mode: lib.jimp.ResizeStrategy.BILINEAR })
|
|
113
|
-
.getBuffer('image/jpeg', { quality: 50 })
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
throw new Boom('No image processing library available');
|
|
117
|
-
};
|
|
118
|
-
export const mediaMessageSHA256B64 = (message) => {
|
|
119
|
-
const media = Object.values(message)[0];
|
|
120
|
-
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
|
|
121
|
-
};
|
|
122
|
-
/** Returns audio duration in seconds, parsed via `music-metadata`. */
|
|
123
|
-
export async function getAudioDuration(buffer) {
|
|
124
|
-
// `music-metadata` is an optional peer: without it the duration is simply
|
|
125
|
-
// unknown and the caller sends without `seconds`. The specifier cast keeps
|
|
126
|
-
// bundlers from failing the build when the peer is absent, the same trick
|
|
127
|
-
// `link-preview.ts` uses for `link-preview-js`. Only the import is
|
|
128
|
-
// guarded: parser failures still throw so the caller's warning reports
|
|
129
|
-
// corrupt audio instead of silently dropping the duration.
|
|
130
|
-
let musicMetadata;
|
|
131
|
-
try {
|
|
132
|
-
musicMetadata = await import(__rewriteRelativeImportExtension('music-metadata'));
|
|
133
|
-
}
|
|
134
|
-
catch {
|
|
135
|
-
return undefined;
|
|
136
|
-
}
|
|
137
|
-
let metadata;
|
|
138
|
-
const options = {
|
|
139
|
-
duration: true
|
|
140
|
-
};
|
|
141
|
-
if (Buffer.isBuffer(buffer)) {
|
|
142
|
-
metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
|
|
143
|
-
}
|
|
144
|
-
else if (typeof buffer === 'string') {
|
|
145
|
-
metadata = await musicMetadata.parseFile(buffer, options);
|
|
146
|
-
}
|
|
147
|
-
else {
|
|
148
|
-
metadata = await musicMetadata.parseStream(buffer, undefined, options);
|
|
149
|
-
}
|
|
150
|
-
return metadata.format.duration;
|
|
151
|
-
}
|
|
152
1
|
/**
|
|
153
|
-
|
|
2
|
+
* Node compatibility wrapper for the historical deep import.
|
|
3
|
+
*
|
|
4
|
+
* Importing this path has always made filesystem, stream, optional processor,
|
|
5
|
+
* and Buffer-backed media behavior available without requiring the package
|
|
6
|
+
* root to be imported first. Host socket internals import the portable core
|
|
7
|
+
* directly and therefore never enter this Node initializer.
|
|
154
8
|
*/
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const { default: decoder } = await import('audio-decode');
|
|
159
|
-
let audioData;
|
|
160
|
-
if (Buffer.isBuffer(buffer)) {
|
|
161
|
-
audioData = buffer;
|
|
162
|
-
}
|
|
163
|
-
else if (typeof buffer === 'string') {
|
|
164
|
-
const rStream = createReadStream(buffer);
|
|
165
|
-
audioData = await toBuffer(rStream);
|
|
166
|
-
}
|
|
167
|
-
else {
|
|
168
|
-
audioData = await toBuffer(buffer);
|
|
169
|
-
}
|
|
170
|
-
const audioBuffer = await decoder(audioData);
|
|
171
|
-
const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
|
|
172
|
-
const samples = 64; // Number of samples we want to have in our final data set
|
|
173
|
-
const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
|
|
174
|
-
const filteredData = [];
|
|
175
|
-
for (let i = 0; i < samples; i++) {
|
|
176
|
-
const blockStart = blockSize * i; // the location of the first sample in the block
|
|
177
|
-
let sum = 0;
|
|
178
|
-
for (let j = 0; j < blockSize; j++) {
|
|
179
|
-
sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
|
|
180
|
-
}
|
|
181
|
-
filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
|
|
182
|
-
}
|
|
183
|
-
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
|
184
|
-
const multiplier = Math.pow(Math.max(...filteredData), -1);
|
|
185
|
-
const normalizedData = filteredData.map(n => n * multiplier);
|
|
186
|
-
// Generate waveform like WhatsApp
|
|
187
|
-
const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
|
|
188
|
-
return waveform;
|
|
189
|
-
}
|
|
190
|
-
catch (e) {
|
|
191
|
-
logger?.debug('Failed to generate waveform: ' + e);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
export const toReadable = (buffer) => {
|
|
195
|
-
const readable = new Readable({ read: () => { } });
|
|
196
|
-
readable.push(buffer);
|
|
197
|
-
readable.push(null);
|
|
198
|
-
return readable;
|
|
199
|
-
};
|
|
200
|
-
export const toBuffer = async (stream) => {
|
|
201
|
-
const chunks = [];
|
|
202
|
-
for await (const chunk of stream) {
|
|
203
|
-
chunks.push(chunk);
|
|
204
|
-
}
|
|
205
|
-
stream.destroy();
|
|
206
|
-
return Buffer.concat(chunks);
|
|
207
|
-
};
|
|
208
|
-
export const getStream = async (item, opts) => {
|
|
209
|
-
if (Buffer.isBuffer(item)) {
|
|
210
|
-
return { stream: toReadable(item), type: 'buffer' };
|
|
211
|
-
}
|
|
212
|
-
if ('stream' in item) {
|
|
213
|
-
return { stream: item.stream, type: 'readable' };
|
|
214
|
-
}
|
|
215
|
-
const urlStr = item.url.toString();
|
|
216
|
-
if (urlStr.startsWith('data:')) {
|
|
217
|
-
const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
|
|
218
|
-
return { stream: toReadable(buffer), type: 'buffer' };
|
|
219
|
-
}
|
|
220
|
-
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
|
|
221
|
-
return { stream: await getHttpStream(item.url, opts), type: 'remote' };
|
|
222
|
-
}
|
|
223
|
-
return { stream: createReadStream(item.url), type: 'file' };
|
|
224
|
-
};
|
|
225
|
-
/** generates a thumbnail for a given media, if required */
|
|
226
|
-
export async function generateThumbnail(bufferOrPath, mediaType, options) {
|
|
227
|
-
let thumbnail;
|
|
228
|
-
let originalImageDimensions;
|
|
229
|
-
if (mediaType === 'image') {
|
|
230
|
-
const { buffer, original } = await extractImageThumb(bufferOrPath);
|
|
231
|
-
thumbnail = buffer.toString('base64');
|
|
232
|
-
if (original.width && original.height) {
|
|
233
|
-
originalImageDimensions = {
|
|
234
|
-
width: original.width,
|
|
235
|
-
height: original.height
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
else if (mediaType === 'video') {
|
|
240
|
-
// Video thumbnails need ffmpeg + file on disk
|
|
241
|
-
let filePath;
|
|
242
|
-
let needsCleanup = false;
|
|
243
|
-
if (Buffer.isBuffer(bufferOrPath)) {
|
|
244
|
-
filePath = join(getTmpFilesDirectory(), 'vid-' + randomId());
|
|
245
|
-
await fs.writeFile(filePath, bufferOrPath);
|
|
246
|
-
needsCleanup = true;
|
|
247
|
-
}
|
|
248
|
-
else {
|
|
249
|
-
filePath = bufferOrPath;
|
|
250
|
-
}
|
|
251
|
-
const imgFilename = join(getTmpFilesDirectory(), randomId() + '.jpg');
|
|
252
|
-
try {
|
|
253
|
-
await extractVideoThumb(filePath, imgFilename, '00:00:00', { width: 32, height: 32 });
|
|
254
|
-
const buff = await fs.readFile(imgFilename);
|
|
255
|
-
thumbnail = buff.toString('base64');
|
|
256
|
-
await fs.unlink(imgFilename);
|
|
257
|
-
}
|
|
258
|
-
catch (err) {
|
|
259
|
-
options.logger?.debug('could not generate video thumb: ' + err);
|
|
260
|
-
}
|
|
261
|
-
if (needsCleanup) {
|
|
262
|
-
try {
|
|
263
|
-
await fs.unlink(filePath);
|
|
264
|
-
}
|
|
265
|
-
catch {
|
|
266
|
-
/* ignore */
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
return {
|
|
271
|
-
thumbnail,
|
|
272
|
-
originalImageDimensions
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
export const getHttpStream = async (url, options = {}) => {
|
|
276
|
-
const response = await fetch(url.toString(), {
|
|
277
|
-
dispatcher: options.dispatcher,
|
|
278
|
-
method: 'GET',
|
|
279
|
-
headers: options.headers
|
|
280
|
-
});
|
|
281
|
-
if (!response.ok) {
|
|
282
|
-
throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
|
|
283
|
-
}
|
|
284
|
-
// @ts-ignore Node18+ Readable.fromWeb exists
|
|
285
|
-
return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
|
|
286
|
-
};
|
|
287
|
-
export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
|
|
288
|
-
export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
|
|
289
|
-
export function extensionForMediaMessage(message) {
|
|
290
|
-
const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
|
|
291
|
-
const type = Object.keys(message)[0];
|
|
292
|
-
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage')
|
|
293
|
-
return '.jpeg';
|
|
294
|
-
return getExtension(message[type].mimetype);
|
|
295
|
-
}
|
|
296
|
-
const getMediaRetryKey = (mediaKey) => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
|
|
297
|
-
export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
298
|
-
const receiptBuffer = proto.ServerErrorReceipt.encode({ stanzaId: key.id }).finish();
|
|
299
|
-
const iv = randomBytes(12);
|
|
300
|
-
const ciphertext = aesEncryptGCM(receiptBuffer, getMediaRetryKey(mediaKey), iv, Buffer.from(key.id));
|
|
301
|
-
return {
|
|
302
|
-
tag: 'receipt',
|
|
303
|
-
attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' },
|
|
304
|
-
content: [
|
|
305
|
-
{
|
|
306
|
-
tag: 'encrypt',
|
|
307
|
-
attrs: {},
|
|
308
|
-
content: [
|
|
309
|
-
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
310
|
-
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
311
|
-
]
|
|
312
|
-
},
|
|
313
|
-
{
|
|
314
|
-
tag: 'rmr',
|
|
315
|
-
attrs: {
|
|
316
|
-
jid: key.remoteJid,
|
|
317
|
-
from_me: (!!key.fromMe).toString(),
|
|
318
|
-
...(key.participant ? { participant: key.participant } : {})
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
]
|
|
322
|
-
};
|
|
323
|
-
};
|
|
324
|
-
const MEDIA_RETRY_STATUS_MAP = {
|
|
325
|
-
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
326
|
-
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
327
|
-
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
328
|
-
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
329
|
-
};
|
|
330
|
-
export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
|
|
331
|
-
export const decodeMediaRetryNode = (node) => {
|
|
332
|
-
const retryNode = getBinaryNodeChild(node, 'rmr');
|
|
333
|
-
const event = {
|
|
334
|
-
key: {
|
|
335
|
-
id: node.attrs.id,
|
|
336
|
-
remoteJid: retryNode.attrs.jid,
|
|
337
|
-
fromMe: retryNode.attrs.from_me === 'true',
|
|
338
|
-
participant: retryNode.attrs.participant
|
|
339
|
-
}
|
|
340
|
-
};
|
|
341
|
-
const errorNode = getBinaryNodeChild(node, 'error');
|
|
342
|
-
if (errorNode) {
|
|
343
|
-
const errorCode = +errorNode.attrs.code;
|
|
344
|
-
event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
|
|
345
|
-
data: errorNode.attrs,
|
|
346
|
-
statusCode: getStatusCodeForMediaRetry(errorCode)
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
else {
|
|
350
|
-
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
|
|
351
|
-
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
|
|
352
|
-
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
|
|
353
|
-
if (ciphertext && iv)
|
|
354
|
-
event.media = { ciphertext, iv };
|
|
355
|
-
else
|
|
356
|
-
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
|
|
357
|
-
}
|
|
358
|
-
return event;
|
|
359
|
-
};
|
|
360
|
-
export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => proto.MediaRetryNotification.decode(aesDecryptGCM(ciphertext, getMediaRetryKey(mediaKey), iv, Buffer.from(msgId)));
|
|
9
|
+
import { nodeRuntime as initializedNodeRuntime } from '../Runtime/node.js';
|
|
10
|
+
void initializedNodeRuntime;
|
|
11
|
+
export * from './messages-media-core.js';
|
|
361
12
|
//# sourceMappingURL=messages-media.js.map
|
package/lib/Utils/messages.d.ts
CHANGED
|
@@ -1,167 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { Readable } from 'node:stream';
|
|
3
|
-
import type { WasmWhatsAppClient } from '@oxidezap/whatsapp-rust-bridge';
|
|
4
|
-
import { type MediaType } from '../Defaults/index.js';
|
|
5
|
-
import type { AnyMediaMessageContent, AnyMessageContent, MessageContentGenerationOptions, MessageGenerationOptions, MessageGenerationOptionsFromContent, MessageUserReceipt, WAMessage, WAMessageContent, WAMessageKey } from '../Types/index.js';
|
|
6
|
-
import { WAProto } from '../Types/index.js';
|
|
7
|
-
import { proto } from '../WAProto/runtime.js';
|
|
8
|
-
import type { ILogger } from './logger.js';
|
|
9
|
-
import { type MediaDownloadOptions } from './messages-media.js';
|
|
10
|
-
type ExtractByKey<T, K extends PropertyKey> = T extends Record<K, unknown> ? T : never;
|
|
11
|
-
/**
|
|
12
|
-
* Uses a regex to test whether the string contains a URL, and returns the URL if it does.
|
|
13
|
-
* @param text eg. hello https://google.com
|
|
14
|
-
* @returns the URL, eg. https://google.com
|
|
15
|
-
*/
|
|
16
|
-
export declare const extractUrlFromText: (text: string) => string | undefined;
|
|
17
|
-
export declare const generateLinkPreviewIfRequired: (text: string, getUrlInfo: MessageGenerationOptions['getUrlInfo'], logger: MessageGenerationOptions['logger']) => Promise<import("../index.js").WAUrlInfo | undefined>;
|
|
18
|
-
export declare const prepareWAMessageMedia: (message: AnyMediaMessageContent, options: MessageContentGenerationOptions) => Promise<WAProto.Message>;
|
|
19
|
-
export declare const prepareDisappearingMessageSettingContent: (ephemeralExpiration?: number) => WAProto.Message;
|
|
20
|
-
/**
|
|
21
|
-
* Generate forwarded message content like WA does
|
|
22
|
-
* @param message the message to forward
|
|
23
|
-
* @param options.forceForward will show the message as forwarded even if it is from you
|
|
24
|
-
*/
|
|
25
|
-
export declare const generateForwardMessageContent: (message: WAMessage, forceForward?: boolean) => WAProto.IMessage;
|
|
26
|
-
export declare const hasNonNullishProperty: <K extends PropertyKey>(message: AnyMessageContent, key: K) => message is ExtractByKey<AnyMessageContent, K>;
|
|
27
|
-
export declare const generateWAMessageContent: (message: AnyMessageContent, options: MessageContentGenerationOptions) => Promise<WAProto.Message>;
|
|
28
|
-
export declare const generateWAMessageFromContent: (jid: string, message: WAMessageContent, options: MessageGenerationOptionsFromContent) => WAMessage;
|
|
29
|
-
export declare const generateWAMessage: (jid: string, content: AnyMessageContent, options: MessageGenerationOptions) => Promise<WAMessage>;
|
|
30
|
-
/** Get the key to access the true type of content */
|
|
31
|
-
export declare const getContentType: (content: proto.IMessage | undefined) => keyof WAProto.IMessage | undefined;
|
|
32
|
-
/**
|
|
33
|
-
* Normalizes ephemeral, view once messages to regular message content
|
|
34
|
-
* Eg. image messages in ephemeral messages, in view once messages etc.
|
|
35
|
-
* @param content
|
|
36
|
-
* @returns
|
|
37
|
-
*/
|
|
38
|
-
export declare const normalizeMessageContent: (content: WAMessageContent | null | undefined) => WAMessageContent | undefined;
|
|
39
|
-
/**
|
|
40
|
-
* Extract the true message content from a message
|
|
41
|
-
* Eg. extracts the inner message from a disappearing message/view once message
|
|
42
|
-
*/
|
|
43
|
-
export declare const extractMessageContent: (content: WAMessageContent | undefined | null) => WAMessageContent | undefined;
|
|
44
|
-
/**
|
|
45
|
-
* Every field is optional, so upstream's `{ reuploadRequest, logger }` and this
|
|
46
|
-
* package's `{ waClient }` are both accepted.
|
|
47
|
-
*
|
|
48
|
-
* `reuploadRequest` and `logger` are declared for that compatibility and are
|
|
49
|
-
* not read: the engine handles the re-upload request, the CDN failover and the
|
|
50
|
-
* logging itself, so a caller's versions would have nothing to do.
|
|
51
|
-
*/
|
|
52
|
-
export type DownloadMediaMessageContext = {
|
|
53
|
-
reuploadRequest?: (msg: WAMessage) => Promise<WAMessage>;
|
|
54
|
-
logger?: ILogger;
|
|
55
|
-
/** Bridge client for media download. Falls back to the registered one. */
|
|
56
|
-
waClient?: Pick<WasmWhatsAppClient, 'downloadMedia' | 'downloadMediaStream'>;
|
|
57
|
-
};
|
|
58
|
-
export declare const MEDIA_DOWNLOAD_TYPES: readonly ['buffer', 'stream'];
|
|
59
|
-
export type MediaDownloadType = (typeof MEDIA_DOWNLOAD_TYPES)[number];
|
|
60
|
-
/**
|
|
61
|
-
* Downloads the given message. Throws an error if it's not a media message.
|
|
62
|
-
*
|
|
63
|
-
* Uses the Rust bridge for download — provides CDN failover, automatic auth
|
|
64
|
-
* refresh on 401/404, HMAC-SHA256 integrity verification, and AES-256-CBC
|
|
65
|
-
* decryption, so a bridge client has to reach it.
|
|
66
|
-
*
|
|
67
|
-
* `ctx` is optional, as upstream has it: without one the client registered by
|
|
68
|
-
* the most recent `makeWASocket` is used, the same fallback
|
|
69
|
-
* `downloadContentFromMessage` offers for standalone calls. A host juggling
|
|
70
|
-
* several sockets should pass `ctx` explicitly, because the registration points
|
|
71
|
-
* at whichever client was created last.
|
|
72
|
-
*/
|
|
73
|
-
export declare const downloadMediaMessage: <Type extends MediaDownloadType>(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer<ArrayBufferLike> : Readable>;
|
|
74
|
-
export declare const _registerActiveBridgeClient: (client: WasmWhatsAppClient, logger?: ILogger) => void;
|
|
75
|
-
/**
|
|
76
|
-
* Drop the module-level pointer when `sock.end()` frees the client it points
|
|
77
|
-
* at. Without this the global keeps a strong reference to a freed
|
|
78
|
-
* `WasmWhatsAppClient`, so the next standalone `downloadContentFromMessage()`
|
|
79
|
-
* call reaches into a null wasm pointer and fails with an opaque
|
|
80
|
-
* wasm-bindgen error instead of the actionable "no bridge client" Boom.
|
|
81
|
-
*
|
|
82
|
-
* Identity-checked on purpose: a multi-account host that ends socket A after
|
|
83
|
-
* creating socket B must not clear B's registration.
|
|
84
|
-
*/
|
|
85
|
-
export declare const _unregisterActiveBridgeClient: (client: WasmWhatsAppClient) => void;
|
|
86
|
-
/**
|
|
87
|
-
* Upstream-Baileys-compatible standalone media download. Builds a synthetic
|
|
88
|
-
* `WAMessage` from the supplied media subcontent (image/video/audio/etc fields)
|
|
89
|
-
* and routes it through {@link downloadMediaMessage}, so CDN failover, auth
|
|
90
|
-
* refresh, HMAC verification, and AES-256-CBC decryption all happen inside the
|
|
91
|
-
* Rust bridge — same code path as `sock.downloadMedia`.
|
|
92
|
-
*
|
|
93
|
-
* The bridge client is required. Pass it explicitly via `opts.client` for
|
|
94
|
-
* multi-account hosts; otherwise the helper falls back to the most-recently
|
|
95
|
-
* created bridge client (registered automatically by `makeWASocket`).
|
|
96
|
-
*/
|
|
97
|
-
export declare const downloadContentFromMessage: (mediaContent: {
|
|
98
|
-
directPath?: string | null;
|
|
99
|
-
mediaKey?: Uint8Array | null;
|
|
100
|
-
fileSha256?: Uint8Array | null;
|
|
101
|
-
fileEncSha256?: Uint8Array | null;
|
|
102
|
-
fileLength?: number | Long | null;
|
|
103
|
-
url?: string | null;
|
|
104
|
-
}, type: MediaType, opts?: MediaDownloadOptions & {
|
|
105
|
-
client?: WasmWhatsAppClient;
|
|
106
|
-
logger?: ILogger;
|
|
107
|
-
}) => Promise<Readable>;
|
|
108
|
-
type Long = {
|
|
109
|
-
low: number;
|
|
110
|
-
high: number;
|
|
111
|
-
unsigned: boolean;
|
|
112
|
-
};
|
|
113
|
-
type VoteAggregation = {
|
|
114
|
-
name: string;
|
|
115
|
-
voters: string[];
|
|
116
|
-
};
|
|
117
|
-
type ResponseAggregation = {
|
|
118
|
-
response: string;
|
|
119
|
-
responders: string[];
|
|
120
|
-
};
|
|
121
|
-
/** Infer the originating client family from WhatsApp's message-id format. */
|
|
122
|
-
export declare const getDevice: (id: string) => "android" | "desktop" | "ios" | "unknown" | "web";
|
|
123
|
-
/**
|
|
124
|
-
* Aggregate votes from a poll message.
|
|
125
|
-
*
|
|
126
|
-
* Takes a poll creation message and its accumulated poll updates (from
|
|
127
|
-
* `messages.update` events) and returns the vote tally per option.
|
|
128
|
-
*
|
|
129
|
-
* `pollUpdates` should contain pre-decrypted votes where `vote.selectedOptions`
|
|
130
|
-
* are the SHA-256 hashes of the voted option names.
|
|
131
|
-
*
|
|
132
|
-
* @example
|
|
133
|
-
* ```ts
|
|
134
|
-
* sock.ev.on('messages.update', event => {
|
|
135
|
-
* for (const { key, update } of event) {
|
|
136
|
-
* if (update.pollUpdates) {
|
|
137
|
-
* const pollMsg = await getMessageFromStore(key)
|
|
138
|
-
* const votes = getAggregateVotesInPollMessage({
|
|
139
|
-
* message: pollMsg.message,
|
|
140
|
-
* pollUpdates: pollMsg.pollUpdates
|
|
141
|
-
* })
|
|
142
|
-
* console.log(votes) // [{ name: 'Yes', voters: ['jid1'] }, ...]
|
|
143
|
-
* }
|
|
144
|
-
* }
|
|
145
|
-
* })
|
|
146
|
-
* ```
|
|
147
|
-
*/
|
|
148
|
-
export declare function getAggregateVotesInPollMessage({ message, pollUpdates }: Pick<WAMessage, 'pollUpdates' | 'message'>, meId?: string): VoteAggregation[];
|
|
149
|
-
export declare function getAggregateResponsesInEventMessage({ eventResponses }: Pick<WAMessage, 'eventResponses'>, meId?: string): ResponseAggregation[];
|
|
150
|
-
/** Group non-self message keys by chat and participant for bulk receipts. */
|
|
151
|
-
export declare const aggregateMessageKeysNotFromMe: (keys: WAMessageKey[]) => {
|
|
152
|
-
jid: string;
|
|
153
|
-
participant: string | undefined;
|
|
154
|
-
messageIds: string[];
|
|
155
|
-
}[];
|
|
156
|
-
/** Upsert one receipt into a message's `userReceipt` collection. */
|
|
157
|
-
export declare const updateMessageWithReceipt: (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => void;
|
|
158
|
-
/** Replace the previous reaction from the same author, then append the latest. */
|
|
159
|
-
export declare const updateMessageWithReaction: (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => void;
|
|
160
|
-
/** Replace the previous poll update from the same author. Empty votes remove it. */
|
|
161
|
-
export declare const updateMessageWithPollUpdate: (msg: Pick<WAMessage, 'pollUpdates'>, update: proto.IPollUpdate) => void;
|
|
162
|
-
/** Replace the previous event response from the same author. */
|
|
163
|
-
export declare const updateMessageWithEventResponse: (msg: Pick<WAMessage, 'eventResponses'>, update: proto.IEventResponse) => void;
|
|
164
|
-
/** Checks whether the message contains one of the upstream media payloads. */
|
|
165
|
-
export declare const assertMediaContent: (content: proto.IMessage | null | undefined) => WAProto.Message.IAudioMessage | WAProto.Message.IDocumentMessage | WAProto.Message.IImageMessage | WAProto.Message.IStickerMessage | WAProto.Message.IVideoMessage;
|
|
166
|
-
export {};
|
|
1
|
+
export * from './messages-core.js';
|
|
167
2
|
//# sourceMappingURL=messages.d.ts.map
|