@wppconnect-team/wppconnect 2.4.0 → 2.4.6

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.
@@ -0,0 +1,426 @@
1
+ "use strict";
2
+ /*
3
+ * This file is part of WPPConnect.
4
+ *
5
+ * WPPConnect is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU Lesser General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ *
10
+ * WPPConnect is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ * GNU Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public License
16
+ * along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
17
+ */
18
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ var desc = Object.getOwnPropertyDescriptor(m, k);
21
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
22
+ desc = { enumerable: true, get: function() { return m[k]; } };
23
+ }
24
+ Object.defineProperty(o, k2, desc);
25
+ }) : (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k;
27
+ o[k2] = m[k];
28
+ }));
29
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
30
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
31
+ }) : function(o, v) {
32
+ o["default"] = v;
33
+ });
34
+ var __importStar = (this && this.__importStar) || (function () {
35
+ var ownKeys = function(o) {
36
+ ownKeys = Object.getOwnPropertyNames || function (o) {
37
+ var ar = [];
38
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
39
+ return ar;
40
+ };
41
+ return ownKeys(o);
42
+ };
43
+ return function (mod) {
44
+ if (mod && mod.__esModule) return mod;
45
+ var result = {};
46
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
47
+ __setModuleDefault(result, mod);
48
+ return result;
49
+ };
50
+ })();
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ exports.CallLayer = void 0;
53
+ const fs = __importStar(require("fs"));
54
+ const helpers_1 = require("../helpers");
55
+ const controls_layer_1 = require("./controls.layer");
56
+ /**
57
+ * Voice and video calls.
58
+ *
59
+ * Audio injection, capture and recording are armed for a single call: the
60
+ * active one, or the next one to start. They are released when that call ends,
61
+ * so enable them again before each {@link CallLayer.call},
62
+ * {@link CallLayer.acceptCall} or {@link CallLayer.joinCallLink}.
63
+ *
64
+ * Audio injection only replaces the microphone: video uses the real camera.
65
+ * Without a camera, or without the camera permission (Chrome asks for it and
66
+ * the call drops), accept with `video: false` or start the browser with
67
+ * `--use-fake-ui-for-media-stream` and `--use-fake-device-for-media-stream`.
68
+ *
69
+ * Errors keep the `code` sent by WA-JS (e.g. `call_not_found`,
70
+ * `call_start_in_progress`, `invalid_call_link`).
71
+ */
72
+ class CallLayer extends controls_layer_1.ControlsLayer {
73
+ page;
74
+ constructor(page, session, options) {
75
+ super(page, session, options);
76
+ this.page = page;
77
+ }
78
+ /**
79
+ * Runs a WA-JS call function that resolves to a CallModel and returns a
80
+ * plain snapshot of it
81
+ */
82
+ async startCall(method, args, audioInjection) {
83
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ method, args, audioInjection }) => {
84
+ if (audioInjection) {
85
+ WPP.call.enableAudioInjection(true);
86
+ }
87
+ return Promise.resolve(WPP.call[method](...args)).then((call) => {
88
+ if (!call) {
89
+ return null;
90
+ }
91
+ const wid = (w) => w ? w._serialized || w.toString() : undefined;
92
+ return {
93
+ id: call.id,
94
+ peerJid: wid(call.peerJid),
95
+ groupJid: wid(call.groupJid),
96
+ isGroup: !!call.isGroup,
97
+ isVideo: !!call.isVideo,
98
+ isOutgoing: !!call.outgoing,
99
+ isCallLink: !!call.isCallLink,
100
+ };
101
+ });
102
+ }, { method, args, audioInjection: !!audioInjection });
103
+ }
104
+ /**
105
+ * Starts a voice or video call
106
+ *
107
+ * @category Call
108
+ * @example
109
+ * ```javascript
110
+ * const call = await client.call('5511999999999@c.us', { audioInjection: true });
111
+ * await client.playCallAudio('./welcome.mp3');
112
+ * ```
113
+ * @param to Contact ID
114
+ * @returns The started call, or null if WhatsApp did not create it in time
115
+ */
116
+ async call(to, options = {}) {
117
+ return this.startCall('offer', [to, { isVideo: !!options.isVideo }], options.audioInjection);
118
+ }
119
+ /**
120
+ * Starts a group call, from a group ID or a list of contacts
121
+ *
122
+ * @category Call
123
+ * @example
124
+ * ```javascript
125
+ * await client.callGroup(['5511999999999@c.us', '5511988888888@c.us']);
126
+ * ```
127
+ */
128
+ async callGroup(to, options = {}) {
129
+ return this.startCall('offerGroup', [to, { isVideo: !!options.isVideo }], options.audioInjection);
130
+ }
131
+ /**
132
+ * Accepts an incoming call
133
+ *
134
+ * Video calls are accepted with the camera on by default, which needs a
135
+ * camera (see {@link CallLayer}). Pass `video: false` to answer with audio only.
136
+ *
137
+ * @category Call
138
+ * @example
139
+ * ```javascript
140
+ * client.onIncomingCall(async (call) => {
141
+ * await client.acceptCall(call.id, { video: false, audioInjection: true });
142
+ * });
143
+ * ```
144
+ * @param callId Call ID, defaults to the ringing call
145
+ */
146
+ async acceptCall(callId, options = {}) {
147
+ const { audioInjection, ...acceptOptions } = options;
148
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ callId, acceptOptions, audioInjection }) => {
149
+ if (audioInjection) {
150
+ WPP.call.enableAudioInjection(true);
151
+ }
152
+ return WPP.call.accept(callId || undefined, acceptOptions);
153
+ }, { callId, acceptOptions, audioInjection: !!audioInjection });
154
+ }
155
+ /**
156
+ * Rejects a call received via WhatsApp
157
+ *
158
+ * @category Call
159
+ * @example
160
+ * ```javascript
161
+ * client.onIncomingCall((call) => client.rejectCall(call.id));
162
+ * ```
163
+ * @param callId Call ID, defaults to the ringing call
164
+ */
165
+ async rejectCall(callId) {
166
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ callId }) => WPP.call.rejectCall(callId || undefined), { callId });
167
+ }
168
+ /**
169
+ * Ends a call
170
+ *
171
+ * @category Call
172
+ * @example
173
+ * ```javascript
174
+ * await client.endCall();
175
+ * ```
176
+ * @param callId Call ID, defaults to the active call
177
+ */
178
+ async endCall(callId) {
179
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ callId }) => WPP.call.end(callId || undefined), { callId });
180
+ }
181
+ /**
182
+ * Returns the active call, if any
183
+ *
184
+ * @category Call
185
+ * @example
186
+ * ```javascript
187
+ * const call = await client.getActiveCall();
188
+ * ```
189
+ */
190
+ async getActiveCall() {
191
+ return this.startCall('getActiveCall', []);
192
+ }
193
+ /**
194
+ * Returns the details of a call reported by WhatsApp
195
+ * (duration, participants, ...)
196
+ *
197
+ * @category Call
198
+ * @example
199
+ * ```javascript
200
+ * const info = await client.getCallInfo();
201
+ * ```
202
+ * @param callId Call ID, defaults to the active call
203
+ */
204
+ async getCallInfo(callId) {
205
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ callId }) => WPP.call.getCallInfo(callId || undefined), { callId });
206
+ }
207
+ /**
208
+ * Mutes or unmutes the microphone in a call
209
+ *
210
+ * @category Call
211
+ * @example
212
+ * ```javascript
213
+ * await client.setCallMute(true);
214
+ * ```
215
+ */
216
+ async setCallMute(muted, callId) {
217
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ muted, callId }) => WPP.call.setMute(muted, callId || undefined), { muted, callId });
218
+ }
219
+ /**
220
+ * Turns the camera on or off in a call, the camera must be available
221
+ * (see {@link CallLayer})
222
+ *
223
+ * @category Call
224
+ * @example
225
+ * ```javascript
226
+ * await client.setCallVideo(false);
227
+ * ```
228
+ */
229
+ async setCallVideo(enabled, callId) {
230
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ enabled, callId }) => WPP.call.setVideoEnabled(enabled, callId || undefined), { enabled, callId });
231
+ }
232
+ /**
233
+ * Sends a reaction in a call, an empty string clears it
234
+ *
235
+ * @category Call
236
+ * @example
237
+ * ```javascript
238
+ * await client.sendCallReaction('👍');
239
+ * ```
240
+ */
241
+ async sendCallReaction(emoji, callId) {
242
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ emoji, callId }) => WPP.call.sendReaction(emoji, callId || undefined), { emoji, callId });
243
+ }
244
+ /**
245
+ * Raises or lowers the hand in a group call
246
+ *
247
+ * @category Call
248
+ * @example
249
+ * ```javascript
250
+ * await client.raiseCallHand(true);
251
+ * ```
252
+ */
253
+ async raiseCallHand(raised, callId) {
254
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ raised, callId }) => WPP.call.raiseHand(raised, callId || undefined), { raised, callId });
255
+ }
256
+ /**
257
+ * Creates a call link
258
+ *
259
+ * @category Call
260
+ * @example
261
+ * ```javascript
262
+ * const link = await client.createCallLink({ isVideo: true });
263
+ * // https://call.whatsapp.com/video/...
264
+ * ```
265
+ */
266
+ async createCallLink(options = {}) {
267
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ options }) => WPP.call.createCallLink(options), { options });
268
+ }
269
+ /**
270
+ * Joins a call from a call link
271
+ *
272
+ * @category Call
273
+ * @example
274
+ * ```javascript
275
+ * await client.joinCallLink('https://call.whatsapp.com/voice/xxxx');
276
+ * ```
277
+ */
278
+ async joinCallLink(link, options = {}) {
279
+ return this.startCall('joinCallLink', [link, { isVideo: options.isVideo }], options.audioInjection);
280
+ }
281
+ /**
282
+ * Replaces the microphone of the next (or active) call with audio sent by
283
+ * {@link CallLayer.playCallAudio} and {@link CallLayer.pushCallAudio}.
284
+ * Call it before starting or accepting each call.
285
+ *
286
+ * @category Call
287
+ * @example
288
+ * ```javascript
289
+ * await client.enableCallAudioInjection();
290
+ * await client.acceptCall();
291
+ * ```
292
+ */
293
+ async enableCallAudioInjection(enabled = true) {
294
+ await (0, helpers_1.evaluateWithErrorCode)(this.page, ({ enabled }) => WPP.call.enableAudioInjection(enabled), { enabled });
295
+ }
296
+ /**
297
+ * @category Call
298
+ * @returns Whether audio injection is enabled
299
+ */
300
+ async isCallAudioInjectionEnabled() {
301
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, () => WPP.call.isAudioInjectionEnabled());
302
+ }
303
+ /**
304
+ * Plays an audio file in the call, resolving when it finishes or is stopped
305
+ *
306
+ * @category Call
307
+ * @example
308
+ * ```javascript
309
+ * await client.playCallAudio('./welcome.mp3');
310
+ * await client.playCallAudio('https://example.com/welcome.ogg', { volume: 0.5 });
311
+ * await client.playCallAudio(fs.readFileSync('./welcome.wav'));
312
+ * ```
313
+ * @param source File path, http(s) URL, data URL or Buffer with the file content
314
+ */
315
+ async playCallAudio(source, options = {}) {
316
+ const dataUrl = await this.toAudioDataUrl(source);
317
+ await (0, helpers_1.evaluateWithErrorCode)(this.page, ({ dataUrl, options }) => WPP.call.playAudio(dataUrl, options), { dataUrl, options });
318
+ }
319
+ /**
320
+ * Streams raw PCM audio to the call (TTS, voice bots).
321
+ * Chunks are played back to back.
322
+ *
323
+ * @category Call
324
+ * @example
325
+ * ```javascript
326
+ * // pcm: Buffer with 16-bit little-endian mono samples at 16 kHz
327
+ * const queued = await client.pushCallAudio(pcm);
328
+ * ```
329
+ * @param pcm Int16 little-endian mono samples, as Buffer, Int16Array or base64
330
+ * @returns Seconds of audio still queued
331
+ */
332
+ async pushCallAudio(pcm, options = {}) {
333
+ let samples;
334
+ if (typeof pcm === 'string') {
335
+ samples = pcm;
336
+ }
337
+ else if (Buffer.isBuffer(pcm)) {
338
+ samples = pcm.toString('base64');
339
+ }
340
+ else {
341
+ samples = Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength).toString('base64');
342
+ }
343
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, ({ samples, options }) => WPP.call.pushAudio(samples, options), { samples, options });
344
+ }
345
+ /**
346
+ * Stops the audio being played or streamed to the call
347
+ *
348
+ * @category Call
349
+ * @example
350
+ * ```javascript
351
+ * await client.stopCallAudio();
352
+ * ```
353
+ */
354
+ async stopCallAudio() {
355
+ await (0, helpers_1.evaluateWithErrorCode)(this.page, () => WPP.call.stopAudio());
356
+ }
357
+ /**
358
+ * Starts recording the next (or active) call.
359
+ * Call it before starting or accepting each call.
360
+ *
361
+ * @category Call
362
+ * @example
363
+ * ```javascript
364
+ * await client.startCallRecording({ source: 'both' });
365
+ * ```
366
+ */
367
+ async startCallRecording(options = {}) {
368
+ await (0, helpers_1.evaluateWithErrorCode)(this.page, ({ options }) => WPP.call.startRecording(options), { options });
369
+ }
370
+ /**
371
+ * @category Call
372
+ * @returns Whether a call is being recorded
373
+ */
374
+ async isCallRecording() {
375
+ return (0, helpers_1.evaluateWithErrorCode)(this.page, () => WPP.call.isRecording());
376
+ }
377
+ /**
378
+ * Stops the recording. It still works after the call has ended.
379
+ *
380
+ * @category Call
381
+ * @example
382
+ * ```javascript
383
+ * client.onCallEnded(async () => {
384
+ * await client.stopCallRecording('./call.wav');
385
+ * });
386
+ * ```
387
+ * @param filePath Where to save the WAV file (optional)
388
+ * @returns WAV file content (16 kHz, mono, 16-bit)
389
+ */
390
+ async stopCallRecording(filePath) {
391
+ const base64 = await (0, helpers_1.evaluateWithErrorCode)(this.page, () => WPP.call.stopRecording({ format: 'base64' }));
392
+ const wav = Buffer.from(base64, 'base64');
393
+ if (filePath) {
394
+ await fs.promises.writeFile(filePath, wav);
395
+ }
396
+ return wav;
397
+ }
398
+ /**
399
+ * Converts a file path, URL or Buffer to a data URL, so the page does not
400
+ * need to reach the file (and is not blocked by its CSP)
401
+ */
402
+ async toAudioDataUrl(source) {
403
+ if (Buffer.isBuffer(source)) {
404
+ if (source.length) {
405
+ return `data:application/octet-stream;base64,${source.toString('base64')}`;
406
+ }
407
+ }
408
+ else if (source.startsWith('data:')) {
409
+ return source;
410
+ }
411
+ else {
412
+ const data = (await (0, helpers_1.downloadFileToBase64)(source, [
413
+ /^audio\//,
414
+ /^video\//,
415
+ 'application/octet-stream',
416
+ ])) || (await (0, helpers_1.fileToBase64)(source));
417
+ if (data) {
418
+ return data;
419
+ }
420
+ }
421
+ throw Object.assign(new Error('Empty or invalid audio source'), {
422
+ code: 'empty_file',
423
+ });
424
+ }
425
+ }
426
+ exports.CallLayer = CallLayer;
@@ -2,7 +2,7 @@ import { BackendEventName, MsgKey } from '@wppconnect/wa-js/dist/whatsapp';
2
2
  import { StreamInfo, StreamMode } from '@wppconnect/wa-js/dist/whatsapp/enums';
