angularsockets 1.4.3 → 1.4.5

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.
@@ -60,7 +60,6 @@ const WAProto_1 = require("../../WAProto");
60
60
  const Defaults_1 = require("../Defaults");
61
61
  const WABinary_1 = require("../WABinary");
62
62
  const crypto_1 = require("./crypto");
63
- const streamToBuffer = require("./streamToBuffer")
64
63
  const generics_1 = require("./generics");
65
64
  const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
66
65
  const getImageProcessingLibrary = async () => {
@@ -350,74 +349,138 @@ const mediaMessageSHA256B64 = (message) => {
350
349
  };
351
350
  exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
352
351
  async function getAudioDuration(buffer) {
353
- const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
354
- let metadata;
355
- const options = {
356
- duration: true
357
- };
358
- if (Buffer.isBuffer(buffer)) {
359
- metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
360
- }
361
- else if (typeof buffer === 'string') {
362
- metadata = await musicMetadata.parseFile(buffer, options);
363
- }
364
- else {
365
- metadata = await musicMetadata.parseStream(buffer, undefined, options);
366
- }
367
- return metadata.format.duration;
368
- }
369
- const toBuffer = async (stream) => {
370
- const chunks = [];
371
- for await (const chunk of stream) {
372
- chunks.push(chunk);
352
+ try {
353
+ const { PassThrough } = require('stream');
354
+ const ff = require('fluent-ffmpeg');
355
+
356
+ return await new Promise((resolve, reject) => {
357
+ const inputStream = new PassThrough();
358
+ inputStream.end(buffer);
359
+
360
+ ff(inputStream)
361
+ .ffprobe((err, data) => {
362
+ if (err) reject(err);
363
+ else resolve(data.format.duration);
364
+ });
365
+ });
366
+ } catch (error) {
367
+ const musicMetadata = await import('music-metadata');
368
+ let metadata;
369
+ if (Buffer.isBuffer(buffer)) {
370
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, {
371
+ duration: true
372
+ });
373
+ } else if (typeof buffer === 'string') {
374
+ const rStream = (0, fs_1.createReadStream)(buffer);
375
+ try {
376
+ metadata = await musicMetadata.parseStream(rStream, undefined, {
377
+ duration: true
378
+ });
379
+ } finally {
380
+ rStream.destroy();
381
+ }
382
+ } else {
383
+ metadata = await musicMetadata.parseStream(buffer, undefined, {
384
+ duration: true
385
+ });
386
+ }
387
+ return metadata.format.duration;
373
388
  }
374
- stream.destroy();
375
- return Buffer.concat(chunks);
376
- };
377
- exports.toBuffer = toBuffer;
378
-
389
+ }
390
+ exports.getAudioDuration = getAudioDuration;
379
391
  async function getAudioWaveform(buffer, logger) {
380
392
  try {
381
- const { default: decoder } = await eval('import("audio-decode")')
382
- let audioData
383
-
393
+ const { PassThrough } = require('stream');
394
+ const ff = require('fluent-ffmpeg');
395
+
396
+ let audioData;
384
397
  if (Buffer.isBuffer(buffer)) {
385
- audioData = buffer
398
+ audioData = buffer;
386
399
  } else if (typeof buffer === 'string') {
387
- const rStream = fs_1.createReadStream(buffer)
388
- audioData = await streamToBuffer(rStream)
400
+ const rStream = require('fs').createReadStream(buffer);
401
+ audioData = await exports.toBuffer(rStream);
389
402
  } else {
390
- audioData = await streamToBuffer(buffer)
403
+ audioData = await exports.toBuffer(buffer);
391
404
  }
392
405
 
393
- const audioBuffer = await decoder(audioData)
394
- const rawData = audioBuffer.getChannelData(0)
395
- const samples = 64
396
- const blockSize = Math.floor(rawData.length / samples)
397
- const filteredData = []
398
-
399
- // === Versi TS style: ambil RATA-RATA amplitudo biar halus ===
400
- for (let i = 0; i < samples; i++) {
401
- let sum = 0
402
- const blockStart = blockSize * i
403
- for (let j = 0; j < blockSize; j++) {
404
- sum += Math.abs(rawData[blockStart + j] || 0)
405
- }
406
- filteredData.push(sum / blockSize)
407
- }
408
-
409
- // Normalisasi
410
- const multiplier = Math.pow(Math.max(...filteredData) || 1, -1)
411
- const normalizedData = filteredData.map((n) => n * multiplier)
412
-
413
- // Hasil akhir: Uint8Array rentang 0–100
414
- return new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)))
406
+ return await new Promise((resolve, reject) => {
407
+ const inputStream = new PassThrough();
408
+ inputStream.end(audioData);
409
+ const chunks = [];
410
+ const bars = 64;
411
+
412
+ ff(inputStream)
413
+ .audioChannels(1)
414
+ .audioFrequency(16000)
415
+ .format('s16le')
416
+ .on('error', reject)
417
+ .on('end', () => {
418
+ const rawData = Buffer.concat(chunks);
419
+ const samples = rawData.length / 2;
420
+ const amplitudes = [];
421
+
422
+ for (let i = 0; i < samples; i++) {
423
+ amplitudes.push(Math.abs(rawData.readInt16LE(i * 2)) / 32768);
424
+ }
425
+
426
+ const blockSize = Math.floor(amplitudes.length / bars);
427
+ const avg = [];
428
+ for (let i = 0; i < bars; i++) {
429
+ const block = amplitudes.slice(i * blockSize, (i + 1) * blockSize);
430
+ avg.push(block.reduce((a, b) => a + b, 0) / block.length);
431
+ }
432
+
433
+ const max = Math.max(...avg);
434
+ const normalized = avg.map(v => Math.floor((v / max) * 100));
435
+ resolve(new Uint8Array(normalized));
436
+ })
437
+ .pipe()
438
+ .on('data', chunk => chunks.push(chunk));
439
+ });
415
440
  } catch (e) {
416
- logger?.debug?.('⚠️ Failed to generate waveform: ' + e)
417
- return new Uint8Array(64).fill(0)
441
+ logger?.debug(e);
418
442
  }
