ell-bail 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +341 -93
  2. package/engine-requirements.js +1 -2
  3. package/lib/Defaults/baileys-version.json +1 -1
  4. package/lib/Defaults/index.js +19 -2
  5. package/lib/Socket/chats.d.ts +215 -28
  6. package/lib/Socket/chats.js +155 -49
  7. package/lib/Socket/{luxu.d.ts → dugong.d.ts} +44 -41
  8. package/lib/Socket/dugong.js +484 -0
  9. package/lib/Socket/groups.js +1 -0
  10. package/lib/Socket/index.js +1 -0
  11. package/lib/Socket/messages-recv.js +5 -47
  12. package/lib/Socket/messages-send.d.ts +1 -1
  13. package/lib/Socket/messages-send.js +227 -320
  14. package/lib/Socket/newsletter.d.ts +130 -232
  15. package/lib/Socket/newsletter.js +101 -22
  16. package/lib/Socket/registration.d.ts +0 -1
  17. package/lib/Socket/registration.js +4 -627
  18. package/lib/Socket/socket.d.ts +1 -1
  19. package/lib/Socket/socket.js +66 -31
  20. package/lib/Types/Newsletter.d.ts +97 -86
  21. package/lib/Types/Newsletter.js +38 -32
  22. package/lib/Utils/auth-utils.js +0 -5
  23. package/lib/Utils/crypto.js +1 -18
  24. package/lib/Utils/generics.d.ts +0 -1
  25. package/lib/Utils/generics.js +64 -38
  26. package/lib/Utils/messages-media.js +145 -57
  27. package/lib/Utils/messages.js +54 -13
  28. package/lib/Utils/use-multi-file-auth-state.js +45 -6
  29. package/lib/Utils/validate-connection.js +89 -65
  30. package/lib/WABinary/constants.d.ts +27 -24
  31. package/lib/WABinary/encode.js +160 -123
  32. package/lib/WABinary/generic-utils.d.ts +2 -1
  33. package/lib/index.d.ts +1 -0
  34. package/lib/index.js +7 -2
  35. package/package.json +15 -7
  36. package/WAProto/index.js +0 -130309
  37. package/lib/KeyDB/BinarySearch.js +0 -18
  38. package/lib/KeyDB/KeyedDB.js +0 -164
  39. package/lib/KeyDB/index.js +0 -2
  40. package/lib/Signal/Group/x +0 -1
  41. package/lib/Socket/luxu.js +0 -550
@@ -3,16 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.encodeNewsletterMessage = exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
6
+ exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
8
  const axios_1 = __importDefault(require("axios"));
9
9
  const crypto_1 = require("crypto");
10
10
  const os_1 = require("os");
11
+ const fetch_1 = require("node-fetch")
11
12
  const WAProto_1 = require("../../WAProto");
12
13
  const baileys_version_json_1 = require("../Defaults/baileys-version.json");
13
14
  const Types_1 = require("../Types");
14
15
  const WABinary_1 = require("../WABinary");
