@vinzsocket/baileys 2.8.10 → 2.8.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/lib/Defaults/index.js +75 -73
  2. package/lib/Signal/Group/ciphertext-message.js +9 -9
  3. package/lib/Signal/Group/group-session-builder.js +21 -21
  4. package/lib/Signal/Group/group_cipher.js +79 -81
  5. package/lib/Signal/Group/index.js +2 -2
  6. package/lib/Signal/Group/keyhelper.js +9 -9
  7. package/lib/Signal/Group/queue-job.js +43 -46
  8. package/lib/Signal/Group/sender-chain-key.js +24 -25
  9. package/lib/Signal/Group/sender-key-distribution-message.js +50 -58
  10. package/lib/Signal/Group/sender-key-message.js +55 -60
  11. package/lib/Signal/Group/sender-key-name.js +38 -39
  12. package/lib/Signal/Group/sender-key-record.js +39 -41
  13. package/lib/Signal/Group/sender-key-state.js +85 -89
  14. package/lib/Signal/Group/sender-message-key.js +22 -22
  15. package/lib/Signal/libsignal.js +387 -292
  16. package/lib/Signal/lid-mapping.js +98 -93
  17. package/lib/Socket/Client/types.js +6 -6
  18. package/lib/Socket/Client/websocket.js +44 -44
  19. package/lib/Socket/business.js +350 -365
  20. package/lib/Socket/chats.js +1019 -914
  21. package/lib/Socket/communities.js +454 -376
  22. package/lib/Socket/groups.js +378 -310
  23. package/lib/Socket/index.js +11 -11
  24. package/lib/Socket/messages-recv.js +1355 -1182
  25. package/lib/Socket/messages-send.js +1224 -1081
  26. package/lib/Socket/mex.js +40 -34
  27. package/lib/Socket/newsletter.js +212 -169
  28. package/lib/Socket/socket.js +896 -757
  29. package/lib/Store/index.js +1 -1
  30. package/lib/Store/make-cache-manager-store.js +75 -79
  31. package/lib/Store/make-in-memory-store.js +450 -389
  32. package/lib/Store/make-ordered-dictionary.js +73 -76
  33. package/lib/Store/object-repository.js +24 -22
  34. package/lib/Types/Chat.js +1 -7
  35. package/lib/Types/Label.js +20 -20
  36. package/lib/Types/LabelAssociation.js +2 -2
  37. package/lib/Types/Message.js +2 -2
  38. package/lib/Types/Newsletter.js +24 -24
  39. package/lib/Types/Socket.js +1 -1
  40. package/lib/Types/State.js +8 -8
  41. package/lib/Types/index.js +10 -10
  42. package/lib/Utils/auth-utils.js +408 -401
  43. package/lib/Utils/baileys-event-stream.js +44 -35
  44. package/lib/Utils/business.js +200 -197
  45. package/lib/Utils/chat-utils.js +775 -708
  46. package/lib/Utils/crypto.js +97 -85
  47. package/lib/Utils/decode-wa-message.js +240 -227
  48. package/lib/Utils/event-buffer.js +547 -518
  49. package/lib/Utils/extended-messages.js +250 -203
  50. package/lib/Utils/generics.js +300 -289
  51. package/lib/Utils/history.js +76 -69
  52. package/lib/Utils/lid-resolver.js +47 -42
  53. package/lib/Utils/link-preview.js +75 -65
  54. package/lib/Utils/logger.js +3 -1
  55. package/lib/Utils/lt-hash.js +38 -34
  56. package/lib/Utils/make-mutex.js +32 -34
  57. package/lib/Utils/mention.js +79 -86
  58. package/lib/Utils/message-retry-manager.js +148 -136
  59. package/lib/Utils/messages-media.js +652 -562
  60. package/lib/Utils/messages.js +753 -707
  61. package/lib/Utils/noise-handler.js +156 -135
  62. package/lib/Utils/process-message.js +404 -341
  63. package/lib/Utils/signal.js +180 -118
  64. package/lib/Utils/use-multi-file-auth-state.js +87 -91
  65. package/lib/Utils/validate-connection.js +167 -142
  66. package/lib/WABinary/constants.js +28 -1293
  67. package/lib/WABinary/decode.js +220 -218
  68. package/lib/WABinary/encode.js +199 -201
  69. package/lib/WABinary/generic-utils.js +80 -77
  70. package/lib/WABinary/jid-utils.js +41 -35
  71. package/lib/WAM/BinaryInfo.js +7 -7
  72. package/lib/WAM/constants.js +1 -15241
  73. package/lib/WAM/encode.js +124 -131
  74. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  75. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +51 -47
  76. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -22
  77. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -32
  78. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -19
  79. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -43
  80. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +17 -17
  81. package/lib/WAUSync/USyncQuery.js +82 -84
  82. package/lib/WAUSync/USyncUser.js +20 -20
  83. package/package.json +4 -2
@@ -1,5 +1,5 @@
1
1
  import { Boom } from '@hapi/boom';
2
- import axios, {} from 'axios';
2
+ import axios from 'axios';
3
3
  import { exec } from 'child_process';
4
4
  import * as Crypto from 'crypto';
5
5
  import { once } from 'events';
@@ -15,628 +15,718 @@ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
15
15
  import { generateMessageIDV2 } from './generics.js';
16
16
  const getTmpFilesDirectory = () => tmpdir();
17
17
  const getImageProcessingLibrary = async () => {
18
- //@ts-ignore
19
- const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
20
- if (sharp) {
21
- return { sharp };
22
- }
23
- if (jimp) {
24
- return { jimp };
25
- }
26
- throw new Boom('No image processing library available');
18
+ //@ts-ignore
19
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => {}), import('sharp').catch(() => {})]);
20
+ if (sharp) {
21
+ return {
22
+ sharp
23
+ };
24
+ }
25
+ if (jimp) {
26
+ return {
27
+ jimp
28
+ };
29
+ }
30
+ throw new Boom('No image processing library available');
27
31
  };