419
443
  }
420
-
444
+ exports.getAudioWaveform = getAudioWaveform;
445
+ async function convertToOpusBuffer(buffer, logger) {
446
+ try {
447
+ const { PassThrough } = require('stream');
448
+ const ff = require('fluent-ffmpeg');
449
+
450
+ return await new Promise((resolve, reject) => {
451
+ const inStream = new PassThrough();
452
+ const outStream = new PassThrough();
453
+ const chunks = [];
454
+ inStream.end(buffer);
455
+
456
+ ff(inStream)
457
+ .noVideo()
458
+ .audioCodec('libopus')
459
+ .format('ogg')
460
+ .audioBitrate('48k')
461
+ .audioChannels(1)
462
+ .audioFrequency(48000)
463
+ .outputOptions([
464
+ '-vn',
465
+ '-b:a 64k',
466
+ '-ac 2',
467
+ '-ar 48000',
468
+ '-map_metadata', '-1',
469
+ '-application', 'voip'
470
+ ])
471
+ .on('error', reject)
472
+ .on('end', () => resolve(Buffer.concat(chunks)))
473
+ .pipe(outStream, {
474
+ end: true
475
+ });
476
+ outStream.on('data', c => chunks.push(c));
477
+ });
478
+ } catch (e) {
479
+ logger?.debug(e);
480
+ throw e;
481
+ }
482
+ }
483
+ exports.convertToOpusBuffer = convertToOpusBuffer;
421
484
  const toReadable = (buffer) => {
422
485
  const readable = new stream_1.Readable({ read: () => { } });
423
486
  readable.push(buffer);
@@ -425,6 +488,15 @@ const toReadable = (buffer) => {
425
488
  return readable;
426
489
  };
427
490
  exports.toReadable = toReadable;
491
+ const toBuffer = async (stream) => {
492
+ const chunks = [];
493
+ for await (const chunk of stream) {
494
+ chunks.push(chunk);
495
+ }
496
+ stream.destroy();
497
+ return Buffer.concat(chunks);
498
+ };
499
+ exports.toBuffer = toBuffer;
428
500
  const getStream = async (item, opts) => {
429
501
  if (Buffer.isBuffer(item)) {
430
502
  return { stream: (0, exports.toReadable)(item), type: 'buffer' };
@@ -534,34 +606,51 @@ const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequi
534
606
  }
535
607
  };
536
608
  exports.prepareStream = prepareStream;
537
- const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
609
+ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
538
610
  const { stream, type } = await (0, exports.getStream)(media, opts);
539
- logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
611
+ logger?.debug('fetched media stream');
612
+
613
+ let finalStream = stream;
614
+
615
+ // Tambahan untuk konversi audio jadi Opus (PTT)
616
+ if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
617
+ try {
618
+ const buffer = await (0, exports.toBuffer)(stream);
619
+ const opusBuffer = await exports.convertToOpusBuffer(buffer, logger);
620
+ finalStream = (0, exports.toReadable)(opusBuffer);
621
+ logger?.debug('converted audio to Opus');
622
+ } catch (error) {
623
+ logger?.error('failed to convert audio to Opus, fallback to original stream');
624
+ const { stream: newStream } = await (0, exports.getStream)(media, opts);
625
+ finalStream = newStream;
626
+ }
627
+ }
628
+
540
629
  const mediaKey = Crypto.randomBytes(32);