15
- const { proto } = require('../../WAProto')
16
+ const baileysVersion = [2, 3000, 1027934701]
16
17
  const PLATFORM_MAP = {
17
18
  'aix': 'AIX',
18
19
  'darwin': 'Mac OS',
@@ -20,14 +21,16 @@ const PLATFORM_MAP = {
20
21
  'android': 'Android',
21
22
  'freebsd': 'FreeBSD',
22
23
  'openbsd': 'OpenBSD',
23
- 'sunos': 'Solaris'
24
+ 'sunos': 'Solaris',
25
+ 'linux': undefined,
26
+ 'haiku': undefined,
27
+ 'cygwin': undefined,
28
+ 'netbsd': undefined
24
29
  };
25
- exports.Browsers = {
26
- ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
27
- macOS: (browser) => ['Mac OS', browser, '14.4.1'],
28
- baileys: (browser) => ['Baileys', browser, '6.5.0'],
29
- windows: (browser) => ['Windows', browser, '10.0.22631'],
30
- appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
30
+ exports.Browsers = (browser) => {
31
+ const osName = PLATFORM_MAP[os_1.platform()] || 'Ubuntu';
32
+ const osRelease = os_1.release();
33
+ return [osName, browser, osRelease];
31
34
  };
32
35
 
33
36
  const getPlatformId = (browser) => {
@@ -173,7 +176,7 @@ const generateMessageIDV2 = (userId) => {
173
176
  };
174
177
  exports.generateMessageIDV2 = generateMessageIDV2;
175
178
  // generate a random ID to attach to a message
176
- const generateMessageID = () => '7EPPELI-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
179
+ const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
177
180
  exports.generateMessageID = generateMessageID;
178
181
  function bindWaitForEvent(ev, event) {
179
182
  return async (check, timeoutMs) => {
@@ -216,6 +219,55 @@ const printQRIfNecessaryListener = (ev, logger) => {
216
219
  });
217
220
  };
218
221
  exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
222
+ /**
223
+ * utility that fetches latest baileys version from the master branch.
224
+ * Use to ensure your WA connection is always on the latest version
225
+ */
226
+ const fetchLatestWaWebVersion = async (options = {}) => {
227
+ try {
228
+ const defaultHeaders = {
229
+ 'User-Agent':
230
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
231
+ 'Accept': '*/*'
232
+ }
233
+
234
+ const headers = { ...defaultHeaders, ...options.headers }
235
+
236
+ const response = await fetch_1('https://web.whatsapp.com/sw.js', {
237
+ method: 'GET',
238
+ headers
239
+ })
240
+
241
+ if (!response.ok) {
242
+ throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
243
+ }
244
+
245
+ const data = await response.text()
246
+ const regex = /"client_revision":\s*(\d+)/ // regex cukup begini untuk Node
247
+ const match = data.match(regex)
248
+
249
+ if (!match || !match[1]) {
250
+ return {
251
+ version: baileysVersion,
252
+ isLatest: false,
253
+ error: { message: 'Client revision not found' }
254
+ }
255
+ }
256
+
257
+ const clientRevision = match[1]
258
+ return {
259
+ version: [2, 3000, +clientRevision],
260
+ isLatest: true
261
+ }
262
+ } catch (error) {
263
+ return {
264
+ version: baileysVersion,
265
+ isLatest: false,
266
+ error
267
+ }
268
+ }
269
+ }
270
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
219
271
  /**
220
272
  * utility that fetches latest baileys version from the master branch.
221
273
  * Use to ensure your WA connection is always on the latest version
@@ -241,31 +293,6 @@ const fetchLatestBaileysVersion = async (options = {}) => {
241
293
  }
242
294
  };
243
295
  exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
244
- /**
245
- * A utility that fetches the latest web version of whatsapp.
246
- * Use to ensure your WA connection is always on the latest version
247
- */
248
- const fetchLatestWaWebVersion = async (options) => {
249
- try {
250
- const result = await axios_1.default.get('https://web.whatsapp.com/check-update?version=1&platform=web', {
251
- ...options,
252
- responseType: 'json'
253
- });
254
- const version = result.data.currentVersion.split('.');
255
- return {
256
- version: [+version[0], +version[1], +version[2]],
257
- isLatest: true
258
- };
259
- }
260
- catch (error) {
261
- return {
262
- version: baileys_version_json_1.version,
263
- isLatest: false,
264
- error
265
- };
266
- }
267
- };
268
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
269
296
  /** unique message tag prefix for MD clients */
270
297
  const generateMdTagPrefix = () => {
271
298
  const bytes = (0, crypto_1.randomBytes)(4);
@@ -390,8 +417,7 @@ function bytesToCrockford(buffer) {
390
417
  return crockford.join('');
391
418
  }
392
419
  exports.bytesToCrockford = bytesToCrockford;
393
-
394
- function encodeNewsletterMessage(message) {
395
- return proto.Message.encode(message).finish();
420
+ const encodeNewsletterMessage = (message) => {
421
+ return WAProto_1.proto.Message.encode(message).finish()
396
422
  }
397
423
  exports.encodeNewsletterMessage = encodeNewsletterMessage;
@@ -188,68 +188,138 @@ const mediaMessageSHA256B64 = (message) => {
188
188
  };
189
189
  exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
190
190
  async function getAudioDuration(buffer) {
191
- const musicMetadata = await import('music-metadata');
192
- let metadata;
193
- if (Buffer.isBuffer(buffer)) {
194
- metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
195
- }
196
- else if (typeof buffer === 'string') {
197
- const rStream = (0, fs_1.createReadStream)(buffer);
198
- try {
199
- metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
200
- }
201
- finally {
202
- rStream.destroy();
191
+ try {
192
+ const { PassThrough } = require('stream');
193
+ const ff = require('fluent-ffmpeg');
194
+
195
+ return await new Promise((resolve, reject) => {
196
+ const inputStream = new PassThrough();
197
+ inputStream.end(buffer);
198
+
199
+ ff(inputStream)
200
+ .ffprobe((err, data) => {
201
+ if (err) reject(err);
202
+ else resolve(data.format.duration);
203
+ });
204
+ });
205
+ } catch (error) {
206
+ const musicMetadata = await import('music-metadata');
207
+ let metadata;
208
+ if (Buffer.isBuffer(buffer)) {
209
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, {
210
+ duration: true
211
+ });
212
+ } else if (typeof buffer === 'string') {
213
+ const rStream = (0, fs_1.createReadStream)(buffer);
214
+ try {
215
+ metadata = await musicMetadata.parseStream(rStream, undefined, {
216
+ duration: true
217
+ });
218
+ } finally {
219
+ rStream.destroy();
220
+ }
221
+ } else {
222
+ metadata = await musicMetadata.parseStream(buffer, undefined, {
223
+ duration: true
224
+ });
203
225
  }
226
+ return metadata.format.duration;
204
227
  }
205
- else {
206
- metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
207
- }
208
- return metadata.format.duration;
209
228
  }
210
229
  exports.getAudioDuration = getAudioDuration;
211
- /**
212
- referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
213
- */
214
230
  async function getAudioWaveform(buffer, logger) {
215
231
  try {
216
- const audioDecode = (buffer) => import('audio-decode').then(({ default: audioDecode }) => audioDecode(buffer));
232
+ const { PassThrough } = require('stream');
233
+ const ff = require('fluent-ffmpeg');
234
+
217
235
  let audioData;
218
236
  if (Buffer.isBuffer(buffer)) {
219
237
  audioData = buffer;
238
+ } else if (typeof buffer === 'string') {
239
+ const rStream = require('fs').createReadStream(buffer);
240
+ audioData = await exports.toBuffer(rStream);
241
+ } else {
242
+ audioData = await exports.toBuffer(buffer);
220
243
  }
221
- else if (typeof buffer === 'string') {
222
- const rStream = (0, fs_1.createReadStream)(buffer);
223
- audioData = await (0, exports.toBuffer)(rStream);
224
- }
225
- else {
226
- audioData = await (0, exports.toBuffer)(buffer);
227
- }
228
- const audioBuffer = await audioDecode(audioData);
229
- const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
230
- const samples = 64; // Number of samples we want to have in our final data set
231
- const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
232
- const filteredData = [];
233
- for (let i = 0; i < samples; i++) {
234
- const blockStart = blockSize * i; // the location of the first sample in the block
235
- let sum = 0;
236
- for (let j = 0; j < blockSize; j++) {
237
- sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
238
- }
239
- filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
240
- }
241
- // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
242
- const multiplier = Math.pow(Math.max(...filteredData), -1);
243
- const normalizedData = filteredData.map((n) => n * multiplier);
244
- // Generate waveform like WhatsApp
245
- const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)));
246
- return waveform;
247
- }
248
- catch (e) {
249
- logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
244
+
245
+ return await new Promise((resolve, reject) => {
246
+ const inputStream = new PassThrough();
247
+ inputStream.end(audioData);
248
+ const chunks = [];
249
+ const bars = 64;
250
+
251
+ ff(inputStream)
252
+ .audioChannels(1)
253
+ .audioFrequency(16000)
254
+ .format('s16le')
255
+ .on('error', reject)
256
+ .on('end', () => {
257
+ const rawData = Buffer.concat(chunks);
258
+ const samples = rawData.length / 2;
259
+ const amplitudes = [];
260
+
261
+ for (let i = 0; i < samples; i++) {
262
+ amplitudes.push(Math.abs(rawData.readInt16LE(i * 2)) / 32768);
263
+ }
264
+
265
+ const blockSize = Math.floor(amplitudes.length / bars);
266
+ const avg = [];
267
+ for (let i = 0; i < bars; i++) {
268
+ const block = amplitudes.slice(i * blockSize, (i + 1) * blockSize);
269
+ avg.push(block.reduce((a, b) => a + b, 0) / block.length);
270
+ }
271
+
272
+ const max = Math.max(...avg);
273
+ const normalized = avg.map(v => Math.floor((v / max) * 100));
274
+ resolve(new Uint8Array(normalized));
275
+ })
276
+ .pipe()
277
+ .on('data', chunk => chunks.push(chunk));
278
+ });
279
+ } catch (e) {
280
+ logger?.debug(e);
250
281
  }
251
282
  }
252
283
  exports.getAudioWaveform = getAudioWaveform;
284
+ async function convertToOpusBuffer(buffer, logger) {
285
+ try {
286
+ const { PassThrough } = require('stream');
287
+ const ff = require('fluent-ffmpeg');
288
+
289
+ return await new Promise((resolve, reject) => {
290
+ const inStream = new PassThrough();
291
+ const outStream = new PassThrough();
292
+ const chunks = [];
293
+ inStream.end(buffer);
294
+
295
+ ff(inStream)
296
+ .noVideo()
297
+ .audioCodec('libopus')
298
+ .format('ogg')
299
+ .audioBitrate('48k')
300
+ .audioChannels(1)
301
+ .audioFrequency(48000)
302
+ .outputOptions([
303
+ '-vn',
304
+ '-b:a 64k',
305
+ '-ac 2',
306
+ '-ar 48000',
307
+ '-map_metadata', '-1',
308
+ '-application', 'voip'
309
+ ])
310
+ .on('error', reject)
311
+ .on('end', () => resolve(Buffer.concat(chunks)))
312
+ .pipe(outStream, {
313
+ end: true
314
+ });
315
+ outStream.on('data', c => chunks.push(c));
316
+ });
317
+ } catch (e) {
318
+ logger?.debug(e);
319
+ throw e;
320
+ }
321
+ }
322
+ exports.convertToOpusBuffer = convertToOpusBuffer;
253
323
  const toReadable = (buffer) => {
254
324
  const readable = new stream_1.Readable({ read: () => { } });
255
325
  readable.push(buffer);
@@ -362,15 +432,28 @@ const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequi
362
432
  }
363
433
  };
364
434
  exports.prepareStream = prepareStream;
365
- const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
435
+ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
366
436
  const { stream, type } = await (0, exports.getStream)(media, opts);
367
- logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
437
+
438
+ let finalStream = stream;
439
+ if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
440
+ try {
441
+ const buffer = await (0, exports.toBuffer)(stream);
442
+ const opusBuffer = await exports.convertToOpusBuffer(buffer, logger);
443
+ finalStream = (0, exports.toReadable)(opusBuffer);
444
+ } catch (error) {
445
+ const { stream: newStream } = await (0, exports.getStream)(media, opts);
446
+ finalStream = newStream;
447
+ }
448
+ }
449
+
368
450
  const mediaKey = Crypto.randomBytes(32);
369
451
  const { cipherKey, iv, macKey } = getMediaKeys(mediaKey, mediaType);
370
452
  const encWriteStream = new stream_1.Readable({ read: () => { } });
371
453
  let bodyPath;
372
454
  let writeStream;
373
455
  let didSaveToTmpPath = false;
456
+
374
457
  if (type === 'file') {
375
458
  bodyPath = media.url;
376
459
  }
@@ -379,13 +462,15 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
379
462
  writeStream = (0, fs_1.createWriteStream)(bodyPath);
380
463
  didSaveToTmpPath = true;
381
464
  }
