@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,10 @@
1
+ import { Page } from 'puppeteer';
2
+ /**
3
+ * Runs `pageFunction(arg)` in the page and keeps the `code` (and the other
4
+ * serializable fields) of a thrown WPPError, which a plain `page.evaluate`
5
+ * drops, leaving only the message.
6
+ *
7
+ * `pageFunction` is sent as source, so it must not reference anything outside
8
+ * of itself, and `arg` must be JSON serializable.
9
+ */
10
+ export declare function evaluateWithErrorCode<A, R>(page: Page, pageFunction: (arg: A) => R | Promise<R>, arg?: A): Promise<R>;
@@ -0,0 +1,49 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.evaluateWithErrorCode = evaluateWithErrorCode;
20
+ /**
21
+ * Runs `pageFunction(arg)` in the page and keeps the `code` (and the other
22
+ * serializable fields) of a thrown WPPError, which a plain `page.evaluate`
23
+ * drops, leaving only the message.
24
+ *
25
+ * `pageFunction` is sent as source, so it must not reference anything outside
26
+ * of itself, and `arg` must be JSON serializable.
27
+ */
28
+ async function evaluateWithErrorCode(page, pageFunction, arg) {
29
+ const result = await page.evaluate(`(async () => {
30
+ try {
31
+ const value = await (${pageFunction.toString()})(${JSON.stringify(arg === undefined ? null : arg)});
32
+ return { ok: true, value };
33
+ } catch (e) {
34
+ const error = { message: (e && e.message) || String(e) };
35
+ if (e && typeof e === 'object') {
36
+ for (const key of Object.keys(e)) {
37
+ try {
38
+ error[key] = JSON.parse(JSON.stringify(e[key]));
39
+ } catch (_) {}
40
+ }
41
+ }
42
+ return { ok: false, error };
43
+ }
44
+ })()`);
45
+ if (!result.ok) {
46
+ throw Object.assign(new Error(result.error.message), result.error);
47
+ }
48
+ return result.value;
49
+ }
@@ -13,5 +13,13 @@ export declare enum ExposedFn {
13
13
  onInterfaceChange = "onInterfaceChange",
14
14
  onPresenceChanged = "onPresenceChanged",
15
15
  onLiveLocation = "onLiveLocation",
16
- onBackendEvent = "onBackendEvent"
16
+ onBackendEvent = "onBackendEvent",
17
+ onCallOutgoing = "onCallOutgoing",
18
+ onCallRinging = "onCallRinging",
19
+ onCallAccepted = "onCallAccepted",
20
+ onCallStateChanged = "onCallStateChanged",
21
+ onCallEnded = "onCallEnded",
22
+ onCallMuteState = "onCallMuteState",
23
+ onCallVideoState = "onCallVideoState",
24
+ onCallAudioFrame = "onCallAudioFrame"
17
25
  }
@@ -34,4 +34,12 @@ var ExposedFn;
34
34
  ExposedFn["onPresenceChanged"] = "onPresenceChanged";
35
35
  ExposedFn["onLiveLocation"] = "onLiveLocation";
36
36
  ExposedFn["onBackendEvent"] = "onBackendEvent";
37
+ ExposedFn["onCallOutgoing"] = "onCallOutgoing";
38
+ ExposedFn["onCallRinging"] = "onCallRinging";
39
+ ExposedFn["onCallAccepted"] = "onCallAccepted";
40
+ ExposedFn["onCallStateChanged"] = "onCallStateChanged";
41
+ ExposedFn["onCallEnded"] = "onCallEnded";
42
+ ExposedFn["onCallMuteState"] = "onCallMuteState";
43
+ ExposedFn["onCallVideoState"] = "onCallVideoState";
44
+ ExposedFn["onCallAudioFrame"] = "onCallAudioFrame";
37
45
  })(ExposedFn || (exports.ExposedFn = ExposedFn = {}));
@@ -5,3 +5,4 @@ export { stickerSelect, resizeImg } from './select-sticker';
5
5
  export { scrapeImg } from './scrape-img-qr';
6
6
  export { scrapeLogin } from './scrape-login';
7
7
  export { evaluateAndReturn } from './evaluate-and-return';