28
- export const hkdfInfoKey = (type) => {
29
- const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
30
- return `WhatsApp ${hkdfInfo} Keys`;
32
+ export const hkdfInfoKey = type => {
33
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
34
+ return `WhatsApp ${hkdfInfo} Keys`;
31
35
  };
32
36
  export const getRawMediaUploadData = async (media, mediaType, logger) => {
33
- const { stream } = await getStream(media);
34
- logger?.debug('got stream for raw upload');
35
- const hasher = Crypto.createHash('sha256');
36
- const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
37
- const fileWriteStream = createWriteStream(filePath);
38
- let fileLength = 0;
37
+ const {
38
+ stream
39
+ } = await getStream(media);
40
+ logger?.debug('got stream for raw upload');
41
+ const hasher = Crypto.createHash('sha256');
42
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
43
+ const fileWriteStream = createWriteStream(filePath);
44
+ let fileLength = 0;
45
+ try {
46
+ for await (const data of stream) {
47
+ fileLength += data.length;
48
+ hasher.update(data);
49
+ if (!fileWriteStream.write(data)) {
50
+ await once(fileWriteStream, 'drain');
51
+ }
52
+ }
53
+ fileWriteStream.end();
54
+ await once(fileWriteStream, 'finish');
55
+ stream.destroy();
56
+ const fileSha256 = hasher.digest();
57
+ logger?.debug('hashed data for raw upload');
58
+ return {
59
+ filePath: filePath,
60
+ fileSha256,
61
+ fileLength
62
+ };
63
+ } catch (error) {
64
+ fileWriteStream.destroy();
65
+ stream.destroy();
39
66
  try {
40
- for await (const data of stream) {
41
- fileLength += data.length;
42
- hasher.update(data);
43
- if (!fileWriteStream.write(data)) {
44
- await once(fileWriteStream, 'drain');
45
- }
46
- }
47
- fileWriteStream.end();
48
- await once(fileWriteStream, 'finish');
49
- stream.destroy();
50
- const fileSha256 = hasher.digest();
51
- logger?.debug('hashed data for raw upload');
52
- return {
53
- filePath: filePath,
54
- fileSha256,
55
- fileLength
56
- };
57
- }
58
- catch (error) {
59
- fileWriteStream.destroy();
60
- stream.destroy();
61
- try {
62
- await fs.unlink(filePath);
63
- }
64
- catch {
65
- //
66
- }
67
- throw error;
67
+ await fs.unlink(filePath);
68
+ } catch {
69
+ //
68
70
  }
71
+ throw error;
72
+ }
69
73
  };
70
74
  /** generates all the keys required to encrypt/decrypt & sign a media message */
71
75
  export async function getMediaKeys(buffer, mediaType) {
72
- if (!buffer) {
73
- throw new Boom('Cannot derive from empty media key');
74
- }
75
- if (typeof buffer === 'string') {
76
- buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
77
- }
78
- // expand using HKDF to 112 bytes, also pass in the relevant app info
79
- const expandedMediaKey = await hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
80
- return {
81
- iv: expandedMediaKey.slice(0, 16),
82
- cipherKey: expandedMediaKey.slice(16, 48),
83
- macKey: expandedMediaKey.slice(48, 80)
84
- };
76
+ if (!buffer) {
77
+ throw new Boom('Cannot derive from empty media key');
78
+ }
79
+ if (typeof buffer === 'string') {
80
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
81
+ }
82
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
83
+ const expandedMediaKey = await hkdf(buffer, 112, {
84
+ info: hkdfInfoKey(mediaType)
85
+ });
86
+ return {
87
+ iv: expandedMediaKey.slice(0, 16),
88
+ cipherKey: expandedMediaKey.slice(16, 48),
89
+ macKey: expandedMediaKey.slice(48, 80)
90
+ };
85
91
  }
86
92
  /** Extracts video thumb using FFMPEG */
87
93
  const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
88
- const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
89
- exec(cmd, err => {
90
- if (err) {
91
- reject(err);
92
- }
93
- else {
94
- resolve();
95
- }
96
- });
94
+ const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
95
+ exec(cmd, err => {
96
+ if (err) {
97
+ reject(err);
98
+ } else {
99
+ resolve();
100
+ }
101
+ });
97
102
  });
98
103
  export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
