@hiroosy/baileys-lite 0.0.4 → 0.3.1
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.
- package/LICENSE +21 -0
- package/README.md +658 -10
- package/WAProto/index.js +2 -2558
- package/engine-requirements.js +3 -4
- package/package.json +8 -3
- package/src/binary/wa-binary.js +3 -25
- package/src/constants.js +7 -15
- package/src/defaults.js +2 -5
- package/src/foundation/ai-rich.js +530 -0
- package/src/foundation/audio-duration.js +43 -103
- package/src/foundation/audio-samples.js +19 -37
- package/src/foundation/boom.js +0 -7
- package/src/foundation/cache.js +4 -26
- package/src/foundation/concurrency.js +1 -19
- package/src/foundation/curve25519.js +7 -39
- package/src/foundation/link-preview.js +15 -57
- package/src/foundation/logger.js +0 -11
- package/src/foundation/long.js +4 -14
- package/src/foundation/protobuf-minimal.js +21 -53
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +2 -31
- package/src/foundation/zip.js +25 -41
- package/src/index.js +8 -18
- package/src/signal/libsignal.js +23 -78
- package/src/signal/signal-group.js +0 -35
- package/src/signal/signal-repository.js +10 -29
- package/src/socket/business-communities.js +12 -31
- package/src/socket/chats.js +5 -8
- package/src/socket/groups-newsletter.js +18 -17
- package/src/socket/messages-recv.js +81 -127
- package/src/socket/messages-send.js +372 -139
- package/src/socket/socket-core.js +227 -157
- package/src/socket/usync.js +2 -6
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +84 -38
- package/src/utils/auth-state-core.js +14 -56
- package/src/utils/auth-state-storage.js +7 -42
- package/src/utils/chat-sync.js +4 -26
- package/src/utils/media.js +15 -71
- package/src/utils/message-compose.js +208 -85
- package/src/utils/message-processing.js +10 -65
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +71 -127
- package/src/vendor/jpeg-js/decoder.js +75 -136
- package/src/vendor/jpeg-js/encoder.js +179 -264
- package/src/vendor/pngjs/bitmapper.js +5 -27
- package/src/vendor/pngjs/bitpacker.js +4 -12
- package/src/vendor/pngjs/constants.js +3 -11
- package/src/vendor/pngjs/crc.js +0 -6
- package/src/vendor/pngjs/filter-pack.js +1 -7
- package/src/vendor/pngjs/filter-parse-sync.js +0 -6
- package/src/vendor/pngjs/filter-parse.js +1 -11
- package/src/vendor/pngjs/format-normaliser.js +5 -11
- package/src/vendor/pngjs/interlace.js +7 -24
- package/src/vendor/pngjs/packer-sync.js +0 -11
- package/src/vendor/pngjs/packer.js +7 -15
- package/src/vendor/pngjs/paeth-predictor.js +0 -6
- package/src/vendor/pngjs/parser-sync.js +0 -8
- package/src/vendor/pngjs/parser.js +5 -29
- package/src/vendor/pngjs/png-sync.js +0 -7
- package/src/vendor/pngjs/sync-inflate.js +7 -16
- package/src/vendor/pngjs/sync-reader.js +4 -11
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1705 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +628 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +0 -1
- package/src/wam/wam.js +2 -7
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { EventEmitter } from 'node:events';
|
|
4
|
+
import { VoipClient } from './voipClient.js';
|
|
5
|
+
import { CallDirection, CallMediaType } from './types.js';
|
|
6
|
+
|
|
7
|
+
const RESOLUTION_PRESETS = {
|
|
8
|
+
'240p': { width: 320, height: 240, frameRate: 20 },
|
|
9
|
+
'360p': { width: 640, height: 360, frameRate: 30 },
|
|
10
|
+
'480p': { width: 854, height: 480, frameRate: 30 },
|
|
11
|
+
'720p': { width: 1280, height: 720, frameRate: 30 },
|
|
12
|
+
'1080p': { width: 1920, height: 1080, frameRate: 30 },
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function resolveVideoConfig(resolution, sourceDims) {
|
|
16
|
+
if (!resolution) {
|
|
17
|
+
if (!sourceDims?.width || !sourceDims?.height)
|
|
18
|
+
return undefined;
|
|
19
|
+
return applyOrientation(RESOLUTION_PRESETS['480p'], sourceDims);
|
|
20
|
+
}
|
|
21
|
+
if (typeof resolution === 'object')
|
|
22
|
+
return resolution;
|
|
23
|
+
const key = String(resolution).trim().toLowerCase();
|
|
24
|
+
const preset = RESOLUTION_PRESETS[key];
|
|
25
|
+
if (!preset) {
|
|
26
|
+
const known = Object.keys(RESOLUTION_PRESETS).join(', ');
|
|
27
|
+
throw new Error(`Unknown resolution "${resolution}". Use one of: ${known}, or pass { width, height, frameRate } directly.`);
|
|
28
|
+
}
|
|
29
|
+
return applyOrientation(preset, sourceDims);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function applyOrientation(preset, sourceDims) {
|
|
33
|
+
if (!sourceDims?.width || !sourceDims?.height)
|
|
34
|
+
return { ...preset };
|
|
35
|
+
const sourceIsPortrait = sourceDims.height > sourceDims.width;
|
|
36
|
+
const presetIsPortrait = preset.height > preset.width;
|
|
37
|
+
if (sourceIsPortrait === presetIsPortrait)
|
|
38
|
+
return { ...preset };
|
|
39
|
+
return { ...preset, width: preset.height, height: preset.width };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const VIDEO_EXTENSIONS = /\.(mp4|mov|webm|mkv|avi|m4v|3gp)(\?|#|$)/i;
|
|
43
|
+
const AUDIO_EXTENSIONS = /\.(mp3|ogg|opus|wav|m4a|aac|flac|weba)(\?|#|$)/i;
|
|
44
|
+
|
|
45
|
+
function detectKind(source) {
|
|
46
|
+
if (VIDEO_EXTENSIONS.test(source))
|
|
47
|
+
return 'video';
|
|
48
|
+
if (AUDIO_EXTENSIONS.test(source))
|
|
49
|
+
return 'audio';
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isUrl(source) {
|
|
54
|
+
return /^https?:\/\//i.test(source);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function downloadToTemp(url, extHint, maxBytes, tmpDirOverride) {
|
|
58
|
+
const response = await fetch(url, {
|
|
59
|
+
headers: { 'User-Agent': 'Mozilla/5.0' },
|
|
60
|
+
signal: AbortSignal.timeout(30_000),
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok)
|
|
63
|
+
throw new Error(`Download failed: HTTP ${response.status}`);
|
|
64
|
+
const declared = Number(response.headers.get('content-length') || 0);
|
|
65
|
+
if (declared && declared > maxBytes)
|
|
66
|
+
throw new Error(`Download too large: ${declared} bytes (max ${maxBytes})`);
|
|
67
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
68
|
+
if (data.length > maxBytes)
|
|
69
|
+
throw new Error(`Download too large: ${data.length} bytes (max ${maxBytes})`);
|
|
70
|
+
const os = await import('node:os');
|
|
71
|
+
const tmpDir = tmpDirOverride || os.tmpdir();
|
|
72
|
+
if (!fs.existsSync(tmpDir))
|
|
73
|
+
fs.mkdirSync(tmpDir, { recursive: true });
|
|
74
|
+
const filePath = path.join(tmpDir, `voip_${Date.now()}_${Math.random().toString(36).slice(2, 8)}${extHint}`);
|
|
75
|
+
fs.writeFileSync(filePath, data);
|
|
76
|
+
return filePath;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function probeMedia(filePath, ffprobePath) {
|
|
80
|
+
try {
|
|
81
|
+
const { execFile } = await import('node:child_process');
|
|
82
|
+
const { promisify } = await import('node:util');
|
|
83
|
+
const execFileAsync = promisify(execFile);
|
|
84
|
+
const { stdout } = await execFileAsync(ffprobePath, [
|
|
85
|
+
'-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', filePath
|
|
86
|
+
]);
|
|
87
|
+
const parsed = JSON.parse(stdout);
|
|
88
|
+
const duration = parsed?.format?.duration;
|
|
89
|
+
const durationMs = (!duration || isNaN(duration)) ? null : Math.ceil(parseFloat(duration) * 1000);
|
|
90
|
+
const videoStream = parsed?.streams?.find((s) => s.codec_type === 'video');
|
|
91
|
+
let width = videoStream?.width || null;
|
|
92
|
+
let height = videoStream?.height || null;
|
|
93
|
+
const rotation = getEffectiveRotation(videoStream);
|
|
94
|
+
if (width && height && Math.abs(rotation) % 180 === 90) {
|
|
95
|
+
[width, height] = [height, width];
|
|
96
|
+
}
|
|
97
|
+
return { durationMs, width, height };
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return { durationMs: null, width: null, height: null };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function getEffectiveRotation(videoStream) {
|
|
105
|
+
const tagRotate = videoStream?.tags?.rotate;
|
|
106
|
+
if (tagRotate !== undefined) {
|
|
107
|
+
const n = parseInt(tagRotate, 10);
|
|
108
|
+
if (!isNaN(n)) return ((n % 360) + 360) % 360;
|
|
109
|
+
}
|
|
110
|
+
const matrixSideData = videoStream?.side_data_list?.find((sd) => sd.rotation !== undefined);
|
|
111
|
+
if (matrixSideData) {
|
|
112
|
+
const n = Math.round(matrixSideData.rotation);
|
|
113
|
+
if (!isNaN(n)) return ((n % 360) + 360) % 360;
|
|
114
|
+
}
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function normalizeItem(item, ffprobePath, tmpDir) {
|
|
119
|
+
let kind;
|
|
120
|
+
let rawSource;
|
|
121
|
+
let autoAdvance = false;
|
|
122
|
+
if (typeof item === 'string') {
|
|
123
|
+
rawSource = item;
|
|
124
|
+
kind = detectKind(item) ?? 'audio';
|
|
125
|
+
}
|
|
126
|
+
else if (item && typeof item === 'object') {
|
|
127
|
+
autoAdvance = !!item.autoAdvance;
|
|
128
|
+
if (item.video) {
|
|
129
|
+
rawSource = item.video;
|
|
130
|
+
kind = 'video';
|
|
131
|
+
}
|
|
132
|
+
else if (item.audio) {
|
|
133
|
+
rawSource = item.audio;
|
|
134
|
+
kind = 'audio';
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
throw new Error('Playlist item must be a string, or an object with a "video" or "audio" key.');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
throw new Error('Playlist item must be a string or an object.');
|
|
142
|
+
}
|
|
143
|
+
let source = rawSource;
|
|
144
|
+
let isTemp = false;
|
|
145
|
+
if (isUrl(rawSource)) {
|
|
146
|
+
const extHint = kind === 'video' ? '.mp4' : '.audio';
|
|
147
|
+
const maxBytes = kind === 'video' ? 50 * 1024 * 1024 : 20 * 1024 * 1024;
|
|
148
|
+
source = await downloadToTemp(rawSource, extHint, maxBytes, tmpDir);
|
|
149
|
+
isTemp = true;
|
|
150
|
+
}
|
|
151
|
+
else if (!fs.existsSync(rawSource)) {
|
|
152
|
+
throw new Error(`Media file not found: ${rawSource}`);
|
|
153
|
+
}
|
|
154
|
+
const probed = await probeMedia(source, ffprobePath);
|
|
155
|
+
const durationMs = probed.durationMs ?? undefined;
|
|
156
|
+
const result = { kind, source, isTemp, durationMs, autoAdvance };
|
|
157
|
+
if (kind === 'video' && probed.width && probed.height) {
|
|
158
|
+
result.sourceWidth = probed.width;
|
|
159
|
+
result.sourceHeight = probed.height;
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
class VoipCall extends EventEmitter {
|
|
165
|
+
#activeCall = null;
|
|
166
|
+
#coordinator = null;
|
|
167
|
+
#items;
|
|
168
|
+
#index = -1;
|
|
169
|
+
#ended = false;
|
|
170
|
+
#onRelease;
|
|
171
|
+
#autoEndCall;
|
|
172
|
+
#loop;
|
|
173
|
+
#onItemAdvance;
|
|
174
|
+
#target;
|
|
175
|
+
#autoDowngrade;
|
|
176
|
+
#startVideoOnFirst;
|
|
177
|
+
#videoDown = false;
|
|
178
|
+
#silenced = false;
|
|
179
|
+
_itemTimer = null;
|
|
180
|
+
constructor(items, onRelease, opts = {}) {
|
|
181
|
+
super();
|
|
182
|
+
this.#items = items;
|
|
183
|
+
this.#onRelease = onRelease;
|
|
184
|
+
this.#autoEndCall = opts.autoEndCall === undefined ? true : !!opts.autoEndCall;
|
|
185
|
+
this.#loop = !!opts.loop;
|
|
186
|
+
this.#onItemAdvance = opts.onItemAdvance;
|
|
187
|
+
this.#target = opts.target ?? null;
|
|
188
|
+
this.#autoDowngrade = opts.autoDowngrade === undefined ? true : !!opts.autoDowngrade;
|
|
189
|
+
this.#startVideoOnFirst = !!opts.startVideoOnFirst;
|
|
190
|
+
}
|
|
191
|
+
async _attach(activeCall) {
|
|
192
|
+
this.#activeCall = activeCall;
|
|
193
|
+
this.#coordinator = activeCall.coordinator;
|
|
194
|
+
activeCall.on('ringing', () => this.emit('ringing'));
|
|
195
|
+
activeCall.on('connected', () => {
|
|
196
|
+
this.emit('connected');
|
|
197
|
+
this._advance().catch((err) => this.emit('error', err));
|
|
198
|
+
});
|
|
199
|
+
activeCall.on('ended', (reason) => this._finish(reason));
|
|
200
|
+
activeCall.on('error', (err) => this.emit('error', err));
|
|
201
|
+
activeCall.on('peer_video', (change) => {
|
|
202
|
+
this._onPeerVideo(change).catch((err) => this.emit('error', err));
|
|
203
|
+
});
|
|
204
|
+
if (activeCall.ended) {
|
|
205
|
+
this._finish('ended');
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (activeCall.connected) {
|
|
209
|
+
this.emit('connected');
|
|
210
|
+
this._advance().catch((err) => this.emit('error', err));
|
|
211
|
+
}
|
|
212
|
+
for (const ev of ['peer_mute', 'hand_raise', 'reaction', 'screen_share', 'peer_video', 'inbound_audio', 'inbound_video', 'audio_finished']) {
|
|
213
|
+
activeCall.on(ev, (...args) => this.emit(ev, ...args));
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
get callId() {
|
|
217
|
+
return this.#activeCall?.callId ?? null;
|
|
218
|
+
}
|
|
219
|
+
get target() {
|
|
220
|
+
return this.#target;
|
|
221
|
+
}
|
|
222
|
+
mute(value = true) {
|
|
223
|
+
return this.#activeCall?.setMute(value);
|
|
224
|
+
}
|
|
225
|
+
raiseHand(value = true) {
|
|
226
|
+
return this.#activeCall?.raiseHand(value);
|
|
227
|
+
}
|
|
228
|
+
shareScreen(value = true) {
|
|
229
|
+
return this.#activeCall?.shareScreen(value);
|
|
230
|
+
}
|
|
231
|
+
react(emoji) {
|
|
232
|
+
return this.#activeCall?.react(emoji) ?? false;
|
|
233
|
+
}
|
|
234
|
+
async upgradeToVideo() {
|
|
235
|
+
await this.#activeCall?.upgradeToVideo();
|
|
236
|
+
this.#videoDown = false;
|
|
237
|
+
}
|
|
238
|
+
get isVideoDowngraded() {
|
|
239
|
+
return this.#videoDown;
|
|
240
|
+
}
|
|
241
|
+
async _onPeerVideo(change) {
|
|
242
|
+
if (!this.#autoDowngrade || this.#ended || this.#silenced || this.#videoDown)
|
|
243
|
+
return;
|
|
244
|
+
if (change?.direction !== 'inbound' || change.active || !change.allOff)
|
|
245
|
+
return;
|
|
246
|
+
const current = this.#items[this.#index];
|
|
247
|
+
if (current?.kind !== 'video')
|
|
248
|
+
return;
|
|
249
|
+
const callId = this.#activeCall?.callId;
|
|
250
|
+
if (!callId)
|
|
251
|
+
return;
|
|
252
|
+
this.#videoDown = true;
|
|
253
|
+
try {
|
|
254
|
+
await this.#coordinator.stopVideoMidCall(callId, { keepSource: true });
|
|
255
|
+
this.emit('downgraded');
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
this.#videoDown = false;
|
|
259
|
+
throw new Error(`Failed to downgrade call to audio: ${err?.message || err}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async _advance() {
|
|
264
|
+
if (this.#silenced)
|
|
265
|
+
return;
|
|
266
|
+
const previous = this.#items[this.#index] ?? null;
|
|
267
|
+
this.#index += 1;
|
|
268
|
+
let next = this.#items[this.#index];
|
|
269
|
+
if (!next) {
|
|
270
|
+
if (this.#loop && this.#items.length > 0) {
|
|
271
|
+
this.emit('playlist_looped');
|
|
272
|
+
this.#index = 0;
|
|
273
|
+
next = this.#items[0];
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
this.emit('playlist_ended');
|
|
277
|
+
if (this.#autoEndCall) {
|
|
278
|
+
this.end().catch((err) => this.emit('error', err));
|
|
279
|
+
}
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const isFirst = previous === null && this.#index === 0;
|
|
284
|
+
if (isFirst && next.kind === 'video' && this.#startVideoOnFirst) {
|
|
285
|
+
try {
|
|
286
|
+
await this.#coordinator.startVideoMidCall(this.#activeCall.callId);
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
this.emit('error', new Error(`Failed to start video: ${err?.message || err}`));
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (!isFirst) {
|
|
293
|
+
const callId = this.#activeCall.callId;
|
|
294
|
+
const videoRunning = previous?.kind === 'video' && !this.#videoDown;
|
|
295
|
+
try {
|
|
296
|
+
if (next.kind === 'video') {
|
|
297
|
+
if (previous && previous.kind === 'video') {
|
|
298
|
+
await this.#coordinator.swapVideoSource(callId, next.source);
|
|
299
|
+
}
|
|
300
|
+
else {
|
|
301
|
+
await this.#coordinator.loadVideo(callId, next.source);
|
|
302
|
+
}
|
|
303
|
+
await this.#coordinator.loadAudio(callId, next.source);
|
|
304
|
+
if (!videoRunning) {
|
|
305
|
+
await this.#coordinator.startVideoMidCall(callId);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
await this.#coordinator.loadAudio(callId, next.source);
|
|
310
|
+
if (videoRunning) {
|
|
311
|
+
await this.#coordinator.stopVideoMidCall(callId, { keepSource: true });
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
this.#videoDown = false;
|
|
315
|
+
}
|
|
316
|
+
catch (err) {
|
|
317
|
+
this.emit('error', new Error(`Failed to advance to playlist item ${this.#index} (${next.kind} "${next.source}"): ${err?.message || err}`));
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
if (!this.#loop) {
|
|
321
|
+
this._cleanupItem(previous);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
this.emit('item', { index: this.#index, kind: next.kind, source: next.source });
|
|
326
|
+
this.#onItemAdvance?.(next);
|
|
327
|
+
if ((next.kind !== 'video' || next.autoAdvance) && next.durationMs) {
|
|
328
|
+
this._itemTimer = setTimeout(() => {
|
|
329
|
+
this._advance().catch((err) => this.emit('error', err));
|
|
330
|
+
}, next.durationMs);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
_cleanupItem(item) {
|
|
334
|
+
if (item?.isTemp && fs.existsSync(item.source)) {
|
|
335
|
+
fs.unlink(item.source, () => { });
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
_finish(reason) {
|
|
339
|
+
if (this.#ended)
|
|
340
|
+
return;
|
|
341
|
+
this.#ended = true;
|
|
342
|
+
if (this._itemTimer)
|
|
343
|
+
clearTimeout(this._itemTimer);
|
|
344
|
+
for (const item of this.#items)
|
|
345
|
+
this._cleanupItem(item);
|
|
346
|
+
this.#onRelease();
|
|
347
|
+
this.emit('ended', reason);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async hangup() {
|
|
351
|
+
if (this.#ended)
|
|
352
|
+
return;
|
|
353
|
+
await this.#activeCall?.end();
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async silent(value) {
|
|
357
|
+
if (this.#ended)
|
|
358
|
+
return this.#silenced;
|
|
359
|
+
const next = value === undefined ? !this.#silenced : !!value;
|
|
360
|
+
if (next === this.#silenced)
|
|
361
|
+
return this.#silenced;
|
|
362
|
+
this.#silenced = next;
|
|
363
|
+
const callId = this.#activeCall?.callId;
|
|
364
|
+
if (!callId)
|
|
365
|
+
return this.#silenced;
|
|
366
|
+
const current = this.#items[this.#index];
|
|
367
|
+
try {
|
|
368
|
+
if (next) {
|
|
369
|
+
await this.#coordinator.setMute(callId, true);
|
|
370
|
+
if (current?.kind === 'video' && !this.#videoDown) {
|
|
371
|
+
await this.#coordinator.stopVideoMidCall(callId, { keepSource: true });
|
|
372
|
+
this.#videoDown = true;
|
|
373
|
+
}
|
|
374
|
+
if (this._itemTimer) {
|
|
375
|
+
clearTimeout(this._itemTimer);
|
|
376
|
+
this._itemTimer = null;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
else {
|
|
380
|
+
await this.#coordinator.setMute(callId, false);
|
|
381
|
+
if (current?.kind === 'video') {
|
|
382
|
+
await this.#coordinator.startVideoMidCall(callId);
|
|
383
|
+
this.#videoDown = false;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
}
|
|
387
|
+
this.emit('silent', this.#silenced);
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
this.#silenced = !next;
|
|
391
|
+
this.emit('error', new Error(`Failed to ${next ? 'silence' : 'resume'} call: ${err?.message || err}`));
|
|
392
|
+
}
|
|
393
|
+
return this.#silenced;
|
|
394
|
+
}
|
|
395
|
+
get isSilenced() {
|
|
396
|
+
return this.#silenced;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async end() {
|
|
400
|
+
return this.hangup();
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export default class Voip {
|
|
405
|
+
#conn;
|
|
406
|
+
#client = null;
|
|
407
|
+
#clientForConn = null;
|
|
408
|
+
#calls = new Set();
|
|
409
|
+
#pending = 0;
|
|
410
|
+
#maxConcurrentCalls;
|
|
411
|
+
#ffprobePath;
|
|
412
|
+
#tmpDir;
|
|
413
|
+
#voipLogLevel;
|
|
414
|
+
constructor(conn, opts = {}) {
|
|
415
|
+
this.#conn = conn;
|
|
416
|
+
this.#ffprobePath = opts.ffprobePath || 'ffprobe';
|
|
417
|
+
this.#voipLogLevel = opts.voipLogLevel ?? 'warn';
|
|
418
|
+
this.#maxConcurrentCalls = opts.maxConcurrentCalls ?? 1;
|
|
419
|
+
if (!Number.isSafeInteger(this.#maxConcurrentCalls) || this.#maxConcurrentCalls < 1)
|
|
420
|
+
throw new Error('maxConcurrentCalls must be a positive integer.');
|
|
421
|
+
this.#tmpDir = opts.tmpDir;
|
|
422
|
+
}
|
|
423
|
+
#getClient() {
|
|
424
|
+
if (this.#client && this.#clientForConn === this.#conn)
|
|
425
|
+
return this.#client;
|
|
426
|
+
this.#client = new VoipClient({
|
|
427
|
+
existingSocket: this.#conn,
|
|
428
|
+
voipLogLevel: this.#voipLogLevel,
|
|
429
|
+
maxConcurrentCalls: this.#maxConcurrentCalls
|
|
430
|
+
});
|
|
431
|
+
this.#clientForConn = this.#conn;
|
|
432
|
+
return this.#client;
|
|
433
|
+
}
|
|
434
|
+
get calls() {
|
|
435
|
+
return [...this.#calls];
|
|
436
|
+
}
|
|
437
|
+
get maxConcurrentCalls() {
|
|
438
|
+
return this.#maxConcurrentCalls;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
#assertCapacity() {
|
|
442
|
+
if (this.#calls.size + this.#pending >= this.#maxConcurrentCalls)
|
|
443
|
+
throw new Error(`Maximum concurrent calls reached (${this.#maxConcurrentCalls}), wait for a call to end.`);
|
|
444
|
+
}
|
|
445
|
+
async call(jid, media, resolution, options = {}) {
|
|
446
|
+
this.#assertCapacity();
|
|
447
|
+
const targetJid = String(jid || '').replace(/\D/g, '');
|
|
448
|
+
if (!targetJid)
|
|
449
|
+
throw new Error('Invalid phone number / jid.');
|
|
450
|
+
return this.#launch(targetJid, media, resolution, options, (client, first, videoConfig) => client.call(targetJid, {
|
|
451
|
+
audioSource: first.source,
|
|
452
|
+
isVideo: first.kind === 'video',
|
|
453
|
+
...(first.kind === 'video' ? { videoSource: first.source } : {}),
|
|
454
|
+
durationMs: 0,
|
|
455
|
+
videoConfig,
|
|
456
|
+
}));
|
|
457
|
+
}
|
|
458
|
+
async accept(callId, media, resolution, options = {}) {
|
|
459
|
+
await this.listen();
|
|
460
|
+
this.#assertCapacity();
|
|
461
|
+
const info = this.coordinator.getCall(callId);
|
|
462
|
+
if (!info)
|
|
463
|
+
throw new Error(`Unknown call ${callId}.`);
|
|
464
|
+
if (!info.canAccept)
|
|
465
|
+
throw new Error(`Call ${callId} cannot be accepted right now.`);
|
|
466
|
+
const callIsVideo = info.mediaType === CallMediaType.Video;
|
|
467
|
+
return this.#launch(info.peerJid, media, resolution, { ...options, startVideoOnFirst: !callIsVideo }, (client, first) => client.answer(callId, {
|
|
468
|
+
audioSource: first.source,
|
|
469
|
+
videoSource: first.kind === 'video' ? first.source : undefined,
|
|
470
|
+
durationMs: 0,
|
|
471
|
+
}));
|
|
472
|
+
}
|
|
473
|
+
async reject(callId, reason) {
|
|
474
|
+
await this.listen();
|
|
475
|
+
return this.coordinator.rejectCall(callId, reason);
|
|
476
|
+
}
|
|
477
|
+
get incoming() {
|
|
478
|
+
return (this.coordinator?.getCalls() ?? []).filter((info) => info.direction === CallDirection.Incoming && info.isRinging);
|
|
479
|
+
}
|
|
480
|
+
onIncoming(listener) {
|
|
481
|
+
const coordinator = this.#requireCoordinator();
|
|
482
|
+
const wrapped = (info) => listener({
|
|
483
|
+
callId: info.callId,
|
|
484
|
+
jid: info.peerJid,
|
|
485
|
+
creator: info.callCreator,
|
|
486
|
+
isVideo: info.mediaType === CallMediaType.Video,
|
|
487
|
+
canAccept: info.canAccept,
|
|
488
|
+
info,
|
|
489
|
+
});
|
|
490
|
+
coordinator.on('call_incoming', wrapped);
|
|
491
|
+
return () => coordinator.off('call_incoming', wrapped);
|
|
492
|
+
}
|
|
493
|
+
async #launch(targetJid, media, resolution, options, begin) {
|
|
494
|
+
this.#pending++;
|
|
495
|
+
let reserved = true;
|
|
496
|
+
const releaseReservation = () => {
|
|
497
|
+
if (!reserved)
|
|
498
|
+
return;
|
|
499
|
+
reserved = false;
|
|
500
|
+
this.#pending--;
|
|
501
|
+
};
|
|
502
|
+
const items = [];
|
|
503
|
+
const cleanupItems = () => {
|
|
504
|
+
for (const item of items) {
|
|
505
|
+
if (item?.isTemp && fs.existsSync(item.source))
|
|
506
|
+
fs.unlink(item.source, () => { });
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
try {
|
|
510
|
+
const rawItems = Array.isArray(media) ? media : [media ?? 'silence'];
|
|
511
|
+
for (const raw of rawItems) {
|
|
512
|
+
if (raw === 'silence' || raw == null) {
|
|
513
|
+
items.push({ kind: 'audio', source: 'silence', isTemp: false });
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
items.push(await normalizeItem(raw, this.#ffprobePath, this.#tmpDir));
|
|
517
|
+
}
|
|
518
|
+
const first = items[0];
|
|
519
|
+
const videoConfig = resolveVideoConfig(resolution, { width: first.sourceWidth, height: first.sourceHeight });
|
|
520
|
+
const client = this.#getClient();
|
|
521
|
+
await client.connect();
|
|
522
|
+
const safetyTimer = { handle: null };
|
|
523
|
+
const scheduleSafety = (ms) => {
|
|
524
|
+
if (safetyTimer.handle)
|
|
525
|
+
clearTimeout(safetyTimer.handle);
|
|
526
|
+
safetyTimer.handle = setTimeout(() => {
|
|
527
|
+
call.emit('error', new Error('Safety timeout — call never reached ended/error.'));
|
|
528
|
+
this.#calls.delete(call);
|
|
529
|
+
}, ms);
|
|
530
|
+
};
|
|
531
|
+
const rescheduleSafetyForItem = (item) => {
|
|
532
|
+
const windowMs = item?.kind === 'video'
|
|
533
|
+
? 10 * 60_000
|
|
534
|
+
: Math.max(item?.durationMs ?? 120_000, 45_000) + 60_000;
|
|
535
|
+
scheduleSafety(windowMs);
|
|
536
|
+
};
|
|
537
|
+
const call = new VoipCall(items, () => { this.#calls.delete(call); }, {
|
|
538
|
+
autoEndCall: options.autoEndCall,
|
|
539
|
+
loop: options.loop,
|
|
540
|
+
autoDowngrade: options.autoDowngrade,
|
|
541
|
+
startVideoOnFirst: options.startVideoOnFirst,
|
|
542
|
+
target: targetJid,
|
|
543
|
+
onItemAdvance: rescheduleSafetyForItem,
|
|
544
|
+
});
|
|
545
|
+
this.#calls.add(call);
|
|
546
|
+
releaseReservation();
|
|
547
|
+
scheduleSafety(105_000);
|
|
548
|
+
let activeCall;
|
|
549
|
+
try {
|
|
550
|
+
activeCall = await begin(client, first, videoConfig);
|
|
551
|
+
}
|
|
552
|
+
catch (err) {
|
|
553
|
+
clearTimeout(safetyTimer.handle);
|
|
554
|
+
call._finish('failed');
|
|
555
|
+
throw err;
|
|
556
|
+
}
|
|
557
|
+
activeCall.on('ended', () => clearTimeout(safetyTimer.handle));
|
|
558
|
+
activeCall.on('error', () => clearTimeout(safetyTimer.handle));
|
|
559
|
+
await call._attach(activeCall);
|
|
560
|
+
return call;
|
|
561
|
+
}
|
|
562
|
+
catch (err) {
|
|
563
|
+
cleanupItems();
|
|
564
|
+
throw err;
|
|
565
|
+
}
|
|
566
|
+
finally {
|
|
567
|
+
releaseReservation();
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async callMany(targets, media, resolution, options = {}) {
|
|
572
|
+
const seen = new Set();
|
|
573
|
+
const list = [];
|
|
574
|
+
for (const target of Array.isArray(targets) ? targets : [targets]) {
|
|
575
|
+
const key = String(target ?? '').replace(/\D/g, '') || String(target ?? '');
|
|
576
|
+
if (seen.has(key))
|
|
577
|
+
continue;
|
|
578
|
+
seen.add(key);
|
|
579
|
+
list.push(target);
|
|
580
|
+
}
|
|
581
|
+
if (!list.length)
|
|
582
|
+
throw new Error('callMany needs at least one target.');
|
|
583
|
+
await this.listen();
|
|
584
|
+
const settled = await Promise.allSettled(list.map((jid) => this.call(jid, media, resolution, options)));
|
|
585
|
+
return settled.map((result, index) => result.status === 'fulfilled'
|
|
586
|
+
? { jid: list[index], call: result.value }
|
|
587
|
+
: { jid: list[index], error: result.reason });
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async listen() {
|
|
591
|
+
await this.#getClient().connect();
|
|
592
|
+
return this;
|
|
593
|
+
}
|
|
594
|
+
get coordinator() {
|
|
595
|
+
return this.#client?.coordinator ?? null;
|
|
596
|
+
}
|
|
597
|
+
on(event, listener) {
|
|
598
|
+
if (!this.coordinator)
|
|
599
|
+
throw new Error('Call listen() before subscribing to voip events.');
|
|
600
|
+
this.coordinator.on(event, listener);
|
|
601
|
+
return this;
|
|
602
|
+
}
|
|
603
|
+
off(event, listener) {
|
|
604
|
+
this.coordinator?.off(event, listener);
|
|
605
|
+
return this;
|
|
606
|
+
}
|
|
607
|
+
async acceptCall(callId) {
|
|
608
|
+
return this.#requireCoordinator().acceptCall(callId);
|
|
609
|
+
}
|
|
610
|
+
async rejectCall(callId, reason) {
|
|
611
|
+
return this.#requireCoordinator().rejectCall(callId, reason);
|
|
612
|
+
}
|
|
613
|
+
async hangup(callId) {
|
|
614
|
+
return this.#requireCoordinator().endCall(callId);
|
|
615
|
+
}
|
|
616
|
+
#requireCoordinator() {
|
|
617
|
+
if (!this.coordinator)
|
|
618
|
+
throw new Error('Call listen() first.');
|
|
619
|
+
return this.coordinator;
|
|
620
|
+
}
|
|
621
|
+
async end(force = false) {
|
|
622
|
+
if (force) {
|
|
623
|
+
this.#calls.clear();
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
await Promise.all([...this.#calls].map((call) => call.hangup()));
|
|
627
|
+
}
|
|
628
|
+
}
|