8
+ export { evaluateWithErrorCode } from './evaluate-with-error-code';
@@ -16,7 +16,7 @@
16
16
  * along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.evaluateAndReturn = exports.scrapeLogin = exports.scrapeImg = exports.resizeImg = exports.stickerSelect = exports.downloadFileToBase64 = exports.base64MimeType = exports.fileToBase64 = void 0;
19
+ exports.evaluateWithErrorCode = exports.evaluateAndReturn = exports.scrapeLogin = exports.scrapeImg = exports.resizeImg = exports.stickerSelect = exports.downloadFileToBase64 = exports.base64MimeType = exports.fileToBase64 = void 0;
20
20
  var file_to_base64_1 = require("./file-to-base64");
21
21
  Object.defineProperty(exports, "fileToBase64", { enumerable: true, get: function () { return file_to_base64_1.fileToBase64; } });
22
22
  var base64_mimetype_1 = require("./base64-mimetype");
@@ -32,3 +32,5 @@ var scrape_login_1 = require("./scrape-login");
32
32
  Object.defineProperty(exports, "scrapeLogin", { enumerable: true, get: function () { return scrape_login_1.scrapeLogin; } });
33
33
  var evaluate_and_return_1 = require("./evaluate-and-return");
34
34
  Object.defineProperty(exports, "evaluateAndReturn", { enumerable: true, get: function () { return evaluate_and_return_1.evaluateAndReturn; } });
35
+ var evaluate_with_error_code_1 = require("./evaluate-with-error-code");
36
+ Object.defineProperty(exports, "evaluateWithErrorCode", { enumerable: true, get: function () { return evaluate_with_error_code_1.evaluateWithErrorCode; } });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Page function that forwards incoming calls to `window.onIncomingCall`.
3
+ *
4
+ * It runs in the browser, so it must not use anything from its module scope.
5
+ *
6
+ * The native VoIP stack does not add incoming calls to `CallStore` (so `add`
7
+ * is never triggered), so WA-JS with call events is listened through
8
+ * `call.incoming_call`. The payload starts from the
9
+ * same JSON that `page.exposeFunction` sent for the `CallModel` (every
10
+ * serializable field is kept) and fills the `IncomingCall` fields on top.
11
+ */
12
+ export declare function listenIncomingCall(): void;
@@ -0,0 +1,98 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.listenIncomingCall = listenIncomingCall;
20
+ /**
21
+ * Page function that forwards incoming calls to `window.onIncomingCall`.
22
+ *
23
+ * It runs in the browser, so it must not use anything from its module scope.
24
+ *
25
+ * The native VoIP stack does not add incoming calls to `CallStore` (so `add`
26
+ * is never triggered), so WA-JS with call events is listened through
27
+ * `call.incoming_call`. The payload starts from the
28
+ * same JSON that `page.exposeFunction` sent for the `CallModel` (every
29
+ * serializable field is kept) and fills the `IncomingCall` fields on top.
30
+ */
31
+ function listenIncomingCall() {
32
+ const w = window;
33
+ if (typeof w.onIncomingCall !== 'function' || w.onIncomingCall.exposed) {
34
+ return;
35
+ }
36
+ if (typeof WPP.call?.enableAudioInjection !== 'function') {
37
+ w.WAPI.onIncomingCall(w.onIncomingCall);
38
+ w.onIncomingCall.exposed = true;
39
+ return;
40
+ }
41
+ const wid = (value) => value ? value._serialized || value.toString() : null;
42
+ // Minified private fields ($Call$p_1, $1, ...) change on every WhatsApp
43
+ // version, they are not part of the payload
44
+ const toJSON = (value) => {
45
+ try {
46
+ const json = value ? JSON.parse(JSON.stringify(value)) || {} : {};
47
+ for (const key of Object.keys(json)) {
48
+ if (key.startsWith('$')) {
49
+ delete json[key];
50
+ }
51
+ }
52
+ return json;
53
+ }
54
+ catch (error) {
55
+ return {};
56
+ }
57
+ };
58
+ // Older WhatsApp versions have a `participants` collection, newer ones the
59
+ // group call participants and a map with their state
60
+ const toParticipants = (call, json) => {
61
+ if (Array.isArray(json.participants)) {
62
+ return json.participants;
63
+ }
64
+ if (!Array.isArray(call?.groupCallParticipants)) {
65
+ return [];
66
+ }
67
+ const states = call.groupCallParticipantStates;
68
+ return call.groupCallParticipants.map((participant) => {
69
+ const jid = wid(participant);
70
+ const state = typeof states?.get === 'function' ? states.get(jid) : undefined;
71
+ return { jid, state: state ?? null };
72
+ });
73
+ };
74
+ WPP.on('call.incoming_call', (data) => {
75
+ // The native VoIP stack registers the call with setActiveCall, without
76
+ // adding it to the collection
77
+ const store = WPP.whatsapp.CallStore;
78
+ const call = store?.get?.(data.id) ||
79
+ (store?.activeCall?.id === data.id ? store.activeCall : undefined);
80
+ const json = toJSON(call);
81
+ w.onIncomingCall({
82
+ ...json,
83
+ id: data.id,
84
+ peerJid: wid(data.peerJid),
85
+ offerTime: data.offerTime,
86
+ isVideo: data.isVideo,
87
+ isGroup: data.isGroup,
88
+ groupJid: wid(data.groupJid),
89
+ canHandleLocally: !!call?.canHandleLocally,
90
+ outgoing: false,
91
+ isSilenced: !!call?.isSilenced,
92
+ offerReceivedWhileOffline: !!call?.offerReceivedWhileOffline,
93
+ webClientShouldHandle: !!call?.webClientShouldHandle,
94
+ participants: toParticipants(call, json),
95
+ });
96
+ });
97
+ w.onIncomingCall.exposed = true;
98
+ }
@@ -1,7 +1,7 @@
1
1
  import { Page } from 'puppeteer';