99
- // TODO: Move entirely to sharp, removing jimp as it supports readable streams
100
- // This will have positive speed and performance impacts as well as minimizing RAM usage.
101
- if (bufferOrFilePath instanceof Readable) {
102
- bufferOrFilePath = await toBuffer(bufferOrFilePath);
103
- }
104
- const lib = await getImageProcessingLibrary();
105
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
106
- const img = lib.sharp.default(bufferOrFilePath);
107
- const dimensions = await img.metadata();
108
- const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
109
- return {
110
- buffer,
111
- original: {
112
- width: dimensions.width,
113
- height: dimensions.height
114
- }
115
- };
116
- }
117
- else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
118
- const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
119
- const dimensions = {
120
- width: jimp.width,
121
- height: jimp.height
122
- };
123
- const buffer = await jimp
124
- .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
125
- .getBuffer('image/jpeg', { quality: 50 });
126
- return {
127
- buffer,
128
- original: dimensions
129
- };
130
- }
131
- else {
132
- throw new Boom('No image processing library available');
133
- }
134
- };
135
- export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
136
- export const generateProfilePicture = async (mediaUpload, dimensions) => {
137
- let buffer;
138
- const { width: w = 640, height: h = 640 } = dimensions || {};
139
- if (Buffer.isBuffer(mediaUpload)) {
140
- buffer = mediaUpload;
141
- }
142
- else {
143
- // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
144
- const { stream } = await getStream(mediaUpload);
145
- // Convert the resulting stream to a buffer
146
- buffer = await toBuffer(stream);
147
- }
148
- const lib = await getImageProcessingLibrary();
149
- let img;
150
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
151
- img = lib.sharp
152
- .default(buffer)
153
- .resize(w, h)
154
- .jpeg({
155
- quality: 50
156
- })
157
- .toBuffer();
158
- }
159
- else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
160
- const jimp = await lib.jimp.Jimp.read(buffer);
161
- const min = Math.min(jimp.width, jimp.height);
162
- const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
163
- img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
164
- }
165
- else {
166
- throw new Boom('No image processing library available');
167
- }
104
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
105
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
106
+ if (bufferOrFilePath instanceof Readable) {
107
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
108
+ }
109
+ const lib = await getImageProcessingLibrary();
110
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
111
+ const img = lib.sharp.default(bufferOrFilePath);
112
+ const dimensions = await img.metadata();
113
+ const buffer = await img.resize(width).jpeg({
114
+ quality: 50
115
+ }).toBuffer();
116
+ return {
117
+ buffer,
118
+ original: {
119
+ width: dimensions.width,
120
+ height: dimensions.height
121
+ }
122
+ };
123
+ } else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
124
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
125
+ const dimensions = {
126
+ width: jimp.width,
127
+ height: jimp.height
128
+ };
129
+ const buffer = await jimp.resize({
130
+ w: width,
131
+ mode: lib.jimp.ResizeStrategy.BILINEAR
132
+ }).getBuffer('image/jpeg', {
133
+ quality: 50
134
+ });
168
135
  return {
169
- img: await img
136
+ buffer,
137
+ original: dimensions
170
138
  };
139
+ } else {
140
+ throw new Boom('No image processing library available');
141
+ }
142
+ };
143
+ export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
144
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
145
+ let buffer;
146
+ const {
147
+ width: w = 640,
148
+ height: h = 640
149
+ } = dimensions || {};
150
+ if (Buffer.isBuffer(mediaUpload)) {
151
+ buffer = mediaUpload;
152
+ } else {
153
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
154
+ const {
155
+ stream
156
+ } = await getStream(mediaUpload);
157
+ // Convert the resulting stream to a buffer
158
+ buffer = await toBuffer(stream);
159
+ }
160
+ const lib = await getImageProcessingLibrary();
161
+ let img;
162
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
163
+ img = lib.sharp.default(buffer).resize(w, h).jpeg({
164
+ quality: 50
165
+ }).toBuffer();
166
+ } else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
167
+ const jimp = await lib.jimp.Jimp.read(buffer);
168
+ const min = Math.min(jimp.width, jimp.height);
169
+ const cropped = jimp.crop({
170
+ x: 0,
171
+ y: 0,
172
+ w: min,
173
+ h: min
174
+ });
175
+ img = cropped.resize({
176
+ w,
177
+ h,
178
+ mode: lib.jimp.ResizeStrategy.BILINEAR
179
+ }).getBuffer('image/jpeg', {
180
+ quality: 50
181
+ });
182
+ } else {
183
+ throw new Boom('No image processing library available');
184
+ }
185
+ return {
186
+ img: await img
187
+ };
171
188
  };
172
189
  /** gets the SHA256 of the given media message */
