nishiki-bail 1.1.21 → 1.1.22

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.
@@ -1,788 +1,896 @@
1
1
  import { Boom } from '@hapi/boom';
2
- import { exec } from 'child_process';
3
- import * as Crypto from 'crypto';
4
- import { once } from 'events';
5
- import { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs';
6
- import { tmpdir } from 'os';
7
- import { join } from 'path';
8
- import { Readable, Transform } from 'stream';
9
- import { URL } from 'url';
2
+ import { randomBytes } from 'crypto';
3
+ import { promises as fs } from 'fs';
4
+ import {} from 'stream';
10
5
  import { proto } from '../../WAProto/index.js';
11
- import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js';
12
- import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
13
- import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
14
- import { generateMessageIDV2 } from './generics.js';
15
- const getTmpFilesDirectory = () => tmpdir();
16
- const getImageProcessingLibrary = async () => {
17
- //@ts-ignore
18
- const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
19
- if (sharp) {
20
- return { sharp };
21
- }
22
- if (jimp) {
23
- return { jimp };
24
- }
25
- throw new Boom('No image processing library available');
6
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
+ import { WAMessageStatus, WAProto } from '../Types/index.js';
8
+ import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
+ import { sha256 } from './crypto.js';
10
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
12
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
13
+ const MIMETYPE_MAP = {
14
+ image: 'image/jpeg',
15
+ video: 'video/mp4',
16
+ document: 'application/pdf',
17
+ audio: 'audio/ogg; codecs=opus',
18
+ sticker: 'image/webp',
19
+ 'product-catalog-image': 'image/jpeg'
26
20
  };
27
- export const hkdfInfoKey = (type) => {
28
- const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
29
- return `WhatsApp ${hkdfInfo} Keys`;
21
+ const MessageTypeProto = {
22
+ image: WAProto.Message.ImageMessage,
23
+ video: WAProto.Message.VideoMessage,
24
+ audio: WAProto.Message.AudioMessage,
25
+ sticker: WAProto.Message.StickerMessage,
26
+ document: WAProto.Message.DocumentMessage
30
27
  };
31
- export const getRawMediaUploadData = async (media, mediaType, logger) => {
32
- const { stream } = await getStream(media);
33
- logger?.debug('got stream for raw upload');
34
- const hasher = Crypto.createHash('sha256');
35
- const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
36
- const fileWriteStream = createWriteStream(filePath);
37
- let fileLength = 0;
38
- try {
39
- for await (const data of stream) {
40
- fileLength += data.length;
41
- hasher.update(data);
42
- if (!fileWriteStream.write(data)) {
43
- await once(fileWriteStream, 'drain');
44
- }
45
- }
46
- fileWriteStream.end();
47
- await once(fileWriteStream, 'finish');
48
- stream.destroy();
49
- const fileSha256 = hasher.digest();
50
- logger?.debug('hashed data for raw upload');
51
- return {
52
- filePath: filePath,
53
- fileSha256,
54
- fileLength
55
- };
56
- }
57
- catch (error) {
58
- fileWriteStream.destroy();
59
- stream.destroy();
28
+ /**
29
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
30
+ * @param text eg. hello https://google.com
31
+ * @returns the URL, eg. https://google.com
32
+ */
33
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
34
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
35
+ const url = extractUrlFromText(text);
36
+ if (!!getUrlInfo && url) {
60
37
  try {
61
- await fs.unlink(filePath);
38
+ const urlInfo = await getUrlInfo(url);
39
+ return urlInfo;
62
40
  }
63
- catch {
64
- //
41
+ catch (error) {
42
+ // ignore if fails
43
+ logger?.warn({ trace: error.stack }, 'url generation failed');
65
44
  }
66
- throw error;
67
45
  }
68
46
  };
69
- /** generates all the keys required to encrypt/decrypt & sign a media message */
70
- export async function getMediaKeys(buffer, mediaType) {
71
- if (!buffer) {
72
- throw new Boom('Cannot derive from empty media key');
73
- }
74
- if (typeof buffer === 'string') {
75
- buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
76
- }
77
- // expand using HKDF to 112 bytes, also pass in the relevant app info
78
- const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
79
- return {
80
- iv: expandedMediaKey.slice(0, 16),
81
- cipherKey: expandedMediaKey.slice(16, 48),
82
- macKey: expandedMediaKey.slice(48, 80)
47
+ const assertColor = async (color) => {
48
+ let assertedColor;
49
+ if (typeof color === 'number') {
50
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
51
+ }
52
+ else {
53
+ let hex = color.trim().replace('#', '');
54
+ if (hex.length <= 6) {
55
+ hex = 'FF' + hex.padStart(6, '0');
56
+ }
57
+ assertedColor = parseInt(hex, 16);
58
+ return assertedColor;
59
+ }
60
+ };
61
+ export const prepareWAMessageMedia = async (message, options) => {
62
+ const logger = options.logger;
63
+ let mediaType;
64
+ for (const key of MEDIA_KEYS) {
65
+ if (key in message) {
66
+ mediaType = key;
67
+ }
68
+ }
69
+ if (!mediaType) {
70
+ throw new Boom('Invalid media type', { statusCode: 400 });
71
+ }
72
+ const uploadData = {
73
+ ...message,
74
+ media: message[mediaType]
83
75
  };
84
- }
85
- /** Extracts video thumb using FFMPEG */
86
- const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
87
- const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
88
- exec(cmd, err => {
89
- if (err) {
90
- reject(err);
76
+ delete uploadData[mediaType];
77
+ // check if cacheable + generate cache key
78
+ const cacheableKey = typeof uploadData.media === 'object' &&
79
+ 'url' in uploadData.media &&
80
+ !!uploadData.media.url &&
81
+ !!options.mediaCache &&
82
+ mediaType + ':' + uploadData.media.url.toString();
83
+ if (mediaType === 'document' && !uploadData.fileName) {
84
+ uploadData.fileName = 'file';
85
+ }
86
+ if (!uploadData.mimetype) {
87
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
88
+ }
89
+ if (cacheableKey) {
90
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
91
+ if (mediaBuff) {
92
+ logger?.debug({ cacheableKey }, 'got media cache hit');
93
+ const obj = proto.Message.decode(mediaBuff);
94
+ const key = `${mediaType}Message`;
95
+ Object.assign(obj[key], { ...uploadData, media: undefined });
96
+ return obj;
91
97
  }
92
- else {
93
- resolve();
98
+ }
99
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
100
+ if (isNewsletter) {
101
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
102
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
103
+ const fileSha256B64 = fileSha256.toString('base64');
104
+ const { mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
105
+ fileEncSha256B64: fileSha256B64,
106
+ mediaType: mediaType,
107
+ timeoutMs: options.mediaUploadTimeoutMs,
108
+ newsletter: isNewsletter
109
+ });
110
+ await fs.unlink(filePath);
111
+ const obj = WAProto.Message.fromObject({
112
+ // todo: add more support here
113
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
114
+ url: mediaUrl || directPath,
115
+ directPath,
116
+ fileSha256,
117
+ fileLength,
118
+ thumbnailDirectPath,
119
+ thumbnailSha256,
120
+ ...uploadData,
121
+ media: undefined
122
+ })
123
+ });
124
+ if (uploadData.ptv) {
125
+ obj.ptvMessage = obj.videoMessage;
126
+ delete obj.videoMessage;
127
+ }
128
+ if (obj.stickerMessage) {
129
+ obj.stickerMessage.stickerSentTs = Date.now();
94
130
  }
131
+ if (cacheableKey) {
132
+ logger?.debug({ cacheableKey }, 'set cache');
133
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
134
+ }
135
+ return obj;
136
+ }
137
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
138
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
139
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
140
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
141
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
142
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
143
+ logger,
144
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
145
+ opts: options.options
95
146
  });
96
- });
97
- export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
98
- // TODO: Move entirely to sharp, removing jimp as it supports readable streams
99
- // This will have positive speed and performance impacts as well as minimizing RAM usage.
100
- if (bufferOrFilePath instanceof Readable) {
101
- bufferOrFilePath = await toBuffer(bufferOrFilePath);
102
- }
103
- const lib = await getImageProcessingLibrary();
104
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
105
- const img = lib.sharp.default(bufferOrFilePath);
106
- const dimensions = await img.metadata();
107
- const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
108
- return {
109
- buffer,
110
- original: {
111
- width: dimensions.width,
112
- height: dimensions.height
147
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
148
+ const [{ mediaUrl, directPath }] = await Promise.all([
149
+ (async () => {
150
+ const result = await options.upload(encFilePath, {
151
+ fileEncSha256B64,
152
+ mediaType,
153
+ timeoutMs: options.mediaUploadTimeoutMs
154
+ });
155
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
156
+ return result;
157
+ })(),
158
+ (async () => {
159
+ try {
160
+ if (requiresThumbnailComputation) {
161
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
162
+ uploadData.jpegThumbnail = thumbnail;
163
+ if (!uploadData.width && originalImageDimensions) {
164
+ uploadData.width = originalImageDimensions.width;
165
+ uploadData.height = originalImageDimensions.height;
166
+ logger?.debug('set dimensions');
167
+ }
168
+ logger?.debug('generated thumbnail');
169
+ }
170
+ if (requiresDurationComputation) {
171
+ uploadData.seconds = await getAudioDuration(originalFilePath);
172
+ logger?.debug('computed audio duration');
173
+ }
174
+ if (requiresWaveformProcessing) {
175
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
176
+ logger?.debug('processed waveform');
177
+ }
178
+ if (requiresAudioBackground) {
179
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
180
+ logger?.debug('computed backgroundColor audio status');
181
+ }
113
182
  }
114
- };
115
- }
116
- else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
117
- const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
118
- const dimensions = {
119
- width: jimp.width,
120
- height: jimp.height
121
- };
122
- const buffer = await jimp
123
- .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
124
- .getBuffer('image/jpeg', { quality: 50 });
125
- return {
126
- buffer,
127
- original: dimensions
128
- };
183
+ catch (error) {
184
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
185
+ }
186
+ })()
187
+ ]).finally(async () => {
188
+ try {
189
+ await fs.unlink(encFilePath);
190
+ if (originalFilePath) {
191
+ await fs.unlink(originalFilePath);
192
+ }
193
+ logger?.debug('removed tmp files');
194
+ }
195
+ catch (error) {
196
+ logger?.warn('failed to remove tmp file');
197
+ }
198
+ });
199
+ const obj = WAProto.Message.fromObject({
200
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
201
+ url: mediaUrl,
202
+ directPath,
203
+ mediaKey,
204
+ fileEncSha256,
205
+ fileSha256,
206
+ fileLength,
207
+ mediaKeyTimestamp: unixTimestampSeconds(),
208
+ ...uploadData,
209
+ media: undefined
210
+ })
211
+ });
212
+ if (uploadData.ptv) {
213
+ obj.ptvMessage = obj.videoMessage;
214
+ delete obj.videoMessage;
129
215
  }
130
- else {
131
- throw new Boom('No image processing library available');
216
+ if (cacheableKey) {
217
+ logger?.debug({ cacheableKey }, 'set cache');
218
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
132
219
  }
220
+ return obj;
133
221
  };
134
- export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
135
- export const generateProfilePicture = async (mediaUpload, dimensions) => {
136
- let buffer;
137
- const { width: w = 640, height: h = 640 } = dimensions || {};
138
- if (Buffer.isBuffer(mediaUpload)) {
139
- buffer = mediaUpload;
140
- }
141
- else {
142
- // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
143
- const { stream } = await getStream(mediaUpload);
144
- // Convert the resulting stream to a buffer
145
- buffer = await toBuffer(stream);
146
- }
147
- const lib = await getImageProcessingLibrary();
148
- let img;
149
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
150
- img = lib.sharp
151
- .default(buffer)
152
- .resize(w, h)
153
- .jpeg({
154
- quality: 50
155
- })
156
- .toBuffer();
157
- }
158
- else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
159
- const jimp = await lib.jimp.Jimp.read(buffer);
160
- const min = Math.min(jimp.width, jimp.height);
161
- const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
162
- img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
222
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
223
+ ephemeralExpiration = ephemeralExpiration || 0;
224
+ const content = {
225
+ ephemeralMessage: {
226
+ message: {
227
+ protocolMessage: {
228
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
229
+ ephemeralExpiration
230
+ }
231
+ }
232
+ }
233
+ };
234
+ return WAProto.Message.fromObject(content);
235
+ };
236
+ /**
237
+ * Generate forwarded message content like WA does
238
+ * @param message the message to forward
239
+ * @param options.forceForward will show the message as forwarded even if it is from you
240
+ */
241
+ export const generateForwardMessageContent = (message, forceForward) => {
242
+ let content = message.message;
243
+ if (!content) {
244
+ throw new Boom('no content in message', { statusCode: 400 });
245
+ }
246
+ // hacky copy
247
+ content = normalizeMessageContent(content);
248
+ content = proto.Message.decode(proto.Message.encode(content).finish());
249
+ let key = Object.keys(content)[0];
250
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
251
+ score += message.key.fromMe && !forceForward ? 0 : 1;
252
+ if (key === 'conversation') {
253
+ content.extendedTextMessage = { text: content[key] };
254
+ delete content.conversation;
255
+ key = 'extendedTextMessage';
256
+ }
257
+ const key_ = content?.[key];
258
+ if (score > 0) {
259
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
163
260
  }
164
261
  else {
165
- throw new Boom('No image processing library available');
262
+ key_.contextInfo = {};
166
263
  }
167
- return {
168
- img: await img
169
- };
264
+ return content;
170
265
  };
171
- /** gets the SHA256 of the given media message */
172
- export const mediaMessageSHA256B64 = (message) => {
173
- const media = Object.values(message)[0];
174
- return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
266
+ export const hasNonNullishProperty = (message, key) => {
267
+ return (typeof message === 'object' &&
268
+ message !== null &&
269
+ key in message &&
270
+ message[key] !== null &&
271
+ message[key] !== undefined);
175
272
  };
176
- export async function getAudioDuration(buffer) {
177
- const musicMetadata = await import('music-metadata');
178
- let metadata;
179
- const options = {
180
- duration: true
181
- };
182
- if (Buffer.isBuffer(buffer)) {
183
- metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
273
+ function hasOptionalProperty(obj, key) {
274
+ return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
275
+ }
276
+ export const generateWAMessageContent = async (message, options) => {
277
+ var _a, _b;
278
+ let m = {};
279
+ if (hasNonNullishProperty(message, 'text')) {
280
+ const extContent = { text: message.text };
281
+ let urlInfo = message.linkPreview;
282
+ if (typeof urlInfo === 'undefined') {
283
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
284
+ }
285
+ if (urlInfo) {
286
+ extContent.matchedText = urlInfo['matched-text'];
287
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
288
+ extContent.description = urlInfo.description;
289
+ extContent.title = urlInfo.title;
290
+ extContent.previewType = 0;
291
+ const img = urlInfo.highQualityThumbnail;
292
+ if (img) {
293
+ extContent.thumbnailDirectPath = img.directPath;
294
+ extContent.mediaKey = img.mediaKey;
295
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
296
+ extContent.thumbnailWidth = img.width;
297
+ extContent.thumbnailHeight = img.height;
298
+ extContent.thumbnailSha256 = img.fileSha256;
299
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
300
+ }
301
+ }
302
+ if (options.backgroundColor) {
303
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
304
+ }
305
+ if (options.font) {
306
+ extContent.font = options.font;
307
+ }
308
+ m.extendedTextMessage = extContent;
184
309
  }
185
- else if (typeof buffer === 'string') {
186
- metadata = await musicMetadata.parseFile(buffer, options);
310
+ else if (hasNonNullishProperty(message, 'contacts')) {
311
+ const contactLen = message.contacts.contacts.length;
312
+ if (!contactLen) {
313
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
314
+ }
315
+ if (contactLen === 1) {
316
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
317
+ }
318
+ else {
319
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
320
+ }
187
321
  }
188
- else {
189
- metadata = await musicMetadata.parseStream(buffer, undefined, options);
322
+ else if (hasNonNullishProperty(message, 'location')) {
323
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
190
324
  }
191
- return metadata.format.duration;
192
- }
193
- /**
194
- referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
195
- */
196
- export async function getAudioWaveform(buffer, logger) {
197
- try {
198
- // @ts-ignore
199
- const { default: decoder } = await import('audio-decode');
200
- let audioData;
201
- if (Buffer.isBuffer(buffer)) {
202
- audioData = buffer;
203
- }
204
- else if (typeof buffer === 'string') {
205
- const rStream = createReadStream(buffer);
206
- audioData = await toBuffer(rStream);
325
+ else if (hasNonNullishProperty(message, 'react')) {
326
+ if (!message.react.senderTimestampMs) {
327
+ message.react.senderTimestampMs = Date.now();
207
328
  }
208
- else {
209
- audioData = await toBuffer(buffer);
210
- }
211
- const audioBuffer = await decoder(audioData);
212
- const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
213
- const samples = 64; // Number of samples we want to have in our final data set
214
- const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
215
- const filteredData = [];
216
- for (let i = 0; i < samples; i++) {
217
- const blockStart = blockSize * i; // the location of the first sample in the block
218
- let sum = 0;
219
- for (let j = 0; j < blockSize; j++) {
220
- sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
329
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
330
+ }
331
+ else if (hasNonNullishProperty(message, 'delete')) {
332
+ m.protocolMessage = {
333
+ key: message.delete,
334
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
335
+ };
336
+ }
337
+ else if (hasNonNullishProperty(message, 'forward')) {
338
+ m = generateForwardMessageContent(message.forward, message.force);
339
+ }
340
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
341
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
342
+ ? message.disappearingMessagesInChat
343
+ ? WA_DEFAULT_EPHEMERAL
344
+ : 0
345
+ : message.disappearingMessagesInChat;
346
+ m = prepareDisappearingMessageSettingContent(exp);
347
+ }
348
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
349
+ m.groupInviteMessage = {};
350
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
351
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
352
+ m.groupInviteMessage.caption = message.groupInvite.text;
353
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
354
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
355
+ //TODO: use built-in interface and get disappearing mode info etc.
356
+ //TODO: cache / use store!?
357
+ if (options.getProfilePicUrl) {
358
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
359
+ if (pfpUrl) {
360
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
361
+ if (resp.ok) {
362
+ const buf = Buffer.from(await resp.arrayBuffer());
363
+ m.groupInviteMessage.jpegThumbnail = buf;
364
+ }
221
365
  }
222
- filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
223
366
  }
224
- // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
225
- const multiplier = Math.pow(Math.max(...filteredData), -1);
226
- const normalizedData = filteredData.map(n => n * multiplier);
227
- // Generate waveform like WhatsApp
228
- const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
229
- return waveform;
230
367
  }
231
- catch (e) {
232
- logger?.debug('Failed to generate waveform: ' + e);
368
+ else if (hasNonNullishProperty(message, 'pin')) {
369
+ m.pinInChatMessage = {};
370
+ m.messageContextInfo = {};
371
+ m.pinInChatMessage.key = message.pin;
372
+ m.pinInChatMessage.type = message.type;
373
+ m.pinInChatMessage.senderTimestampMs = Date.now();
374
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
375
+ }
376
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
377
+ switch (message.type) {
378
+ case 'template':
379
+ m.templateButtonReplyMessage = {
380
+ selectedDisplayText: message.buttonReply.displayText,
381
+ selectedId: message.buttonReply.id,
382
+ selectedIndex: message.buttonReply.index
383
+ };
384
+ break;
385
+ case 'plain':
386
+ m.buttonsResponseMessage = {
387
+ selectedButtonId: message.buttonReply.id,
388
+ selectedDisplayText: message.buttonReply.displayText,
389
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
390
+ };
391
+ break;
392
+ }
233
393
  }
234
- }
235
- export const toReadable = (buffer) => {
236
- const readable = new Readable({ read: () => { } });
237
- readable.push(buffer);
238
- readable.push(null);
239
- return readable;
240
- };
241
- export const toBuffer = async (stream) => {
242
- const chunks = [];
243
- for await (const chunk of stream) {
244
- chunks.push(chunk);
394
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
395
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
396
+ m.ptvMessage = videoMessage;
397
+ }
398
+ else if (hasNonNullishProperty(message, 'product')) {
399
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
400
+ m.productMessage = WAProto.Message.ProductMessage.create({
401
+ ...message,
402
+ product: {
403
+ ...message.product,
404
+ productImage: imageMessage
405
+ }
406
+ });
245
407
  }
246
- stream.destroy();
247
- return Buffer.concat(chunks);
248
- };
249
- export const getStream = async (item, opts) => {
250
- if (Buffer.isBuffer(item)) {
251
- return { stream: toReadable(item), type: 'buffer' };
408
+ else if (hasNonNullishProperty(message, 'listReply')) {
409
+ m.listResponseMessage = { ...message.listReply };
252
410
  }
253
- if ('stream' in item) {
254
- return { stream: item.stream, type: 'readable' };
411
+ else if (hasNonNullishProperty(message, 'event')) {
412
+ m.eventMessage = {};
413
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
414
+ if (message.event.call && options.getCallLink) {
415
+ const token = await options.getCallLink(message.event.call, { startTime });
416
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
417
+ }
418
+ m.messageContextInfo = {
419
+ // encKey
420
+ messageSecret: message.event.messageSecret || randomBytes(32)
421
+ };
422
+ m.eventMessage.name = message.event.name;
423
+ m.eventMessage.description = message.event.description;
424
+ m.eventMessage.startTime = startTime;
425
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
426
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
427
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
428
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
429
+ m.eventMessage.location = message.event.location;
430
+ }
431
+ else if (hasNonNullishProperty(message, 'poll')) {
432
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
433
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
434
+ if (!Array.isArray(message.poll.values)) {
435
+ throw new Boom('Invalid poll values', { statusCode: 400 });
436
+ }
437
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
438
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
439
+ statusCode: 400
440
+ });
441
+ }
442
+ m.messageContextInfo = {
443
+ // encKey
444
+ messageSecret: message.poll.messageSecret || randomBytes(32)
445
+ };
446
+ const pollCreationMessage = {
447
+ name: message.poll.name,
448
+ selectableOptionsCount: message.poll.selectableCount,
449
+ options: message.poll.values.map(optionName => ({ optionName }))
450
+ };
451
+ if (message.poll.toAnnouncementGroup) {
452
+ // poll v2 is for community announcement groups (single select and multiple)
453
+ m.pollCreationMessageV2 = pollCreationMessage;
454
+ }
455
+ else {
456
+ if (message.poll.selectableCount === 1) {
457
+ //poll v3 is for single select polls
458
+ m.pollCreationMessageV3 = pollCreationMessage;
459
+ }
460
+ else {
461
+ // poll for multiple choice polls
462
+ m.pollCreationMessage = pollCreationMessage;
463
+ }
464
+ }
255
465
  }
256
- const urlStr = item.url.toString();
257
- if (urlStr.startsWith('data:')) {
258
- const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
259
- return { stream: toReadable(buffer), type: 'buffer' };
466
+ else if (hasNonNullishProperty(message, 'album')) {
467
+ m.albumMessage = {
468
+ expectedImageCount: message.album.expectedImageCount,
469
+ expectedVideoCount: message.album.expectedVideoCount
470
+ };
260
471
  }
261
- if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
262
- return { stream: await getHttpStream(item.url, opts), type: 'remote' };
472
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
473
+ m.protocolMessage = {
474
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
475
+ };
263
476
  }
264
- return { stream: createReadStream(item.url), type: 'file' };
265
- };
266
- /** generates a thumbnail for a given media, if required */
267
- export async function generateThumbnail(file, mediaType, options) {
268
- let thumbnail;
269
- let originalImageDimensions;
270
- if (mediaType === 'image') {
271
- const { buffer, original } = await extractImageThumb(file);
272
- thumbnail = buffer.toString('base64');
273
- if (original.width && original.height) {
274
- originalImageDimensions = {
275
- width: original.width,
276
- height: original.height
277
- };
278
- }
477
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
478
+ m.requestPhoneNumberMessage = {};
479
+ }
480
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
481
+ m.protocolMessage = {
482
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
483
+ limitSharing: {
484
+ sharingLimited: message.limitSharing === true,
485
+ trigger: 1,
486
+ limitSharingSettingTimestamp: Date.now(),
487
+ initiatedByMe: true
488
+ }
489
+ };
279
490
  }
280
- else if (mediaType === 'video') {
281
- const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg');
282
- try {
283
- await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
284
- const buff = await fs.readFile(imgFilename);
285
- thumbnail = buff.toString('base64');
286
- await fs.unlink(imgFilename);
491
+ else {
492
+ m = await prepareWAMessageMedia(message, options);
493
+ }
494
+ if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
495
+ m = { viewOnceMessage: { message: m } };
496
+ }
497
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
498
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
499
+ const messageType = Object.keys(m)[0];
500
+ const key = m[messageType];
501
+ if (key && 'contextInfo' in key) {
502
+ key.contextInfo = key.contextInfo || {};
503
+ if (message.mentions?.length) {
504
+ key.contextInfo.mentionedJid = message.mentions;
505
+ }
506
+ if (message.mentionAll) {
507
+ key.contextInfo.nonJidMentions = 1;
508
+ }
287
509
  }
288
- catch (err) {
289
- options.logger?.debug('could not generate video thumb: ' + err);
510
+ else if (key) {
511
+ key.contextInfo = {
512
+ mentionedJid: message.mentions,
513
+ nonJidMentions: message.mentionAll ? 1 : 0
514
+ };
290
515
  }
291
516
  }
292
- return {
293
- thumbnail,
294
- originalImageDimensions
295
- };
296
- }
297
- export const getHttpStream = async (url, options = {}) => {
298
- const response = await fetch(url.toString(), {
299
- dispatcher: options.dispatcher,
300
- method: 'GET',
301
- headers: options.headers
302
- });
303
- if (!response.ok) {
304
- throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
517
+ if (hasOptionalProperty(message, 'edit')) {
518
+ m = {
519
+ protocolMessage: {
520
+ key: message.edit,
521
+ editedMessage: m,
522
+ timestampMs: Date.now(),
523
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
524
+ }
525
+ };
305
526
  }
306
- // @ts-ignore Node18+ Readable.fromWeb exists
307
- return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
308
- };
309
- export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
310
- const { stream, type } = await getStream(media, opts);
311
- logger?.debug('fetched media stream');
312
- const mediaKey = Crypto.randomBytes(32);
313
- const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
314
- const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
315
- const encFileWriteStream = createWriteStream(encFilePath);
316
- let originalFileStream;
317
- let originalFilePath;
318
- if (saveOriginalFileIfRequired) {
319
- originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
320
- originalFileStream = createWriteStream(originalFilePath);
321
- }
322
- let fileLength = 0;
323
- const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
324
- const hmac = Crypto.createHmac('sha256', macKey).update(iv);
325
- const sha256Plain = Crypto.createHash('sha256');
326
- const sha256Enc = Crypto.createHash('sha256');
327
- const onChunk = async (buff) => {
328
- sha256Enc.update(buff);
329
- hmac.update(buff);
330
- // Handle backpressure: if write returns false, wait for drain
331
- if (!encFileWriteStream.write(buff)) {
332
- await once(encFileWriteStream, 'drain');
527
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
528
+ const messageType = Object.keys(m)[0];
529
+ const key = m[messageType];
530
+ if ('contextInfo' in key && !!key.contextInfo) {
531
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
333
532
  }
334
- };
335
- try {
336
- for await (const data of stream) {
337
- fileLength += data.length;
338
- if (type === 'remote' &&
339
- opts?.maxContentLength &&
340
- fileLength + data.length > opts.maxContentLength) {
341
- throw new Boom(`content length exceeded when encrypting "${type}"`, {
342
- data: { media, type }
343
- });
344
- }
345
- if (originalFileStream) {
346
- if (!originalFileStream.write(data)) {
347
- await once(originalFileStream, 'drain');
348
- }
533
+ else if (key) {
534
+ key.contextInfo = message.contextInfo;
535
+ }
536
+ }
537
+ if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
538
+ m.messageContextInfo = {
539
+ ...m.messageContextInfo,
540
+ messageAssociation: {
541
+ associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
542
+ parentMessageKey: message.albumParentKey
349
543
  }
350
- sha256Plain.update(data);
351
- await onChunk(aes.update(data));
352
- }
353
- await onChunk(aes.final());
354
- const mac = hmac.digest().slice(0, 10);
355
- sha256Enc.update(mac);
356
- const fileSha256 = sha256Plain.digest();
357
- const fileEncSha256 = sha256Enc.digest();
358
- encFileWriteStream.write(mac);
359
- const encFinishPromise = once(encFileWriteStream, 'finish');
360
- const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
361
- encFileWriteStream.end();
362
- originalFileStream?.end?.();
363
- stream.destroy();
364
- // Wait for write streams to fully flush to disk
365
- // This helps reduce memory pressure by allowing OS to release buffers
366
- await encFinishPromise;
367
- await originalFinishPromise;
368
- logger?.debug('encrypted data successfully');
369
- return {
370
- mediaKey,
371
- originalFilePath,
372
- encFilePath,
373
- mac,
374
- fileEncSha256,
375
- fileSha256,
376
- fileLength
377
544
  };
378
545
  }
379
- catch (error) {
380
- // destroy all streams with error
381
- encFileWriteStream.destroy();
382
- originalFileStream?.destroy?.();
383
- aes.destroy();
384
- hmac.destroy();
385
- sha256Plain.destroy();
386
- sha256Enc.destroy();
387
- stream.destroy();
388
- try {
389
- await fs.unlink(encFilePath);
390
- if (originalFilePath) {
391
- await fs.unlink(originalFilePath);
392
- }
546
+ if (shouldIncludeReportingToken(m)) {
547
+ m.messageContextInfo = m.messageContextInfo || {};
548
+ if (!m.messageContextInfo.messageSecret) {
549
+ m.messageContextInfo.messageSecret = randomBytes(32);
393
550
  }
394
- catch (err) {
395
- logger?.error({ err }, 'failed deleting tmp files');
551
+ }
552
+ return WAProto.Message.create(m);
553
+ };
554
+ export const generateWAMessageFromContent = (jid, message, options) => {
555
+ // set timestamp to now
556
+ // if not specified
557
+ if (!options.timestamp) {
558
+ options.timestamp = new Date();
559
+ }
560
+ const innerMessage = normalizeMessageContent(message);
561
+ const key = getContentType(innerMessage);
562
+ const timestamp = unixTimestampSeconds(options.timestamp);
563
+ const { quoted, userJid } = options;
564
+ if (quoted && !isJidNewsletter(jid)) {
565
+ const participant = quoted.key.fromMe
566
+ ? userJid // TODO: Add support for LIDs
567
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
568
+ let quotedMsg = normalizeMessageContent(quoted.message);
569
+ const msgType = getContentType(quotedMsg);
570
+ // strip any redundant properties
571
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
572
+ const quotedContent = quotedMsg[msgType];
573
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
574
+ delete quotedContent.contextInfo;
396
575
  }
397
- throw error;
576
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
577
+ contextInfo.participant = jidNormalizedUser(participant);
578
+ contextInfo.stanzaId = quoted.key.id;
579
+ contextInfo.quotedMessage = quotedMsg;
580
+ // if a participant is quoted, then it must be a group
581
+ // hence, remoteJid of group must also be entered
582
+ if (jid !== quoted.key.remoteJid) {
583
+ contextInfo.remoteJid = quoted.key.remoteJid;
584
+ }
585
+ if (contextInfo && innerMessage[key]) {
586
+ /* @ts-ignore */
587
+ innerMessage[key].contextInfo = contextInfo;
588
+ }
589
+ }
590
+ if (
591
+ // if we want to send a disappearing message
592
+ !!options?.ephemeralExpiration &&
593
+ // and it's not a protocol message -- delete, toggle disappear message
594
+ key !== 'protocolMessage' &&
595
+ // already not converted to disappearing message
596
+ key !== 'ephemeralMessage' &&
597
+ // newsletters don't support ephemeral messages
598
+ !isJidNewsletter(jid)) {
599
+ /* @ts-ignore */
600
+ innerMessage[key].contextInfo = {
601
+ ...(innerMessage[key].contextInfo || {}),
602
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
603
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
604
+ };
398
605
  }
606
+ message = WAProto.Message.create(message);
607
+ const messageJSON = {
608
+ key: {
609
+ remoteJid: jid,
610
+ fromMe: true,
611
+ id: options?.messageId || generateMessageIDV2()
612
+ },
613
+ message: message,
614
+ messageTimestamp: timestamp,
615
+ messageStubParameters: [],
616
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
617
+ status: WAMessageStatus.PENDING
618
+ };
619
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
399
620
  };
400
- export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
401
- const AES_CHUNK_SIZE = 16;
402
- const toSmallestChunkSize = (num) => {
403
- return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
621
+ export const generateWAMessage = async (jid, content, options) => {
622
+ // ensure msg ID is with every log
623
+ options.logger = options?.logger?.child({ msgId: options.messageId });
624
+ // Pass jid in the options to generateWAMessageContent
625
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
404
626
  };
405
- export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
406
- const extractHost = (url) => {
407
- if (!url)
408
- return undefined;
409
- try {
410
- return new URL(url).host;
627
+ /** Get the key to access the true type of content */
628
+ export const getContentType = (content) => {
629
+ if (content) {
630
+ const keys = Object.keys(content);
631
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
632
+ return key;
411
633
  }
412
- catch {
634
+ };
635
+ /**
636
+ * Normalizes ephemeral, view once messages to regular message content
637
+ * Eg. image messages in ephemeral messages, in view once messages etc.
638
+ * @param content
639
+ * @returns
640
+ */
641
+ export const normalizeMessageContent = (content) => {
642
+ if (!content) {
413
643
  return undefined;
414
644
  }
415
- };
416
- export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
417
- // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
418
- // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
419
- const fallbackHost = opts.host ?? extractHost(url);
420
- const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
421
- if (!downloadUrl) {
422
- throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
423
- }
424
- const keys = await getMediaKeys(mediaKey, type);
425
- return downloadEncryptedContent(downloadUrl, keys, opts);
645
+ // set max iterations to prevent an infinite loop
646
+ for (let i = 0; i < 5; i++) {
647
+ const inner = getFutureProofMessage(content);
648
+ if (!inner) {
649
+ break;
650
+ }
651
+ content = inner.message;
652
+ }
653
+ return content;
654
+ function getFutureProofMessage(message) {
655
+ return (message?.ephemeralMessage ||
656
+ message?.viewOnceMessage ||
657
+ message?.documentWithCaptionMessage ||
658
+ message?.viewOnceMessageV2 ||
659
+ message?.viewOnceMessageV2Extension ||
660
+ message?.editedMessage ||
661
+ message?.associatedChildMessage ||
662
+ message?.groupStatusMessage ||
663
+ message?.groupStatusMessageV2);
664
+ }
426
665
  };
427
666
  /**
428
- * Decrypts and downloads an AES256-CBC encrypted file given the keys.
429
- * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
430
- * */
431
- export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
432
- let bytesFetched = 0;
433
- let startChunk = 0;
434
- let firstBlockIsIV = false;
435
- // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
436
- if (startByte) {
437
- const chunk = toSmallestChunkSize(startByte || 0);
438
- if (chunk) {
439
- startChunk = chunk - AES_CHUNK_SIZE;
440
- bytesFetched = chunk;
441
- firstBlockIsIV = true;
442
- }
443
- }
444
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
445
- const headersInit = options?.headers ? options.headers : undefined;
446
- const headers = {
447
- ...(headersInit
448
- ? Array.isArray(headersInit)
449
- ? Object.fromEntries(headersInit)
450
- : headersInit
451
- : {}),
452
- Origin: DEFAULT_ORIGIN
453
- };
454
- if (startChunk || endChunk) {
455
- headers.Range = `bytes=${startChunk}-`;
456
- if (endChunk) {
457
- headers.Range += endChunk;
667
+ * Extract the true message content from a message
668
+ * Eg. extracts the inner message from a disappearing message/view once message
669
+ */
670
+ export const extractMessageContent = (content) => {
671
+ const extractFromTemplateMessage = (msg) => {
672
+ if (msg.imageMessage) {
673
+ return { imageMessage: msg.imageMessage };
458
674
  }
459
- }
460
- // download the message
461
- const fetched = await getHttpStream(downloadUrl, {
462
- ...(options || {}),
463
- headers
464
- });
465
- let remainingBytes = Buffer.from([]);
466
- let aes;
467
- const pushBytes = (bytes, push) => {
468
- if (startByte || endByte) {
469
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
470
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
471
- push(bytes.slice(start, end));
472
- bytesFetched += bytes.length;
675
+ else if (msg.documentMessage) {
676
+ return { documentMessage: msg.documentMessage };
677
+ }
678
+ else if (msg.videoMessage) {
679
+ return { videoMessage: msg.videoMessage };
680
+ }
681
+ else if (msg.locationMessage) {
682
+ return { locationMessage: msg.locationMessage };
473
683
  }
474
684
  else {
475
- push(bytes);
685
+ return {
686
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
687
+ };
476
688
  }
477
689
  };
478
- const output = new Transform({
479
- transform(chunk, _, callback) {
480
- let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
481
- const decryptLength = toSmallestChunkSize(data.length);
482
- remainingBytes = data.slice(decryptLength);
483
- data = data.slice(0, decryptLength);
484
- if (!aes) {
485
- let ivValue = iv;
486
- if (firstBlockIsIV) {
487
- ivValue = data.slice(0, AES_CHUNK_SIZE);
488
- data = data.slice(AES_CHUNK_SIZE);
489
- }
490
- aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
491
- // if an end byte that is not EOF is specified
492
- // stop auto padding (PKCS7) -- otherwise throws an error for decryption
493
- if (endByte) {
494
- aes.setAutoPadding(false);
495
- }
496
- }
497
- try {
498
- pushBytes(aes.update(data), b => this.push(b));
499
- callback();
500
- }
501
- catch (error) {
502
- callback(error);
503
- }
504
- },
505
- final(callback) {
506
- try {
507
- pushBytes(aes.final(), b => this.push(b));
508
- callback();
509
- }
510
- catch (error) {
511
- callback(error);
512
- }
513
- }
514
- });
515
- return fetched.pipe(output, { end: true });
516
- };
517
- export function extensionForMediaMessage(message) {
518
- const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
519
- const type = Object.keys(message)[0];
520
- let extension;
521
- if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
522
- extension = '.jpeg';
690
+ content = normalizeMessageContent(content);
691
+ if (content?.buttonsMessage) {
692
+ return extractFromTemplateMessage(content.buttonsMessage);
523
693
  }
524
- else {
525
- const messageContent = message[type];
526
- extension = getExtension(messageContent.mimetype);
694
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
695
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
527
696
  }
528
- return extension;
529
- }
530
- const isNodeRuntime = () => {
531
- return (typeof process !== 'undefined' &&
532
- process.versions?.node !== null &&
533
- typeof process.versions.bun === 'undefined' &&
534
- typeof globalThis.Deno === 'undefined');
535
- };
536
- export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
537
- if (redirectCount > 5) {
538
- throw new Error('Too many redirects');
539
- }
540
- const parsedUrl = new URL(url);
541
- const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
542
- // Get file size for Content-Length header (required for Node.js streaming)
543
- const fileStats = await fs.stat(filePath);
544
- const fileSize = fileStats.size;
545
- return new Promise((resolve, reject) => {
546
- const req = httpModule.request({
547
- hostname: parsedUrl.hostname,
548
- port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
549
- path: parsedUrl.pathname + parsedUrl.search,
550
- method: 'POST',
551
- headers: {
552
- ...headers,
553
- 'Content-Length': fileSize
554
- },
555
- agent,
556
- timeout: timeoutMs
557
- }, res => {
558
- // Handle redirects (3xx)
559
- if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
560
- res.resume(); // Consume response to free resources
561
- const newUrl = new URL(res.headers.location, url).toString();
562
- resolve(uploadWithNodeHttp({
563
- url: newUrl,
564
- filePath,
565
- headers,
566
- timeoutMs,
567
- agent
568
- }, redirectCount + 1));
569
- return;
570
- }
571
- let body = '';
572
- res.on('data', chunk => (body += chunk));
573
- res.on('end', () => {
574
- try {
575
- resolve(JSON.parse(body));
576
- }
577
- catch {
578
- resolve(undefined);
579
- }
580
- });
581
- });
582
- req.on('error', reject);
583
- req.on('timeout', () => {
584
- req.destroy();
585
- reject(new Error('Upload timeout'));
586
- });
587
- const stream = createReadStream(filePath);
588
- stream.pipe(req);
589
- stream.on('error', err => {
590
- req.destroy();
591
- reject(err);
592
- });
593
- });
594
- };
595
- const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
596
- // Convert Node.js Readable to Web ReadableStream
597
- const nodeStream = createReadStream(filePath);
598
- const webStream = Readable.toWeb(nodeStream);
599
- // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
600
- const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
601
- const response = await fetch(url, {
602
- ...(dispatcher ? { dispatcher } : {}),
603
- method: 'POST',
604
- body: webStream,
605
- headers,
606
- duplex: 'half',
607
- signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
608
- });
609
- try {
610
- return (await response.json());
697
+ if (content?.templateMessage?.hydratedTemplate) {
698
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
611
699
  }
612
- catch {
613
- return undefined;
700
+ if (content?.templateMessage?.fourRowTemplate) {
701
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
614
702
  }
703
+ return content;
615
704
  };
616
705
  /**
617
- * Uploads media to WhatsApp servers.
618
- *
619
- * ## Why we have two upload implementations:
620
- *
621
- * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
622
- * the entire request body in memory before sending, even when using streams.
623
- * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
624
- * See: https://github.com/nodejs/undici/issues/4058
625
- *
626
- * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
627
- * buffering, so we can use the web-standard Fetch API there.
628
- *
629
- * ## Future considerations:
630
- * Once the undici bug is fixed, we can simplify this to use only the Fetch API
631
- * across all runtimes. Monitor the GitHub issue for updates.
706
+ * Returns the device predicted by message ID
632
707
  */
633
- const uploadMedia = async (params, logger) => {
634
- if (isNodeRuntime()) {
635
- logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
636
- return uploadWithNodeHttp(params);
708
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
709
+ ? 'ios'
710
+ : /^3E.{20}$/.test(id)
711
+ ? 'web'
712
+ : /^(.{21}|.{32})$/.test(id)
713
+ ? 'android'
714
+ : /^(3F|.{18}$)/.test(id)
715
+ ? 'desktop'
716
+ : 'unknown';
717
+ /** Upserts a receipt in the message */
718
+ export const updateMessageWithReceipt = (msg, receipt) => {
719
+ msg.userReceipt = msg.userReceipt || [];
720
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
721
+ if (recp) {
722
+ Object.assign(recp, receipt);
637
723
  }
638
724
  else {
639
- logger?.debug('Using web-standard Fetch API for upload');
640
- return uploadWithFetch(params);
725
+ msg.userReceipt.push(receipt);
641
726
  }
642
727
  };
643
- export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
644
- return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
645
- // send a query JSON to obtain the url & auth token to upload our media
646
- let uploadInfo = await refreshMediaConn(false);
647
- let urls;
648
- const hosts = [...customUploadHosts, ...uploadInfo.hosts];
649
- fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
650
- // Prepare common headers
651
- const customHeaders = (() => {
652
- const hdrs = options?.headers;
653
- if (!hdrs)
654
- return {};
655
- return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
656
- })();
657
- const headers = {
658
- ...customHeaders,
659
- 'Content-Type': 'application/octet-stream',
660
- Origin: DEFAULT_ORIGIN
728
+ /** Update the message with a new reaction */
729
+ export const updateMessageWithReaction = (msg, reaction) => {
730
+ const authorID = getKeyAuthor(reaction.key);
731
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
732
+ reaction.text = reaction.text || '';
733
+ reactions.push(reaction);
734
+ msg.reactions = reactions;
735
+ };
736
+ /** Update the message with a new poll update */
737
+ export const updateMessageWithPollUpdate = (msg, update) => {
738
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
739
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
740
+ if (update.vote?.selectedOptions?.length) {
741
+ reactions.push(update);
742
+ }
743
+ msg.pollUpdates = reactions;
744
+ };
745
+ /** Update the message with a new event response */
746
+ export const updateMessageWithEventResponse = (msg, update) => {
747
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
748
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
749
+ responses.push(update);
750
+ msg.eventResponses = responses;
751
+ };
752
+ /**
753
+ * Aggregates all poll updates in a poll.
754
+ * @param msg the poll creation message
755
+ * @param meId your jid
756
+ * @returns A list of options & their voters
757
+ */
758
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
759
+ const opts = message?.pollCreationMessage?.options ||
760
+ message?.pollCreationMessageV2?.options ||
761
+ message?.pollCreationMessageV3?.options ||
762
+ [];
763
+ const voteHashMap = opts.reduce((acc, opt) => {
764
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
765
+ acc[hash] = {
766
+ name: opt.optionName || '',
767
+ voters: []
661
768
  };
662
- for (const { hostname } of hosts) {
663
- logger.debug(`uploading to "${hostname}"`);
664
- const auth = encodeURIComponent(uploadInfo.auth);
665
- const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
666
- let result;
667
- try {
668
- result = await uploadMedia({
669
- url,
670
- filePath,
671
- headers,
672
- timeoutMs,
673
- agent: fetchAgent
674
- }, logger);
675
- if (result?.url || result?.direct_path) {
676
- urls = {
677
- mediaUrl: result.url,
678
- directPath: result.direct_path,
679
- meta_hmac: result.meta_hmac,
680
- fbid: result.fbid,
681
- ts: result.ts
682
- };
683
- break;
684
- }
685
- else {
686
- uploadInfo = await refreshMediaConn(true);
687
- throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
688
- }
689
- }
690
- catch (error) {
691
- const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
692
- logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
693
- }
769
+ return acc;
770
+ }, {});
771
+ for (const update of pollUpdates || []) {
772
+ const { vote } = update;
773
+ if (!vote) {
774
+ continue;
694
775
  }
695
- if (!urls) {
696
- throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
776
+ for (const option of vote.selectedOptions || []) {
777
+ const hash = option.toString();
778
+ let data = voteHashMap[hash];
779
+ if (!data) {
780
+ voteHashMap[hash] = {
781
+ name: 'Unknown',
782
+ voters: []
783
+ };
784
+ data = voteHashMap[hash];
785
+ }
786
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
697
787
  }
698
- return urls;
699
- };
700
- };
701
- const getMediaRetryKey = (mediaKey) => {
702
- return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
703
- };
788
+ }
789
+ return Object.values(voteHashMap);
790
+ }
704
791
  /**
705
- * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
792
+ * Aggregates all event responses in an event message.
793
+ * @param msg the event creation message
794
+ * @param meId your jid
795
+ * @returns A list of response types & their responders
706
796
  */
707
- export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
708
- const recp = { stanzaId: key.id };
709
- const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
710
- const iv = Crypto.randomBytes(12);
711
- const retryKey = getMediaRetryKey(mediaKey);
712
- const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
713
- const req = {
714
- tag: 'receipt',
715
- attrs: {
716
- id: key.id,
717
- to: jidNormalizedUser(meId),
718
- type: 'server-error'
719
- },
720
- content: [
721
- // this encrypt node is actually pretty useless
722
- // the media is returned even without this node
723
- // keeping it here to maintain parity with WA Web
724
- {
725
- tag: 'encrypt',
726
- attrs: {},
727
- content: [
728
- { tag: 'enc_p', attrs: {}, content: ciphertext },
729
- { tag: 'enc_iv', attrs: {}, content: iv }
730
- ]
731
- },
732
- {
733
- tag: 'rmr',
734
- attrs: {
735
- jid: key.remoteJid,
736
- from_me: (!!key.fromMe).toString(),
737
- // @ts-ignore
738
- participant: key.participant || undefined
739
- }
797
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
798
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
799
+ const responseMap = {};
800
+ for (const type of responseTypes) {
801
+ responseMap[type] = {
802
+ response: type,
803
+ responders: []
804
+ };
805
+ }
806
+ for (const update of eventResponses || []) {
807
+ const responseType = update.eventResponse || 'UNKNOWN';
808
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
809
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
810
+ }
811
+ }
812
+ return Object.values(responseMap);
813
+ }
814
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
815
+ export const aggregateMessageKeysNotFromMe = (keys) => {
816
+ const keyMap = {};
817
+ for (const { remoteJid, id, participant, fromMe } of keys) {
818
+ if (!fromMe) {
819
+ const uqKey = `${remoteJid}:${participant || ''}`;
820
+ if (!keyMap[uqKey]) {
821
+ keyMap[uqKey] = {
822
+ jid: remoteJid,
823
+ participant: participant,
824
+ messageIds: []
825
+ };
740
826
  }
741
- ]
742
- };
743
- return req;
744
- };
745
- export const decodeMediaRetryNode = (node) => {
746
- const rmrNode = getBinaryNodeChild(node, 'rmr');
747
- const event = {
748
- key: {
749
- id: node.attrs.id,
750
- remoteJid: rmrNode.attrs.jid,
751
- fromMe: rmrNode.attrs.from_me === 'true',
752
- participant: rmrNode.attrs.participant
827
+ keyMap[uqKey].messageIds.push(id);
753
828
  }
754
- };
755
- const errorNode = getBinaryNodeChild(node, 'error');
756
- if (errorNode) {
757
- const errorCode = +errorNode.attrs.code;
758
- event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
759
- data: errorNode.attrs,
760
- statusCode: getStatusCodeForMediaRetry(errorCode)
761
- });
762
829
  }
763
- else {
764
- const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
765
- const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
766
- const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
767
- if (ciphertext && iv) {
768
- event.media = { ciphertext, iv };
830
+ return Object.values(keyMap);
831
+ };
832
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
833
+ /**
834
+ * Downloads the given message. Throws an error if it's not a media message
835
+ */
836
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
837
+ const result = await downloadMsg().catch(async (error) => {
838
+ if (ctx &&
839
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
840
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
841
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
842
+ // request reupload
843
+ message = await ctx.reuploadRequest(message);
844
+ const result = await downloadMsg();
845
+ return result;
846
+ }
847
+ throw error;
848
+ });
849
+ return result;
850
+ async function downloadMsg() {
851
+ const mContent = extractMessageContent(message.message);
852
+ if (!mContent) {
853
+ throw new Boom('No message present', { statusCode: 400, data: message });
854
+ }
855
+ const contentType = getContentType(mContent);
856
+ let mediaType = contentType?.replace('Message', '');
857
+ const media = mContent[contentType];
858
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
859
+ throw new Boom(`"${contentType}" message is not a media message`);
860
+ }
861
+ let download;
862
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
863
+ download = {
864
+ directPath: media.thumbnailDirectPath,
865
+ mediaKey: media.mediaKey
866
+ };
867
+ mediaType = 'thumbnail-link';
769
868
  }
770
869
  else {
771
- event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
870
+ download = media;
772
871
  }
872
+ const stream = await downloadContentFromMessage(download, mediaType, options);
873
+ if (type === 'buffer') {
874
+ const bufferArray = [];
875
+ for await (const chunk of stream) {
876
+ bufferArray.push(chunk);
877
+ }
878
+ return Buffer.concat(bufferArray);
879
+ }
880
+ return stream;
773
881
  }
774
- return event;
775
- };
776
- export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
777
- const retryKey = getMediaRetryKey(mediaKey);
778
- const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
779
- return proto.MediaRetryNotification.decode(plaintext);
780
882
  };
781
- export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
782
- const MEDIA_RETRY_STATUS_MAP = {
783
- [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
784
- [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
785
- [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
786
- [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
883
+ /** Checks whether the given message is a media message; if it is returns the inner content */
884
+ export const assertMediaContent = (content) => {
885
+ content = extractMessageContent(content);
886
+ const mediaContent = content?.documentMessage ||
887
+ content?.imageMessage ||
888
+ content?.videoMessage ||
889
+ content?.audioMessage ||
890
+ content?.stickerMessage;
891
+ if (!mediaContent) {
892
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
893
+ }
894
+ return mediaContent;
787
895
  };
788
- //# sourceMappingURL=messages-media.js.map
896
+ //# sourceMappingURL=messages.js.map