3
3
  import { Page } from 'puppeteer';
4
4
  import { CreateConfig } from '../../config/create-config';
5
- import { Ack, Chat, IncomingCall, LiveLocation, Message, ParticipantEvent, PresenceEvent, Wid } from '../model';
5
+ import { Ack, CallAudioFrame, CallAudioFrameOptions, CallEndedEvent, CallEvent, CallMuteStateEvent, CallStateChangedEvent, CallVideoStateEvent, Chat, IncomingCall, LiveLocation, Message, ParticipantEvent, PresenceEvent, Wid } from '../model';
6
6
  import { SocketState, SocketStream } from '../model/enum';
7
7
  import { InterfaceMode } from '../model/enum/interface-mode';
8
8
  import { InterfaceState } from '../model/enum/interface-state';
@@ -26,6 +26,10 @@ export declare class ListenerLayer extends ProfileLayer {
26
26
  private listenerEmitter;
27
27
  constructor(page: Page, session?: string, options?: CreateConfig);
28
28
  protected afterPageScriptInjected(): Promise<void>;
29
+ /**
30
+ * Enables or disables the call audio capture used by {@link onCallAudioFrame}
31
+ */
32
+ private setCallAudioCapture;
29
33
  /**
30
34
  * Register the event and create a disposable object to stop the listening
31
35
  * @param event Name of event
@@ -178,6 +182,115 @@ export declare class ListenerLayer extends ProfileLayer {
178
182
  onIncomingCall(callback: (call: IncomingCall) => any): {
179
183
  dispose: () => void;
180
184
  };
185
+ /**
186
+ * @event Listens to calls started by this session
187
+ * @category Call
188
+ * @example
189
+ * ```javascript
190
+ * client.onCallOutgoing((call) => console.log('Calling', call.peerJid));
191
+ * ```
192
+ * @returns Disposable object to stop listening
193
+ */
194
+ onCallOutgoing(callback: (call: CallEvent) => any): {
195
+ dispose: () => void;
196
+ };
197
+ /**
198
+ * @event Listens to calls ringing on the other side
199
+ * @category Call
200
+ * @example
201
+ * ```javascript
202
+ * client.onCallRinging((call) => console.log('Ringing', call.id));
203
+ * ```
204
+ * @returns Disposable object to stop listening
205
+ */
206
+ onCallRinging(callback: (call: CallEvent) => any): {
207
+ dispose: () => void;
208
+ };
209
+ /**
210
+ * @event Listens to calls being connected, incoming or outgoing
211
+ * @category Call
212
+ * @example
213
+ * ```javascript
214
+ * client.onCallAccepted(() => client.playCallAudio('./welcome.mp3'));
215
+ * ```
216
+ * @returns Disposable object to stop listening
217
+ */
218
+ onCallAccepted(callback: (call: CallEvent) => any): {
219
+ dispose: () => void;
220
+ };
221
+ /**
222
+ * @event Listens to every call state change
223
+ * @category Call
224
+ * @example
225
+ * ```javascript
226
+ * client.onCallStateChanged((call) => console.log(call.id, call.stateName));
227
+ * ```
228
+ * @returns Disposable object to stop listening
229
+ */
230
+ onCallStateChanged(callback: (call: CallStateChangedEvent) => any): {
231
+ dispose: () => void;
232
+ };
233
+ /**
234
+ * @event Listens to calls ending, with the result and duration
235
+ * @category Call
236
+ * @example
237
+ * ```javascript
238
+ * client.onCallEnded((call) => {
239
+ * console.log(call.resultName, call.duration);
240
+ * });
241
+ * ```
242
+ * @returns Disposable object to stop listening
243
+ */
244
+ onCallEnded(callback: (call: CallEndedEvent) => any): {
245
+ dispose: () => void;
246
+ };
247
+ /**
248
+ * @event Listens to microphone mute changes of the call participants
249
+ * @category Call
250
+ * @example
251
+ * ```javascript
252
+ * client.onCallMuteState((state) => console.log(state.peerMuted));
253
+ * ```
254
+ * @returns Disposable object to stop listening
255
+ */
256
+ onCallMuteState(callback: (state: CallMuteStateEvent) => any): {
257
+ dispose: () => void;
258
+ };
259
+ /**
260
+ * @event Listens to camera changes of the call participants
261
+ * @category Call
262
+ * @example
263
+ * ```javascript
264
+ * client.onCallVideoState((state) => console.log(state.stateName));
265
+ * ```
266
+ * @returns Disposable object to stop listening
267
+ */
268
+ onCallVideoState(callback: (state: CallVideoStateEvent) => any): {
269
+ dispose: () => void;
270
+ };
271
+ /**
272
+ * Listens to the call audio, in frames of 60 ms of 16 kHz mono PCM
273
+ * (about 16 frames per second for each side).
274
+ *
275
+ * The capture is only enabled while there is a listener, and is armed again
276
+ * for each call. Register it before the call starts to get every frame.
277
+ *
278
+ * @event Listens to the call audio
279
+ * @category Call
280
+ * @example
281
+ * ```javascript
282
+ * client.onCallAudioFrame(
283
+ * (frame) => {
284
+ * const pcm = Buffer.from(frame.samples, 'base64'); // Int16 LE
285
+ * },
286
+ * { source: 'remote' }
287
+ * );
288
+ * ```
289
+ * @returns Disposable object to stop listening
290
+ */
291
+ onCallAudioFrame(callback: (frame: CallAudioFrame) => any, options?: CallAudioFrameOptions): {
292
+ dispose: () => void;
293
+ };
181
294
  /**
182
295
  * Listens to presence changed, by default, it will be triggered for active chats only or contacts subscribed (see {@link subscribePresence})
183
296
  * @event Listens to presence changed