2
- import { ControlsLayer } from './controls.layer';
2
+ import { CallLayer } from './call.layer';
3
3
  import { CreateConfig } from '../../config/create-config';
4
- export declare class BusinessLayer extends ControlsLayer {
4
+ export declare class BusinessLayer extends CallLayer {
5
5
  page: Page;
6
6
  constructor(page: Page, session?: string, options?: CreateConfig);
7
7
  /**
@@ -17,9 +17,9 @@
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
19
  exports.BusinessLayer = void 0;
20
- const controls_layer_1 = require("./controls.layer");
20
+ const call_layer_1 = require("./call.layer");
21
21
  const helpers_1 = require("../helpers");
22
- class BusinessLayer extends controls_layer_1.ControlsLayer {
22
+ class BusinessLayer extends call_layer_1.CallLayer {
23
23
  page;
24
24
  constructor(page, session, options) {
25
25
  super(page, session, options);
@@ -0,0 +1,264 @@
1
+ import { Page } from 'puppeteer';
2
+ import { CreateConfig } from '../../config/create-config';
3
+ import { AcceptCallOptions, CallInfo, CallOptions, CallRecordingOptions, CreateCallLinkOptions, JoinCallLinkOptions, PlayCallAudioOptions, PushCallAudioOptions } from '../model';
4
+ import { ControlsLayer } from './controls.layer';
5
+ /**
6
+ * Voice and video calls.
7
+ *
8
+ * Audio injection, capture and recording are armed for a single call: the
9
+ * active one, or the next one to start. They are released when that call ends,
10
+ * so enable them again before each {@link CallLayer.call},
11
+ * {@link CallLayer.acceptCall} or {@link CallLayer.joinCallLink}.
12
+ *
13
+ * Audio injection only replaces the microphone: video uses the real camera.
14
+ * Without a camera, or without the camera permission (Chrome asks for it and
15
+ * the call drops), accept with `video: false` or start the browser with
16
+ * `--use-fake-ui-for-media-stream` and `--use-fake-device-for-media-stream`.
17
+ *
18
+ * Errors keep the `code` sent by WA-JS (e.g. `call_not_found`,
19
+ * `call_start_in_progress`, `invalid_call_link`).
20
+ */
21
+ export declare class CallLayer extends ControlsLayer {
22
+ page: Page;
23
+ constructor(page: Page, session?: string, options?: CreateConfig);
24
+ /**
25
+ * Runs a WA-JS call function that resolves to a CallModel and returns a
26
+ * plain snapshot of it
27
+ */
28
+ private startCall;
29
+ /**
30
+ * Starts a voice or video call
31
+ *
32
+ * @category Call
33
+ * @example
34
+ * ```javascript
35
+ * const call = await client.call('5511999999999@c.us', { audioInjection: true });
36
+ * await client.playCallAudio('./welcome.mp3');
37
+ * ```
38
+ * @param to Contact ID
39
+ * @returns The started call, or null if WhatsApp did not create it in time
40
+ */
41
+ call(to: string, options?: CallOptions): Promise<CallInfo>;
42
+ /**
43
+ * Starts a group call, from a group ID or a list of contacts
44
+ *
45
+ * @category Call
46
+ * @example
47
+ * ```javascript
48
+ * await client.callGroup(['5511999999999@c.us', '5511988888888@c.us']);
49
+ * ```
50
+ */
51
+ callGroup(to: string | string[], options?: CallOptions): Promise<CallInfo>;
52
+ /**
53
+ * Accepts an incoming call
54
+ *
55
+ * Video calls are accepted with the camera on by default, which needs a
56
+ * camera (see {@link CallLayer}). Pass `video: false` to answer with audio only.
57
+ *
58
+ * @category Call
59
+ * @example
60
+ * ```javascript
61
+ * client.onIncomingCall(async (call) => {
62
+ * await client.acceptCall(call.id, { video: false, audioInjection: true });
63
+ * });
64
+ * ```
65
+ * @param callId Call ID, defaults to the ringing call
66
+ */
67
+ acceptCall(callId?: string, options?: AcceptCallOptions): Promise<boolean>;
68
+ /**
69
+ * Rejects a call received via WhatsApp
70
+ *
71
+ * @category Call
72
+ * @example
73
+ * ```javascript
74
+ * client.onIncomingCall((call) => client.rejectCall(call.id));
75
+ * ```
76
+ * @param callId Call ID, defaults to the ringing call
77
+ */
78
+ rejectCall(callId?: string): Promise<boolean>;
79
+ /**
80
+ * Ends a call
81
+ *
82
+ * @category Call
83
+ * @example
84
+ * ```javascript
85
+ * await client.endCall();
86
+ * ```
87
+ * @param callId Call ID, defaults to the active call
88
+ */
89
+ endCall(callId?: string): Promise<boolean>;
90
+ /**
91
+ * Returns the active call, if any
92
+ *
93
+ * @category Call
94
+ * @example
95
+ * ```javascript
96
+ * const call = await client.getActiveCall();
97
+ * ```
98
+ */
99
+ getActiveCall(): Promise<CallInfo>;
100
+ /**
101
+ * Returns the details of a call reported by WhatsApp
102
+ * (duration, participants, ...)
103
+ *
104
+ * @category Call
105
+ * @example
106
+ * ```javascript
107
+ * const info = await client.getCallInfo();
108
+ * ```
109
+ * @param callId Call ID, defaults to the active call
110
+ */
111
+ getCallInfo(callId?: string): Promise<any>;
112
+ /**
113
+ * Mutes or unmutes the microphone in a call
114
+ *
115
+ * @category Call
116
+ * @example
117
+ * ```javascript
118
+ * await client.setCallMute(true);
119
+ * ```
120
+ */
121
+ setCallMute(muted: boolean, callId?: string): Promise<boolean>;
122
+ /**
123
+ * Turns the camera on or off in a call, the camera must be available
124
+ * (see {@link CallLayer})
125
+ *
126
+ * @category Call
127
+ * @example
128
+ * ```javascript
129
+ * await client.setCallVideo(false);
130
+ * ```
131
+ */
132
+ setCallVideo(enabled: boolean, callId?: string): Promise<boolean>;
133
+ /**
134
+ * Sends a reaction in a call, an empty string clears it
135
+ *
136
+ * @category Call
137
+ * @example
138
+ * ```javascript
139
+ * await client.sendCallReaction('👍');
140
+ * ```
141
+ */
142
+ sendCallReaction(emoji: string, callId?: string): Promise<boolean>;
143
+ /**
144
+ * Raises or lowers the hand in a group call
145
+ *
146
+ * @category Call
147
+ * @example
148
+ * ```javascript
149
+ * await client.raiseCallHand(true);
150
+ * ```
151
+ */
152
+ raiseCallHand(raised: boolean, callId?: string): Promise<boolean>;
153
+ /**
154
+ * Creates a call link
155
+ *
156
+ * @category Call
157
+ * @example
158
+ * ```javascript
159
+ * const link = await client.createCallLink({ isVideo: true });
160
+ * // https://call.whatsapp.com/video/...
161
+ * ```
162
+ */
163
+ createCallLink(options?: CreateCallLinkOptions): Promise<string>;
164
+ /**
165
+ * Joins a call from a call link
166
+ *
167
+ * @category Call
168
+ * @example
169
+ * ```javascript
170
+ * await client.joinCallLink('https://call.whatsapp.com/voice/xxxx');
171
+ * ```
172
+ */
173
+ joinCallLink(link: string, options?: JoinCallLinkOptions): Promise<CallInfo>;
174
+ /**
175
+ * Replaces the microphone of the next (or active) call with audio sent by
176
+ * {@link CallLayer.playCallAudio} and {@link CallLayer.pushCallAudio}.
177
+ * Call it before starting or accepting each call.
178
+ *
179
+ * @category Call
180
+ * @example
181
+ * ```javascript
182
+ * await client.enableCallAudioInjection();
183
+ * await client.acceptCall();
184
+ * ```
185
+ */
186
+ enableCallAudioInjection(enabled?: boolean): Promise<void>;
187
+ /**
188
+ * @category Call
189
+ * @returns Whether audio injection is enabled
190
+ */
191
+ isCallAudioInjectionEnabled(): Promise<boolean>;
192
+ /**
193
+ * Plays an audio file in the call, resolving when it finishes or is stopped
194
+ *
195
+ * @category Call
196
+ * @example
197
+ * ```javascript
198
+ * await client.playCallAudio('./welcome.mp3');
199
+ * await client.playCallAudio('https://example.com/welcome.ogg', { volume: 0.5 });
200
+ * await client.playCallAudio(fs.readFileSync('./welcome.wav'));
201
+ * ```
202
+ * @param source File path, http(s) URL, data URL or Buffer with the file content
203
+ */
204
+ playCallAudio(source: string | Buffer, options?: PlayCallAudioOptions): Promise<void>;
205
+ /**
206
+ * Streams raw PCM audio to the call (TTS, voice bots).
207
+ * Chunks are played back to back.
208
+ *
209
+ * @category Call
210
+ * @example
211
+ * ```javascript
212
+ * // pcm: Buffer with 16-bit little-endian mono samples at 16 kHz
213
+ * const queued = await client.pushCallAudio(pcm);
214
+ * ```
215
+ * @param pcm Int16 little-endian mono samples, as Buffer, Int16Array or base64
216
+ * @returns Seconds of audio still queued
217
+ */
218
+ pushCallAudio(pcm: Buffer | Int16Array | string, options?: PushCallAudioOptions): Promise<number>;
219
+ /**
220
+ * Stops the audio being played or streamed to the call
221
+ *
222
+ * @category Call
223
+ * @example
224
+ * ```javascript
225
+ * await client.stopCallAudio();
226
+ * ```
227
+ */
228
+ stopCallAudio(): Promise<void>;
229
+ /**
230
+ * Starts recording the next (or active) call.
231
+ * Call it before starting or accepting each call.
232
+ *
233
+ * @category Call
234
+ * @example
235
+ * ```javascript
236
+ * await client.startCallRecording({ source: 'both' });
237
+ * ```
238
+ */
239
+ startCallRecording(options?: CallRecordingOptions): Promise<void>;
240
+ /**
241
+ * @category Call
242
+ * @returns Whether a call is being recorded
243
+ */
244
+ isCallRecording(): Promise<boolean>;
245
+ /**
246
+ * Stops the recording. It still works after the call has ended.
247
+ *
248
+ * @category Call
249
+ * @example
250
+ * ```javascript
251
+ * client.onCallEnded(async () => {
252
+ * await client.stopCallRecording('./call.wav');
253
+ * });
254
+ * ```
255
+ * @param filePath Where to save the WAV file (optional)
256
+ * @returns WAV file content (16 kHz, mono, 16-bit)
257
+ */
258
+ stopCallRecording(filePath?: string): Promise<Buffer>;
259
+ /**
260
+ * Converts a file path, URL or Buffer to a data URL, so the page does not
261
+ * need to reach the file (and is not blocked by its CSP)
262
+ */
263
+ private toAudioDataUrl;
264
+ }