465
+
382
466
  let fileLength = 0;
383
467
  const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
384
468
  let hmac = Crypto.createHmac('sha256', macKey).update(iv);
385
469
  let sha256Plain = Crypto.createHash('sha256');
386
470
  let sha256Enc = Crypto.createHash('sha256');
471
+
387
472
  try {
388
- for await (const data of stream) {
473
+ for await (const data of finalStream) {
389
474
  fileLength += data.length;
390
475
  if (type === 'remote'
391
476
  && (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
@@ -394,6 +479,7 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
394
479
  data: { media, type }
395
480
  });
396
481
  }
482
+
397
483
  sha256Plain = sha256Plain.update(data);
398
484
  if (writeStream) {
399
485
  if (!writeStream.write(data)) {
@@ -402,16 +488,18 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
402
488
  }
403
489
  onChunk(aes.update(data));
404
490
  }
491
+
405
492
  onChunk(aes.final());
406
493
  const mac = hmac.digest().slice(0, 10);
407
494
  sha256Enc = sha256Enc.update(mac);
408
495
  const fileSha256 = sha256Plain.digest();
409
496
  const fileEncSha256 = sha256Enc.digest();
497
+
410
498
  encWriteStream.push(mac);
411
499
  encWriteStream.push(null);
412
500
  writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
413
- stream.destroy();
414
- logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
501
+ finalStream.destroy();
502
+
415
503
  return {
416
504
  mediaKey,
417
505
  encWriteStream,
@@ -424,24 +512,24 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
424
512
  };
425
513
  }
426
514
  catch (error) {
427
- // destroy all streams with error
428
515
  encWriteStream.destroy();
429
516
  writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
430
517
  aes.destroy();
431
518
  hmac.destroy();
432
519
  sha256Plain.destroy();
433
520
  sha256Enc.destroy();
434
- stream.destroy();
521
+ finalStream.destroy();
522
+
435
523
  if (didSaveToTmpPath) {
436
524
  try {
437
525
  await fs_1.promises.unlink(bodyPath);
438
526
  }
439
527
  catch (err) {
440
- logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
441
528
  }
442
529
  }
443
530
  throw error;
444
531
  }
532
+
445
533
  function onChunk(buff) {
446
534
  sha256Enc = sha256Enc.update(buff);
447
535
  hmac = hmac.update(buff);
@@ -74,30 +74,62 @@ const prepareWAMessageMedia = async (message, options) => {
74
74
  }
75
75
  }
76
76
  if (!mediaType) {
77
- throw new boom_1.Boom('Invalid media type', { statusCode: 400 });
77
+ throw new boom_1.Boom('Invalid media type', {
78
+ statusCode: 400
79
+ });
78
80
  }
81
+
79
82
  const uploadData = {
80
83
  ...message,
81
- ...(message.annotations, {
84
+ ...(message.annotations ? {
82
85
  annotations: message.annotations
86
+ } : {
87
+ annotations: [
88
+ {
89
+ polygonVertices: [
90
+ {
91
+ x: 60.71664810180664,
92
+ y: -36.39784622192383
93
+ },
94
+ {
95
+ x: -16.710189819335938,
96
+ y: 49.263675689697266
97
+ },
98
+ {
99
+ x: -56.585853576660156,
100
+ y: 37.85963439941406
101
+ },
102
+ {
103
+ x: 20.840980529785156,
104
+ y: -47.80188751220703
105
+ }
106
+ ],
107
+ newsletter: {
108
+ newsletterJid: "120363420249672073@newsletter",
109
+ serverMessageId: 0,
110
+ newsletterName: "kyuu ilysm",
111
+ contentType: "UPDATE",
112
+ }
113
+ }
114
+ ]
83
115
  }),
84
116
  media: message[mediaType]
85
117
  };
86
118
  delete uploadData[mediaType];
87
- // check if cacheable + generate cache key
88
119
  const cacheableKey = typeof uploadData.media === 'object' &&
89
120
  ('url' in uploadData.media) &&
90
121
  !!uploadData.media.url &&
91
122
  !!options.mediaCache && (
92
- // generate the key
93
123
  mediaType + ':' + uploadData.media.url.toString());
124
+
94
125
  if (mediaType === 'document' && !uploadData.fileName) {
95
126
  uploadData.fileName = 'file';
96
127
  }
128
+
97
129
  if (!uploadData.mimetype) {
98
130
  uploadData.mimetype = MIMETYPE_MAP[mediaType];
99
131
  }
100
- // check for cache hit
132
+
101
133
  if (cacheableKey) {
102
134
  const mediaBuff = options.mediaCache.get(cacheableKey);
103
135
  if (mediaBuff) {
@@ -108,19 +140,28 @@ const prepareWAMessageMedia = async (message, options) => {
108
140
  return obj;
109
141
  }
110
142
  }
143
+
111
144
  const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
112
145
  const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
113
146
  (typeof uploadData['jpegThumbnail'] === 'undefined');
114
147
  const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
115
148
  const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
116
149
  const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
117
- const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
150
+
151
+ const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, opusConverted } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
118
152
  logger,
119
153
  saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
120
- opts: options.options
154
+ opts: options.options,
155
+ isPtt: uploadData.ptt,
156
+ forceOpus: (mediaType === "audio" && uploadData.mimetype && uploadData.mimetype.includes('opus'))
121
157
  });
122
- // url safe Base64 encode the SHA256 hash of the body
158
+
159
+ if (mediaType === 'audio' && opusConverted) {
160
+ uploadData.mimetype = 'audio/ogg; codecs=opus';
161
+ }
162
+
123
163
  const fileEncSha256B64 = (options.newsletter ? fileSha256 : fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
164
+
124
165
  const [{ mediaUrl, directPath, handle }] = await Promise.all([
125
166
  (async () => {
126
167
  const result = await options.upload(encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs });
@@ -147,10 +188,6 @@ const prepareWAMessageMedia = async (message, options) => {
147
188
  uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(bodyPath, logger);
148
189
  logger === null || logger === void 0 ? void 0 : logger.debug('processed waveform');
149
190
  }
150
- if (requiresWaveformProcessing) {
151
- uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(bodyPath, logger);
152
- logger === null || logger === void 0 ? void 0 : logger.debug('processed waveform');
153
- }
154
191
  if (requiresAudioBackground) {
155
192
  uploadData.backgroundArgb = await assertColor(options.backgroundColor);
156
193
  logger === null || logger === void 0 ? void 0 : logger.debug('computed backgroundColor audio status');
@@ -165,12 +202,13 @@ const prepareWAMessageMedia = async (message, options) => {
165
202
  if (!Buffer.isBuffer(encWriteStream)) {
166
203
  encWriteStream.destroy();
167
204
  }
168
- // remove tmp files
205
+
169
206
  if (didSaveToTmpPath && bodyPath) {
170
207
  await fs_1.promises.unlink(bodyPath);
171
208
  logger === null || logger === void 0 ? void 0 : logger.debug('removed tmp files');
172
209
  }
173
210
  });
211
+
174
212
  const obj = Types_1.WAProto.Message.fromObject({
175
213
  [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
176
214
  url: handle ? undefined : mediaUrl,
@@ -184,14 +222,17 @@ const prepareWAMessageMedia = async (message, options) => {
184
222
  media: undefined
185
223
  })
186
224
  });
225
+
187
226
  if (uploadData.ptv) {
188
227
  obj.ptvMessage = obj.videoMessage;
189
228
  delete obj.videoMessage;
190
229
  }
230
+
191
231
  if (cacheableKey) {
192
232
  logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
193
233
  options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
194
234
  }
235
+
195
236
  return obj;
196
237
  };
197
238
  exports.prepareWAMessageMedia = prepareWAMessageMedia;
@@ -1,11 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useMultiFileAuthState = void 0;
4
+ const async_mutex_1 = require("async-mutex");
4
5
  const promises_1 = require("fs/promises");
5
6
  const path_1 = require("path");
6
7
  const WAProto_1 = require("../../WAProto");
7
8
  const auth_utils_1 = require("./auth-utils");
8
9
  const generics_1 = require("./generics");
10
+ const fileLocks = new Map();
11
+ const getFileLock = (path) => {
12
+ let mutex = fileLocks.get(path);
13
+ if (!mutex) {
14
+ mutex = new async_mutex_1.Mutex();
15
+ fileLocks.set(path, mutex);
16
+ }
17
+ return mutex;
18
+ };
9
19
  /**
10
20
  * stores the full authentication state in a single folder.
11
21
  * Far more efficient than singlefileauthstate
@@ -14,13 +24,31 @@ const generics_1 = require("./generics");
14
24
  * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
15
25
  * */
16
26
  const useMultiFileAuthState = async (folder) => {
17
- const writeData = (data, file) => {
18
- return (0, promises_1.writeFile)((0, path_1.join)(folder, fixFileName(file)), JSON.stringify(data, generics_1.BufferJSON.replacer));
27
+ const writeData = async (data, file) => {
28
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
29
+ const mutex = getFileLock(filePath);
30
+ return mutex.acquire().then(async (release) => {
31
+ try {
32
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
33
+ }
34
+ finally {
35
+ release();
36
+ }
37
+ });
19
38
  };
20
39
  const readData = async (file) => {
21
40
  try {
22
- const data = await (0, promises_1.readFile)((0, path_1.join)(folder, fixFileName(file)), { encoding: 'utf-8' });
23
- return JSON.parse(data, generics_1.BufferJSON.reviver);
41
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
42
+ const mutex = getFileLock(filePath);
43
+ return await mutex.acquire().then(async (release) => {
44
+ try {
45
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
46
+ return JSON.parse(data, generics_1.BufferJSON.reviver);
47
+ }
48
+ finally {
49
+ release();
50
+ }
51
+ });
24
52
  }
25
53
  catch (error) {
26
54
  return null;
@@ -28,7 +56,18 @@ const useMultiFileAuthState = async (folder) => {
28
56
  };
29
57
  const removeData = async (file) => {
30
58
  try {
31
- await (0, promises_1.unlink)((0, path_1.join)(folder, fixFileName(file)));
59
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
60
+ const mutex = getFileLock(filePath);
61
+ return mutex.acquire().then(async (release) => {
62
+ try {
63
+ await (0, promises_1.unlink)(filePath);
64
+ }
65
+ catch (_a) {
66
+ }
67
+ finally {
68
+ release();
69
+ }
70
+ });
32
71
  }
33
72
  catch (_a) {
34
73
  }
@@ -72,7 +111,7 @@ const useMultiFileAuthState = async (folder) => {
72
111
  }
73
112
  }
74
113
  },
75
- saveCreds: () => {
114
+ saveCreds: async () => {
76
115
  return writeData(creds, 'creds.json');
77
116
  }
78
117
  };