541
630
  const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
542
631
  const encWriteStream = new stream_1.Readable({ read: () => { } });
543
632
  let bodyPath;
544
633
  let writeStream;
545
634
  let didSaveToTmpPath = false;
635
+
546
636
  if (type === 'file') {
547
637
  bodyPath = media.url;
548
- }
549
- else if (saveOriginalFileIfRequired) {
638
+ } else if (saveOriginalFileIfRequired) {
550
639
  bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
551
640
  writeStream = (0, fs_1.createWriteStream)(bodyPath);
552
641
  didSaveToTmpPath = true;
553
642
  }
643
+
554
644
  let fileLength = 0;
555
645
  const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
556
646
  let hmac = Crypto.createHmac('sha256', macKey).update(iv);
557
647
  let sha256Plain = Crypto.createHash('sha256');
558
648
  let sha256Enc = Crypto.createHash('sha256');
649
+
559
650
  try {
560
- for await (const data of stream) {
651
+ for await (const data of finalStream) {
561
652
  fileLength += data.length;
562
- if (type === 'remote'
563
- && (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
564
- && fileLength + data.length > opts.maxContentLength) {
653
+ if (type === 'remote' && (opts?.maxContentLength) && fileLength + data.length > opts.maxContentLength) {
565
654
  throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
566
655
  data: { media, type }
567
656
  });
@@ -574,16 +663,20 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
574
663
  }
575
664
  onChunk(aes.update(data));
576
665
  }
666
+
577
667
  onChunk(aes.final());
578
668
  const mac = hmac.digest().slice(0, 10);
579
669
  sha256Enc = sha256Enc.update(mac);
580
670
  const fileSha256 = sha256Plain.digest();
581
671
  const fileEncSha256 = sha256Enc.digest();
672
+
582
673
  encWriteStream.push(mac);
583
674
  encWriteStream.push(null);
584
- writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
585
- stream.destroy();
586
- logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
675
+ writeStream?.end();
676
+ finalStream.destroy();
677
+
678
+ logger?.debug('encrypted data successfully');
679
+
587
680
  return {
588
681
  mediaKey,
589
682
  encWriteStream,
@@ -594,25 +687,25 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
594
687
  fileLength,
595
688
  didSaveToTmpPath
596
689
  };
597
- }
598
- catch (error) {
690
+ } catch (error) {
599
691
  encWriteStream.destroy();
600
- writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
692
+ writeStream?.destroy();
601
693
  aes.destroy();
602
694
  hmac.destroy();
603
695
  sha256Plain.destroy();
604
696
  sha256Enc.destroy();
605
- stream.destroy();
697
+ finalStream.destroy();
698
+
606
699
  if (didSaveToTmpPath) {
607
700
  try {
608
701
  await fs_1.promises.unlink(bodyPath);
609
- }
610
- catch (err) {
611
- logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
702
+ } catch (err) {
703
+ logger?.error({ err }, 'failed to save to tmp path');
612
704
  }
613
705
  }
614
706
  throw error;
615
707
  }
708
+
616
709
  function onChunk(buff) {
617
710
  sha256Enc = sha256Enc.update(buff);
618
711
  hmac = hmac.update(buff);
@@ -884,4 +977,4 @@ const MEDIA_RETRY_STATUS_MAP = {
884
977
  };
885
978
  function __importStar(arg0) {
886
979
  throw new Error('Function not implemented.');
887
- }
980
+ }
@@ -72,4 +72,9 @@ type DownloadMediaMessageContext = {
72
72
  export declare const downloadMediaMessage: <Type extends "buffer" | "stream">(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer<ArrayBufferLike> : Transform>;
73
73
  /** Checks whether the given message is a media message; if it is returns the inner content */
74
74
  export declare const assertMediaContent: (content: proto.IMessage | null | undefined) => proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage;
75
+ export declare const toJid: (id: string) => string;
76
+ export declare const getSenderLid: (msg: WAMessage) => {
77
+ jid: string;
78
+ lid: string;
79
+ };
75
80
  export {};
@@ -1,3 +1,4 @@
1
+ /* modified by alip*/
1
2
  "use strict";
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -79,6 +80,38 @@ const prepareWAMessageMedia = async (message, options) => {
79
80
  }
80
81
  const uploadData = {
81
82
  ...message,
83
+ ...(message.annotations ? {
84
+ annotations: message.annotations
85
+ } : {
86
+ annotations: [
87
+ {
88
+ polygonVertices: [
89
+ {
90
+ x: 60.71664810180664,
91
+ y: -36.39784622192383
92
+ },
93
+ {
94
+ x: -16.710189819335938,
95
+ y: 49.263675689697266
96
+ },
97
+ {
98
+ x: -56.585853576660156,
99
+ y: 37.85963439941406
100
+ },
101
+ {
102
+ x: 20.840980529785156,
103
+ y: -47.80188751220703
104
+ }
105
+ ],
106
+ newsletter: {
107
+ newsletterJid: "120363403865450077@newsletter",
108
+ serverMessageId: 0,
109
+ newsletterName: "Alisa AI",
110
+ contentType: "UPDATE",
111
+ }
112
+ }
113
+ ]
114
+ }),
82
115
  media: message[mediaType]
83
116
  };
84
117
  delete uploadData[mediaType];
@@ -106,19 +139,27 @@ const prepareWAMessageMedia = async (message, options) => {
106
139
  return obj;
107
140
  }
108
141
  }
109
- const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
142
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
110
143
  const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
111
144
  (typeof uploadData['jpegThumbnail'] === 'undefined');
112
145
  const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
113
146
  const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
114
147
  const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
115
- const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
148
+
149
+ 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, {
116
150
  logger,
117
151
  saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
118
- opts: options.options
152
+ opts: options.options,
153
+ isPtt: uploadData.ptt,
154
+ forceOpus: (mediaType === "audio" && uploadData.mimetype && uploadData.mimetype.includes('opus'))
119
155
  });
120
- // url safe Base64 encode the SHA256 hash of the body
156
+
157
+ if (mediaType === 'audio' && opusConverted) {
158
+ uploadData.mimetype = 'audio/ogg; codecs=opus';
159
+ }
160
+
121
161
  const fileEncSha256B64 = (options.newsletter ? fileSha256 : fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
162
+
122
163
  const [{ mediaUrl, directPath, handle }] = await Promise.all([
123
164
  (async () => {
124
165
  const result = await options.upload(encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs });
@@ -184,10 +225,21 @@ const prepareWAMessageMedia = async (message, options) => {
184
225
  media: undefined
185
226
  })
186
227
  });
228
+
229
+ // START PERBAIKAN PTV UNTUK CHANNEL
187
230
  if (uploadData.ptv) {
188
- obj.ptvMessage = obj.videoMessage;
189
- delete obj.videoMessage;
231
+ if (options.newsletter) {
232
+ // Untuk Channel (Newsletter), set flag viewOnce di videoMessage
233
+ obj.videoMessage = obj.videoMessage;
234
+ obj.videoMessage.viewOnce = true;
235
+ } else {
236
+ // Untuk chat biasa, gunakan ptvMessage
237
+ obj.ptvMessage = obj.videoMessage;
238
+ delete obj.videoMessage;
239
+ }
190
240
  }
241
+ // END PERBAIKAN PTV UNTUK CHANNEL
242
+
191
243
  if (cacheableKey) {
192
244
  logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
193
245
  options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
@@ -379,7 +431,7 @@ const generateWAMessageContent = async (message, options) => {
379
431
  }
380
432
  }
381
433
  else if ('ptv' in message && message.ptv) {
382
- const { videoMessage } = await (0, exports.prepareWAMessageMedia)({ video: message.video }, options);
434
+ const { videoMessage } = await (0, exports.prepareWAMessageMedia)({ video: message.video, ptv: true }, options); // <-- Perbaikan ptv: true
383
435
  m.ptvMessage = videoMessage;
384
436
  }
385
437
  else if ('product' in message) {
@@ -1028,3 +1080,22 @@ const assertMediaContent = (content) => {
1028
1080
  return mediaContent;
1029
1081
  };
1030
1082
  exports.assertMediaContent = assertMediaContent;
1083
+
1084
+ const toJid = (id) => {
1085
+ if (!id)
1086
+ return '';
1087
+ if (id.endsWith('@lid'))
1088
+ return id.replace('@lid', '@s.whatsapp.net');
1089
+ if (id.includes('@'))
1090
+ return id;
1091
+ return `${id}@s.whatsapp.net`;
1092
+ };
1093
+ exports.toJid = toJid;
1094
+ const getSenderLid = (message) => {
1095
+ const sender = message.key.participant || message.key.remoteJid;
1096
+ const user = (0, WABinary_1.jidDecode)(sender)?.user || '';
1097
+ const lid = (0, WABinary_1.jidEncode)(user, 'lid');
1098
+ console.log('sender lid:', lid);
1099
+ return { jid: sender, lid };
1100
+ };
1101
+ exports.getSenderLid = getSenderLid;
@@ -130,6 +130,25 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
130
130
  }
131
131
  }
132
132
  const content = (0, messages_1.normalizeMessageContent)(message.message);
133
+ const senderId = message.key.participant || message.key.remoteJid;
134
+ if ((0, WABinary_1.isLidUser)(senderId)) {
135
+ const jid = (0, WABinary_1.lidToJid)(senderId);
136
+ if (message.key.participant) {
137
+ message.key.participant = jid;
138
+ }
139
+ else {
140
+ message.key.remoteJid = jid;
141
+ }
142
+ }
143
+ const mJids = content && content.contextInfo && content.contextInfo.mentionedJid ? content.contextInfo.mentionedJid : [];
144
+ for (let i = 0; i < mJids.length; i++) {
145
+ if ((0, WABinary_1.isLidUser)(mJids[i])) {
146
+ mJids[i] = (0, WABinary_1.lidToJid)(mJids[i]);
147
+ }
148
+ }
149
+ if (content && content.contextInfo && content.contextInfo.participant && (0, WABinary_1.isLidUser)(content.contextInfo.participant)) {
150
+ content.contextInfo.participant = (0, WABinary_1.lidToJid)(content.contextInfo.participant);
151
+ }
133
152
  // unarchive chat if it's a real message, or someone reacted to our message
134
153
  // and we've the unarchive chats setting on
135
154
  if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))