173
- export const mediaMessageSHA256B64 = (message) => {
174
- const media = Object.values(message)[0];
175
- return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
190
+ export const mediaMessageSHA256B64 = message => {
191
+ const media = Object.values(message)[0];
192
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
176
193
  };
177
194
  export async function getAudioDuration(buffer) {
178
- const musicMetadata = await import('music-metadata');
179
- let metadata;
180
- const options = {
181
- duration: true
182
- };
183
- if (Buffer.isBuffer(buffer)) {
184
- metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
185
- }
186
- else if (typeof buffer === 'string') {
187
- metadata = await musicMetadata.parseFile(buffer, options);
188
- }
189
- else {
190
- metadata = await musicMetadata.parseStream(buffer, undefined, options);
191
- }
192
- return metadata.format.duration;
195
+ const musicMetadata = await import('music-metadata');
196
+ let metadata;
197
+ const options = {
198
+ duration: true
199
+ };
200
+ if (Buffer.isBuffer(buffer)) {
201
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
202
+ } else if (typeof buffer === 'string') {
203
+ metadata = await musicMetadata.parseFile(buffer, options);
204
+ } else {
205
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
206
+ }
207
+ return metadata.format.duration;
193
208
  }
194
209
  /**
195
210
  referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
196
211
  */
197
212
  export async function getAudioWaveform(buffer, logger) {
198
- try {
199
- // @ts-ignore
200
- const { default: decoder } = await import('audio-decode');
201
- let audioData;
202
- if (Buffer.isBuffer(buffer)) {
203
- audioData = buffer;
204
- }
205
- else if (typeof buffer === 'string') {
206
- const rStream = createReadStream(buffer);
207
- audioData = await toBuffer(rStream);
208
- }
209
- else {
210
- audioData = await toBuffer(buffer);
211
- }
212
- const audioBuffer = await decoder(audioData);
213
- const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
214
- const samples = 64; // Number of samples we want to have in our final data set
215
- const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
216
- const filteredData = [];
217
- for (let i = 0; i < samples; i++) {
218
- const blockStart = blockSize * i; // the location of the first sample in the block
219
- let sum = 0;
220
- for (let j = 0; j < blockSize; j++) {
221
- sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
222
- }
223
- filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
224
- }
225
- // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
226
- const multiplier = Math.pow(Math.max(...filteredData), -1);
227
- const normalizedData = filteredData.map(n => n * multiplier);
228
- // Generate waveform like WhatsApp
229
- const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
230
- return waveform;
231
- }
232
- catch (e) {
233
- logger?.debug('Failed to generate waveform: ' + e);
234
- }
213
+ try {
214
+ // @ts-ignore
215
+ const {
216
+ default: decoder
217
+ } = await import('audio-decode');
218
+ let audioData;
219
+ if (Buffer.isBuffer(buffer)) {
220
+ audioData = buffer;
221
+ } else if (typeof buffer === 'string') {
222
+ const rStream = createReadStream(buffer);
223
+ audioData = await toBuffer(rStream);
224
+ } else {
225
+ audioData = await toBuffer(buffer);
226
+ }
227
+ const audioBuffer = await decoder(audioData);
228
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
229
+ const samples = 64; // Number of samples we want to have in our final data set
230
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
231
+ const filteredData = [];
232
+ for (let i = 0; i < samples; i++) {
233
+ const blockStart = blockSize * i; // the location of the first sample in the block
234
+ let sum = 0;
235
+ for (let j = 0; j < blockSize; j++) {
236
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
237
+ }
238
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
239
+ }
240
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
241
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
242
+ const normalizedData = filteredData.map(n => n * multiplier);
243
+ // Generate waveform like WhatsApp
244
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
245
+ return waveform;
246
+ } catch (e) {
247
+ logger?.debug('Failed to generate waveform: ' + e);
248
+ }
235
249
  }
236
- export const toReadable = (buffer) => {
237
- const readable = new Readable({ read: () => { } });
238
- readable.push(buffer);
239
- readable.push(null);
240
- return readable;
250
+ export const toReadable = buffer => {
251
+ const readable = new Readable({
252
+ read: () => {}
253
+ });
254
+ readable.push(buffer);
255
+ readable.push(null);
256
+ return readable;
241
257
  };
242
- export const toBuffer = async (stream) => {
243
- const chunks = [];
244
- for await (const chunk of stream) {
245
- chunks.push(chunk);
246
- }
247
- stream.destroy();
248
- return Buffer.concat(chunks);
258
+ export const toBuffer = async stream => {
259
+ const chunks = [];
260
+ for await (const chunk of stream) {
261
+ chunks.push(chunk);
262
+ }
263
+ stream.destroy();
264
+ return Buffer.concat(chunks);
249
265
  };
250
266
  export const getStream = async (item, opts) => {
251
- if (Buffer.isBuffer(item)) {
252
- return { stream: toReadable(item), type: 'buffer' };
253
- }
254
- if ('stream' in item) {
255
- return { stream: item.stream, type: 'readable' };
256
- }
257
- const urlStr = item.url.toString();
258
- if (urlStr.startsWith('data:')) {
259
- const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
260
- return { stream: toReadable(buffer), type: 'buffer' };
261
- }
262
- if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
263
- return { stream: await getHttpStream(item.url, opts), type: 'remote' };
264
- }
265
- return { stream: createReadStream(item.url), type: 'file' };
267
+ if (Buffer.isBuffer(item)) {
268
+ return {
269
+ stream: toReadable(item),
270
+ type: 'buffer'
271
+ };
272
+ }
273
+ if ('stream' in item) {
274
+ return {
275
+ stream: item.stream,
276
+ type: 'readable'
277
+ };
278
+ }
279
+ const urlStr = item.url.toString();
280
+ if (urlStr.startsWith('data:')) {
281
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
282
+ return {
283
+ stream: toReadable(buffer),
284
+ type: 'buffer'
285
+ };
286
+ }
287
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
288
+ return {
289
+ stream: await getHttpStream(item.url, opts),
290
+ type: 'remote'
291
+ };
292
+ }
293
+ return {
294
+ stream: createReadStream(item.url),
295
+ type: 'file'
296
+ };
266
297
  };
267
298
  /** generates a thumbnail for a given media, if required */
268
299
  export async function generateThumbnail(file, mediaType, options) {
269
- let thumbnail;
270
- let originalImageDimensions;
271
- if (mediaType === 'image') {
272
- const { buffer, original } = await extractImageThumb(file);
273
- thumbnail = buffer.toString('base64');
274
- if (original.width && original.height) {
275
- originalImageDimensions = {
276
- width: original.width,
277
- height: original.height
278
- };
279
- }
280
- }
281
- else if (mediaType === 'video') {
282
- const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg');
283
- try {
284
- await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
285
- const buff = await fs.readFile(imgFilename);
286
- thumbnail = buff.toString('base64');
287
- await fs.unlink(imgFilename);
288
- }
289
- catch (err) {
290
- options.logger?.debug('could not generate video thumb: ' + err);
291
- }
292
- }
293
- return {
294
- thumbnail,
295
- originalImageDimensions
296
- };
300
+ let thumbnail;
301
+ let originalImageDimensions;
302
+ if (mediaType === 'image') {
303
+ const {
304
+ buffer,
305
+ original
306
+ } = await extractImageThumb(file);
307
+ thumbnail = buffer.toString('base64');
308
+ if (original.width && original.height) {
309
+ originalImageDimensions = {
310
+ width: original.width,
311
+ height: original.height
312
+ };
313
+ }
314
+ } else if (mediaType === 'video') {
315
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg');
316
+ try {
317
+ await extractVideoThumb(file, imgFilename, '00:00:00', {
318
+ width: 32,
319
+ height: 32
320
+ });
321
+ const buff = await fs.readFile(imgFilename);
322
+ thumbnail = buff.toString('base64');
323
+ await fs.unlink(imgFilename);
324
+ } catch (err) {
325
+ options.logger?.debug('could not generate video thumb: ' + err);
326
+ }
327
+ }
328
+ return {
329
+ thumbnail,
330
+ originalImageDimensions
331
+ };
297
332
  }
298
333
  export const getHttpStream = async (url, options = {}) => {
299
- const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' });
300
- return fetched.data;
334
+ const fetched = await axios.get(url.toString(), {
335
+ ...options,
336
+ responseType: 'stream'
337
+ });
338
+ return fetched.data;
301
339
  };
302
- export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
303
- const { stream, type } = await getStream(media, opts);
304
- logger?.debug('fetched media stream');
305
- const mediaKey = Crypto.randomBytes(32);
306
- const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
307
- const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
308
- const encFileWriteStream = createWriteStream(encFilePath);
309
- let originalFileStream;
310
- let originalFilePath;
311
- if (saveOriginalFileIfRequired) {
312
- originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
313
- originalFileStream = createWriteStream(originalFilePath);
314
- }
315
- let fileLength = 0;
316
- const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
317
- const hmac = Crypto.createHmac('sha256', macKey).update(iv);
318
- const sha256Plain = Crypto.createHash('sha256');
319
- const sha256Enc = Crypto.createHash('sha256');
320
- const onChunk = (buff) => {
321
- sha256Enc.update(buff);
322
- hmac.update(buff);
323
- encFileWriteStream.write(buff);
340
+ export const encryptedStream = async (media, mediaType, {
341
+ logger,
342
+ saveOriginalFileIfRequired,
343
+ opts
344
+ } = {}) => {
345
+ const {
346
+ stream,
347
+ type
348
+ } = await getStream(media, opts);
349
+ logger?.debug('fetched media stream');
350
+ const mediaKey = Crypto.randomBytes(32);
351
+ const {
352
+ cipherKey,
353
+ iv,
354
+ macKey
355
+ } = await getMediaKeys(mediaKey, mediaType);
356
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
357
+ const encFileWriteStream = createWriteStream(encFilePath);
358
+ let originalFileStream;
359
+ let originalFilePath;
360
+ if (saveOriginalFileIfRequired) {
361
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
362
+ originalFileStream = createWriteStream(originalFilePath);
363
+ }
364
+ let fileLength = 0;
365
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
366
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
367
+ const sha256Plain = Crypto.createHash('sha256');
368
+ const sha256Enc = Crypto.createHash('sha256');
369
+ const onChunk = buff => {
370
+ sha256Enc.update(buff);
371
+ hmac.update(buff);
372
+ encFileWriteStream.write(buff);
373
+ };
374
+ try {
375
+ for await (const data of stream) {
376
+ fileLength += data.length;
377
+ if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
378
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
379
+ data: {
380
+ media,
381
+ type
382
+ }
383
+ });
384
+ }
385
+ if (originalFileStream) {
386
+ if (!originalFileStream.write(data)) {
387
+ await once(originalFileStream, 'drain');
388
+ }
389
+ }
390
+ sha256Plain.update(data);
391
+ onChunk(aes.update(data));
392
+ }
393
+ onChunk(aes.final());
394
+ const mac = hmac.digest().slice(0, 10);
395
+ sha256Enc.update(mac);
396
+ const fileSha256 = sha256Plain.digest();
397
+ const fileEncSha256 = sha256Enc.digest();
398
+ encFileWriteStream.write(mac);
399
+ encFileWriteStream.end();
400
+ originalFileStream?.end?.();
401
+ stream.destroy();
402
+ logger?.debug('encrypted data successfully');
403
+ return {
404
+ mediaKey,
405
+ originalFilePath,
406
+ encFilePath,
407
+ mac,
408
+ fileEncSha256,
409
+ fileSha256,
410
+ fileLength
324
411
  };
412
+ } catch (error) {
413
+ // destroy all streams with error
414
+ encFileWriteStream.destroy();
415
+ originalFileStream?.destroy?.();
416
+ aes.destroy();
417
+ hmac.destroy();
418
+ sha256Plain.destroy();
419
+ sha256Enc.destroy();
420
+ stream.destroy();
325
421
  try {
326
- for await (const data of stream) {
327
- fileLength += data.length;
328
- if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
329
- throw new Boom(`content length exceeded when encrypting "${type}"`, {
330
- data: { media, type }
331
- });
332
- }
333
- if (originalFileStream) {
334
- if (!originalFileStream.write(data)) {
335
- await once(originalFileStream, 'drain');
336
- }
337
- }
338
- sha256Plain.update(data);
339
- onChunk(aes.update(data));
340
- }
341
- onChunk(aes.final());
342
- const mac = hmac.digest().slice(0, 10);
343
- sha256Enc.update(mac);
344
- const fileSha256 = sha256Plain.digest();
345
- const fileEncSha256 = sha256Enc.digest();
346
- encFileWriteStream.write(mac);
347
- encFileWriteStream.end();
348
- originalFileStream?.end?.();
349
- stream.destroy();
350
- logger?.debug('encrypted data successfully');
351
- return {
352
- mediaKey,
353
- originalFilePath,
354
- encFilePath,
355
- mac,
356
- fileEncSha256,
357
- fileSha256,
358
- fileLength
359
- };
360
- }
361
- catch (error) {
362
- // destroy all streams with error
363
- encFileWriteStream.destroy();
364
- originalFileStream?.destroy?.();
365
- aes.destroy();
366
- hmac.destroy();
367
- sha256Plain.destroy();
368
- sha256Enc.destroy();
369
- stream.destroy();
370
- try {
371
- await fs.unlink(encFilePath);
372
- if (originalFilePath) {
373
- await fs.unlink(originalFilePath);
374
- }
375
- }
376
- catch (err) {
377
- logger?.error({ err }, 'failed deleting tmp files');
378
- }
379
- throw error;
380
- }
422
+ await fs.unlink(encFilePath);
423
+ if (originalFilePath) {
424
+ await fs.unlink(originalFilePath);
425
+ }
426
+ } catch (err) {
427
+ logger?.error({
428
+ err
429
+ }, 'failed deleting tmp files');
430
+ }
431
+ throw error;
432
+ }
381
433
  };
382
434
  const DEF_HOST = 'mmg.whatsapp.net';
383
435
  const AES_CHUNK_SIZE = 16;
384
- const toSmallestChunkSize = (num) => {
385
- return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
436
+ const toSmallestChunkSize = num => {
437
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
386
438
  };
387
- export const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
388
- export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
389
- const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
390
- const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
391
- if (!downloadUrl) {
392
- throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
393
- }
394
- const keys = await getMediaKeys(mediaKey, type);
395
- return downloadEncryptedContent(downloadUrl, keys, opts);
439
+ export const getUrlFromDirectPath = directPath => `https://${DEF_HOST}${directPath}`;
440
+ export const downloadContentFromMessage = async ({
441
+ mediaKey,
442
+ directPath,
443
+ url
444
+ }, type, opts = {}) => {
445
+ const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
446
+ const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
447
+ if (!downloadUrl) {
448
+ throw new Boom('No valid media URL or directPath present in message', {
449
+ statusCode: 400
450
+ });
451
+ }
452
+ const keys = await getMediaKeys(mediaKey, type);
453
+ return downloadEncryptedContent(downloadUrl, keys, opts);
396
454
  };
397
455
  /**
398
456
  * Decrypts and downloads an AES256-CBC encrypted file given the keys.
399
457
  * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
400
458
  * */
401
- export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
402
- let bytesFetched = 0;
403
- let startChunk = 0;
404
- let firstBlockIsIV = false;
405
- // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
406
- if (startByte) {
407
- const chunk = toSmallestChunkSize(startByte || 0);
408
- if (chunk) {
409
- startChunk = chunk - AES_CHUNK_SIZE;
410
- bytesFetched = chunk;
411
- firstBlockIsIV = true;
412
- }
413
- }
414
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
415
- const headers = {
416
- ...(options?.headers || {}),
417
- Origin: DEFAULT_ORIGIN
418
- };
419
- if (startChunk || endChunk) {
420
- headers.Range = `bytes=${startChunk}-`;
421
- if (endChunk) {
422
- headers.Range += endChunk;
423
- }
424
- }
425
- // download the message
426
- const fetched = await getHttpStream(downloadUrl, {
427
- ...(options || {}),
428
- headers,
429
- maxBodyLength: Infinity,
430
- maxContentLength: Infinity
431
- });
432
- let remainingBytes = Buffer.from([]);
433
- let aes;
434
- const pushBytes = (bytes, push) => {
435
- if (startByte || endByte) {
436
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
437
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
438
- push(bytes.slice(start, end));
439
- bytesFetched += bytes.length;
459
+ export const downloadEncryptedContent = async (downloadUrl, {
460
+ cipherKey,
461
+ iv
462
+ }, {
463
+ startByte,
464
+ endByte,
465
+ options
466
+ } = {}) => {
467
+ let bytesFetched = 0;
468
+ let startChunk = 0;
469
+ let firstBlockIsIV = false;
470
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
471
+ if (startByte) {
472
+ const chunk = toSmallestChunkSize(startByte || 0);
473
+ if (chunk) {
474
+ startChunk = chunk - AES_CHUNK_SIZE;
475
+ bytesFetched = chunk;
476
+ firstBlockIsIV = true;
477
+ }
478
+ }
479
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
480
+ const headers = {
481
+ ...(options?.headers || {}),
482
+ Origin: DEFAULT_ORIGIN
483
+ };
484
+ if (startChunk || endChunk) {
485
+ headers.Range = `bytes=${startChunk}-`;
486
+ if (endChunk) {
487
+ headers.Range += endChunk;
488
+ }
489
+ }
490
+ // download the message
491
+ const fetched = await getHttpStream(downloadUrl, {
492
+ ...(options || {}),
493
+ headers,
494
+ maxBodyLength: Infinity,
495
+ maxContentLength: Infinity
496
+ });
497
+ let remainingBytes = Buffer.from([]);
498
+ let aes;
499
+ const pushBytes = (bytes, push) => {
500
+ if (startByte || endByte) {
501
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
502
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
503
+ push(bytes.slice(start, end));
504
+ bytesFetched += bytes.length;
505
+ } else {
506
+ push(bytes);
507
+ }
508
+ };
509
+ const output = new Transform({
510
+ transform(chunk, _, callback) {
511
+ let data = Buffer.concat([remainingBytes, chunk]);
512
+ const decryptLength = toSmallestChunkSize(data.length);
513
+ remainingBytes = data.slice(decryptLength);
514
+ data = data.slice(0, decryptLength);
515
+ if (!aes) {
516
+ let ivValue = iv;
517
+ if (firstBlockIsIV) {
518
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
519
+ data = data.slice(AES_CHUNK_SIZE);
440
520
  }
441
- else {
442
- push(bytes);
521
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
522
+ // if an end byte that is not EOF is specified
523
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
524
+ if (endByte) {
525
+ aes.setAutoPadding(false);
443
526
  }
444
- };
445
- const output = new Transform({
446
- transform(chunk, _, callback) {
447
- let data = Buffer.concat([remainingBytes, chunk]);
448
- const decryptLength = toSmallestChunkSize(data.length);
449
- remainingBytes = data.slice(decryptLength);
450
- data = data.slice(0, decryptLength);
451
- if (!aes) {
452
- let ivValue = iv;
453
- if (firstBlockIsIV) {
454
- ivValue = data.slice(0, AES_CHUNK_SIZE);
455
- data = data.slice(AES_CHUNK_SIZE);
456
- }
457
- aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
458
- // if an end byte that is not EOF is specified
459
- // stop auto padding (PKCS7) -- otherwise throws an error for decryption
460
- if (endByte) {
461
- aes.setAutoPadding(false);
462
- }
463
- }
464
- try {
465
- pushBytes(aes.update(data), b => this.push(b));
466
- callback();
467
- }
468
- catch (error) {
469
- callback(error);
470
- }
471
- },
472
- final(callback) {
473
- try {
474
- pushBytes(aes.final(), b => this.push(b));
475
- callback();
476
- }
477
- catch (error) {
478
- callback(error);
479
- }
480
- }
481
- });
482
- return fetched.pipe(output, { end: true });
527
+ }
528
+ try {
529
+ pushBytes(aes.update(data), b => this.push(b));
530
+ callback();
531
+ } catch (error) {
532
+ callback(error);
533
+ }
534
+ },
535
+ final(callback) {
536
+ try {
537
+ pushBytes(aes.final(), b => this.push(b));
538
+ callback();
539
+ } catch (error) {
540
+ callback(error);
541
+ }
542
+ }
543
+ });
544
+ return fetched.pipe(output, {
545
+ end: true
546
+ });
483
547
  };
484
548
  export function extensionForMediaMessage(message) {
485
- const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
486
- const type = Object.keys(message)[0];
487
- let extension;
488
- if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
489
- extension = '.jpeg';
490
- }
491
- else {
492
- const messageContent = message[type];
493
- extension = getExtension(messageContent.mimetype);
494
- }
495
- return extension;
549
+ const getExtension = mimetype => mimetype.split(';')[0]?.split('/')[1];
550
+ const type = Object.keys(message)[0];
551
+ let extension;
552
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
553
+ extension = '.jpeg';
554
+ } else {
555
+ const messageContent = message[type];
556
+ extension = getExtension(messageContent.mimetype);
557
+ }
558
+ return extension;
496
559
  }
497
- export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
498
- return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
499
- // send a query JSON to obtain the url & auth token to upload our media
500
- let uploadInfo = await refreshMediaConn(false);
501
- let urls;
502
- const hosts = [...customUploadHosts, ...uploadInfo.hosts];
503
- fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
504
- for (const { hostname } of hosts) {
505
- logger.debug(`uploading to "${hostname}"`);
506
- const auth = encodeURIComponent(uploadInfo.auth); // the auth token
507
- const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
508
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
509
- let result;
510
- try {
511
- const body = await axios.post(url, createReadStream(filePath), {
512
- ...options,
513
- maxRedirects: 0,
514
- headers: {
515
- ...(options.headers || {}),
516
- 'Content-Type': 'application/octet-stream',
517
- Origin: DEFAULT_ORIGIN
518
- },
519
- httpsAgent: fetchAgent,
520
- timeout: timeoutMs,
521
- responseType: 'json',
522
- maxBodyLength: Infinity,
523
- maxContentLength: Infinity
524
- });
525
- result = body.data;
526
- if (result?.url || result?.directPath) {
527
- urls = {
528
- mediaUrl: result.url,
529
- directPath: result.direct_path,
530
- meta_hmac: result.meta_hmac,
531
- fbid: result.fbid,
532
- ts: result.ts
533
- };
534
- break;
535
- }
536
- else {
537
- uploadInfo = await refreshMediaConn(true);
538
- throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
539
- }
540
- }
541
- catch (error) {
542
- if (axios.isAxiosError(error)) {
543
- result = error.response?.data;
544
- }
545
- const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
546
- logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
547
- }
560
+ export const getWAUploadToServer = ({
561
+ customUploadHosts,
562
+ fetchAgent,
563
+ logger,
564
+ options
565
+ }, refreshMediaConn) => {
566
+ return async (filePath, {
567
+ mediaType,
568
+ fileEncSha256B64,
569
+ timeoutMs
570
+ }) => {
571
+ // send a query JSON to obtain the url & auth token to upload our media
572
+ let uploadInfo = await refreshMediaConn(false);
573
+ let urls;
574
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
575
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
576
+ for (const {
577
+ hostname
578
+ } of hosts) {
579
+ logger.debug(`uploading to "${hostname}"`);
580
+ const auth = encodeURIComponent(uploadInfo.auth); // the auth token
581
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
582
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
583
+ let result;
584
+ try {
585
+ const body = await axios.post(url, createReadStream(filePath), {
586
+ ...options,
587
+ maxRedirects: 0,
588
+ headers: {
589
+ ...(options.headers || {}),
590
+ 'Content-Type': 'application/octet-stream',
591
+ Origin: DEFAULT_ORIGIN
592
+ },
593
+ httpsAgent: fetchAgent,
594
+ timeout: timeoutMs,
595
+ responseType: 'json',
596
+ maxBodyLength: Infinity,
597
+ maxContentLength: Infinity
598
+ });
599
+ result = body.data;
600
+ if (result?.url || result?.directPath) {
601
+ urls = {
602
+ mediaUrl: result.url,
603
+ directPath: result.direct_path,
604
+ meta_hmac: result.meta_hmac,
605
+ fbid: result.fbid,
606
+ ts: result.ts
607
+ };
608
+ break;
609
+ } else {
610
+ uploadInfo = await refreshMediaConn(true);
611
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
548
612
  }
549
- if (!urls) {
550
- throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
613
+ } catch (error) {
614
+ if (axios.isAxiosError(error)) {
615
+ result = error.response?.data;
551
616
  }
552
- return urls;
553
- };
617
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
618
+ logger.warn({
619
+ trace: error.stack,
620
+ uploadResult: result
621
+ }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
622
+ }
623
+ }
624
+ if (!urls) {
625
+ throw new Boom('Media upload failed on all hosts', {
626
+ statusCode: 500
627
+ });
628
+ }
629
+ return urls;
630
+ };
554
631
  };
555
- const getMediaRetryKey = (mediaKey) => {
556
- return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
632
+ const getMediaRetryKey = mediaKey => {
633
+ return hkdf(mediaKey, 32, {
634
+ info: 'WhatsApp Media Retry Notification'
635
+ });
557
636
  };
558
637
  /**
559
638
  * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
560
639
  */
561
640
  export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
562
- const recp = { stanzaId: key.id };
563
- const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
564
- const iv = Crypto.randomBytes(12);
565
- const retryKey = await getMediaRetryKey(mediaKey);
566
- const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
567
- const req = {
568
- tag: 'receipt',
569
- attrs: {
570
- id: key.id,
571
- to: jidNormalizedUser(meId),
572
- type: 'server-error'
573
- },
574
- content: [
575
- // this encrypt node is actually pretty useless
576
- // the media is returned even without this node
577
- // keeping it here to maintain parity with WA Web
578
- {
579
- tag: 'encrypt',
580
- attrs: {},
581
- content: [
582
- { tag: 'enc_p', attrs: {}, content: ciphertext },
583
- { tag: 'enc_iv', attrs: {}, content: iv }
584
- ]
585
- },
586
- {
587
- tag: 'rmr',
588
- attrs: {
589
- jid: key.remoteJid,
590
- from_me: (!!key.fromMe).toString(),
591
- // @ts-ignore
592
- participant: key.participant || undefined
593
- }
594
- }
595
- ]
596
- };
597
- return req;
641
+ const recp = {
642
+ stanzaId: key.id
643
+ };
644
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
645
+ const iv = Crypto.randomBytes(12);
646
+ const retryKey = await getMediaRetryKey(mediaKey);
647
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
648
+ const req = {
649
+ tag: 'receipt',
650
+ attrs: {
651
+ id: key.id,
652
+ to: jidNormalizedUser(meId),
653
+ type: 'server-error'
654
+ },
655
+ content: [
656
+ // this encrypt node is actually pretty useless
657
+ // the media is returned even without this node
658
+ // keeping it here to maintain parity with WA Web
659
+ {
660
+ tag: 'encrypt',
661
+ attrs: {},
662
+ content: [{
663
+ tag: 'enc_p',
664
+ attrs: {},
665
+ content: ciphertext
666
+ }, {
667
+ tag: 'enc_iv',
668
+ attrs: {},
669
+ content: iv
670
+ }]
671
+ }, {
672
+ tag: 'rmr',
673
+ attrs: {
674
+ jid: key.remoteJid,
675
+ from_me: (!!key.fromMe).toString(),
676
+ // @ts-ignore
677
+ participant: key.participant || undefined
678
+ }
679
+ }]
680
+ };
681
+ return req;
598
682
  };
599
- export const decodeMediaRetryNode = (node) => {
600
- const rmrNode = getBinaryNodeChild(node, 'rmr');
601
- const event = {
602
- key: {
603
- id: node.attrs.id,
604
- remoteJid: rmrNode.attrs.jid,
605
- fromMe: rmrNode.attrs.from_me === 'true',
606
- participant: rmrNode.attrs.participant
607
- }
608
- };
609
- const errorNode = getBinaryNodeChild(node, 'error');
610
- if (errorNode) {
611
- const errorCode = +errorNode.attrs.code;
612
- event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
613
- data: errorNode.attrs,
614
- statusCode: getStatusCodeForMediaRetry(errorCode)
615
- });
616
- }
617
- else {
618
- const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
619
- const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
620
- const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
621
- if (ciphertext && iv) {
622
- event.media = { ciphertext, iv };
623
- }
624
- else {
625
- event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
626
- }
627
- }
628
- return event;
683
+ export const decodeMediaRetryNode = node => {
684
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
685
+ const event = {
686
+ key: {
687
+ id: node.attrs.id,
688
+ remoteJid: rmrNode.attrs.jid,
689
+ fromMe: rmrNode.attrs.from_me === 'true',
690
+ participant: rmrNode.attrs.participant
691
+ }
692
+ };
693
+ const errorNode = getBinaryNodeChild(node, 'error');
694
+ if (errorNode) {
695
+ const errorCode = +errorNode.attrs.code;
696
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
697
+ data: errorNode.attrs,
698
+ statusCode: getStatusCodeForMediaRetry(errorCode)
699
+ });
700
+ } else {
701
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
702
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
703
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
704
+ if (ciphertext && iv) {
705
+ event.media = {
706
+ ciphertext,
707
+ iv
708
+ };
709
+ } else {
710
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', {
711
+ statusCode: 404
712
+ });
713
+ }
714
+ }
715
+ return event;
629
716
  };
630
- export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
631
- const retryKey = await getMediaRetryKey(mediaKey);
632
- const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
633
- return proto.MediaRetryNotification.decode(plaintext);
717
+ export const decryptMediaRetryData = async ({
718
+ ciphertext,
719
+ iv
720
+ }, mediaKey, msgId) => {
721
+ const retryKey = await getMediaRetryKey(mediaKey);
722
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
723
+ return proto.MediaRetryNotification.decode(plaintext);
634
724
  };
635
- export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
725
+ export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code];
636
726
  const MEDIA_RETRY_STATUS_MAP = {
637
- [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
638
- [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
639
- [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
640
- [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
727
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
728
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
729
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
730
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
641
731
  };
642
732
  //# sourceMappingURL=messages-media.js.map