@hiroosy/baileys-lite 0.3.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  - [x] High performance for multi sessions.
13
13
  - [x] Zero dependency.
14
14
  - [x] Low memory & CPU consumption.
15
- - [x] Calls: Video & Audio.
15
+ - [x] Calls: Video & Audio, group calls, call links, and waiting rooms.
16
16
 
17
17
  ---
18
18
 
@@ -504,7 +504,7 @@ await sock.sendMessage([contactJid1, contactJid2], { text: 'Status update text'
504
504
 
505
505
  ## Call
506
506
 
507
- Calls need `ffmpeg` and `ffprobe` in `PATH`. Create one `Voip` per socket once it is open. After a reconnect there is a new socket, so create a new `Voip`.
507
+ Calls need `ffmpeg` and `ffprobe` in `PATH`. Create one `Voip` per socket once it is open. After a reconnect there is a new socket, so create a new `Voip`. The same `Voip` handles 1:1 calls, group calls, and call links.
508
508
 
509
509
  <details> <summary>Quick start</summary>
510
510
 
@@ -532,7 +532,7 @@ await voip.call('628123456789')
532
532
 
533
533
  ```javascript
534
534
  await voip.call(jid, './song.mp3') // local file
535
- await voip.call(jid, 'https://example.com/song.mp3') // url, downloaded first (audio max 20MB, video max 50MB)
535
+ await voip.call(jid, 'https://example.com/song.mp3') // audio url is streamed, video url is downloaded first (max 50MB)
536
536
  await voip.call(jid, { audio: './voice.ogg' })
537
537
  await voip.call(jid, './clip.mp4', '720p') // video call
538
538
 
@@ -603,6 +603,13 @@ call.on('peer_video', change => {})
603
603
  call.on('inbound_audio', pcm => {}) // Float32Array, 16 kHz mono, 60 ms
604
604
  call.on('inbound_video', frame => {}) // decoded H.264 frame
605
605
  call.on('audio_finished', () => {}) // current audio item reached its end
606
+ call.on('reconnecting', detail => {}) // connection is recovering
607
+ call.on('reconnected', () => {})
608
+
609
+ call.on('group_state', state => {}) // group roster snapshot
610
+ call.on('participants_changed', ({ added, removed }) => {})
611
+ call.on('waiting_room', room => {})
612
+ call.on('participant_audio', (jid, pcm) => {}) // audio from one participant
606
613
  ```
607
614
 
608
615
  </details>
@@ -625,13 +632,97 @@ await voip.hangup(callId)
625
632
 
626
633
  // events: call_incoming, call_state, call_ended, call_peer_mute, call_inbound_audio,
627
634
  // call_inbound_video, call_hand_raise, call_reaction, call_screen_share,
628
- // call_peer_video_state, call_outbound_audio_finished, call_error
635
+ // call_video_state, call_outbound_audio_finished, call_error, call_reconnecting,
636
+ // call_reconnected, call_group_state, call_waiting_room, call_participant_audio
629
637
  ```
630
638
 
639
+ `voip.incoming()` returns the ringing incoming calls. It is a method, not a getter.
640
+
631
641
  `voip.coordinator` is the raw engine (`feedLiveAudio`, `feedLiveVideo`, `setExternalAudioMode`, ...).
632
642
 
633
643
  </details>
634
644
 
645
+ <details> <summary>Participants & Approval</summary>
646
+
647
+ ```javascript
648
+ call.participants // current group members
649
+ call.waitingRoom // people waiting for approval, null if none
650
+ call.link // call link, null if the call has none
651
+
652
+ await call.addParticipant('628111111111') // invite into the call
653
+ await call.ringParticipant('628111111111') // invite and ring
654
+ await call.setApprovalRequired(true) // waiting room on or off
655
+ await call.admit('628111111111') // let a waiting person in
656
+ await call.deny('628111111111') // reject a waiting person
657
+ ```
658
+
659
+ Targets can be a number or a jid. Numbers are converted to a LID before the request is sent.
660
+
661
+ </details>
662
+
663
+ <details> <summary>Group Calls</summary>
664
+
665
+ ```javascript
666
+ const call = await voip.groupCall(
667
+ ['628111111111', '628222222222'], // at least two numbers besides yourself
668
+ './song.mp3',
669
+ '480p',
670
+ { groupJid: '120363000000000000@g.us' } // group chat the call belongs to
671
+ )
672
+
673
+ call.on('participants_changed', ({ added, removed }) => {
674
+ console.log('joined:', added.map(p => p.number), 'left:', removed.map(p => p.number))
675
+ })
676
+ ```
677
+
678
+ A group call is one call with several participants, so it uses one slot in `maxConcurrentCalls`.
679
+
680
+ </details>
681
+
682
+ <details> <summary>Call Links & Rooms</summary>
683
+
684
+ ```javascript
685
+ // create a room, the call stays open until you hang up
686
+ const room = await voip.createRoom('./song.mp3', '480p', {
687
+ requireApproval: true, // waiting room, approve people with call.admit()
688
+ loop: true
689
+ })
690
+ console.log(room.link)
691
+
692
+ // join an existing link
693
+ const joined = await voip.joinLink('https://call.whatsapp.com/voice/xxxx', './song.mp3')
694
+
695
+ // read the link of a call, and check a link before joining
696
+ const link = await voip.getLink(room) // or getLink(callId)
697
+ const info = await voip.previewLink('https://call.whatsapp.com/voice/xxxx')
698
+ ```
699
+
700
+ - `createRoom()` sets `autoEndCall: false` unless you pass your own.
701
+ - `joinLink()` uses a 10 minute safety timeout by default (`safetyMs` changes it). See Multi Call for what happens when it fires.
702
+ - `requireApproval` in `createRoom()` turns the waiting room on once the call is connected.
703
+
704
+ </details>
705
+
706
+ <details> <summary>Helpers by Call ID</summary>
707
+
708
+ ```javascript
709
+ voip.activeCalls() // summaries of active calls
710
+ voip.info(callId) // details of one call, or null
711
+ voip.silent(callId, true)
712
+ voip.mute(callId, true)
713
+ voip.react(callId, '👍')
714
+ voip.hand(callId, true)
715
+ voip.add(callId, '628111111111')
716
+ voip.admit(callId, '628111111111')
717
+ voip.deny(callId, '628111111111')
718
+ voip.approval(callId, true)
719
+ voip.link(callId)
720
+ ```
721
+
722
+ All helpers except `info()` throw `No active call with id ...` if the call is gone.
723
+
724
+ </details>
725
+
635
726
  <details> <summary>Multi Call</summary>
636
727
 
637
728
  ```javascript
@@ -665,9 +756,9 @@ await voip.end(true) // only release the slots
665
756
  ```
666
757
 
667
758
  - `maxConcurrentCalls` defaults to `1`. Each call gets its own relay, codec and audio.
668
- - Incoming calls count toward the limit too.
759
+ - Incoming calls, group calls, call links, and rooms count toward the limit too.
669
760
  - A call over the limit throws `Maximum concurrent calls reached`. In `callMany()` it is returned as `error` for that number and the rest still go through.
670
761
  - `callMany()` takes the same media and options as `call()` and calls duplicate numbers once.
671
- - A safety timeout emits `error` if a call never ends (starts at 105s).
762
+ - A safety timeout emits `error` if a call never ends. It starts at 105s, or 10 minutes for `joinLink()` and `createRoom()`. When a playlist item starts, video items reset it to 10 minutes and audio items clear it. The call is not hung up by the timeout, so call `hangup()` yourself when you are done.
672
763
 
673
764
  </details>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hiroosy/baileys-lite",
3
- "version": "0.3.8",
4
- "description": "A Lightweight Baileys built with NodeJs 18+",
3
+ "version": "0.4.0",
4
+ "description": "A Lightweight Baileys built with Pure NodeJs 18+",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/HirooSy/baileys-lite.git"
@@ -6,7 +6,9 @@ export class WaVoipCoordinator {
6
6
  deps;
7
7
  logger;
8
8
  unregisterHandlers = [];
9
+ ctx;
9
10
  constructor(ctx, options = {}) {
11
+ this.ctx = ctx;
10
12
  this.deps = ctx.deps;
11
13
  this.logger = ctx.logger.child({ scope: 'voip' }, { level: options.logLevel });
12
14
  this.manager = new WaCallManager({
@@ -21,6 +23,39 @@ export class WaVoipCoordinator {
21
23
  async startCall(options) {
22
24
  return this.manager.startCall(options);
23
25
  }
26
+ async startGroupCall(options) {
27
+ return this.manager.startGroupCall(options);
28
+ }
29
+ async createCallLink(options) {
30
+ return this.manager.createCallLink(options);
31
+ }
32
+ async queryCallLink(tokenOrUrl, options) {
33
+ return this.manager.queryCallLink(tokenOrUrl, options);
34
+ }
35
+ async joinCallLink(tokenOrUrl, options) {
36
+ return this.manager.joinCallLink(tokenOrUrl, options);
37
+ }
38
+ async addGroupParticipant(callId, target) {
39
+ return this.manager.addGroupParticipant(callId, target);
40
+ }
41
+ async ringGroupParticipant(callId, target) {
42
+ return this.manager.ringGroupParticipant(callId, target);
43
+ }
44
+ async setApprovalRequired(callId, enabled) {
45
+ return this.manager.setApprovalRequired(callId, enabled);
46
+ }
47
+ async admitParticipant(callId, jid) {
48
+ return this.manager.admitParticipant(callId, jid);
49
+ }
50
+ async denyParticipant(callId, jid) {
51
+ return this.manager.denyParticipant(callId, jid);
52
+ }
53
+ async getCallLink(callId) {
54
+ return this.manager.getCallLink(callId);
55
+ }
56
+ getParticipants(callId) {
57
+ return this.manager.getParticipants(callId);
58
+ }
24
59
  async acceptCall(callId) {
25
60
  return this.manager.acceptCall(callId);
26
61
  }
@@ -94,10 +129,22 @@ export class WaVoipCoordinator {
94
129
  return this;
95
130
  }
96
131
  dispose() {
132
+ this.suspendIncoming();
133
+ this.manager.destroy();
134
+ }
135
+ suspendIncoming() {
97
136
  for (const unregister of this.unregisterHandlers.splice(0)) {
98
137
  unregister();
99
138
  }
100
- this.manager.destroy();
139
+ }
140
+ resumeIncoming() {
141
+ this.registerIncomingHandlers(this.ctx);
142
+ }
143
+ notifyReconnecting() {
144
+ this.manager.notifyReconnecting();
145
+ }
146
+ notifyReconnected() {
147
+ this.manager.notifyReconnected();
101
148
  }
102
149
  registerIncomingHandlers(ctx) {
103
150
  this.unregisterHandlers.push(ctx.registerIncomingHandler({
@@ -151,6 +198,15 @@ export class WaVoipCoordinator {
151
198
  this.manager.on('call_screen_share', (call, share) => {
152
199
  ctx.emit('voip_call_screen_share', { call, share });
153
200
  });
201
+ this.manager.on('call_group_state', (call, state) => {
202
+ ctx.emit('voip_call_group_state', { call, state });
203
+ });
204
+ this.manager.on('call_waiting_room', (call, room) => {
205
+ ctx.emit('voip_call_waiting_room', { call, room });
206
+ });
207
+ this.manager.on('call_participant_audio', (call, participantJid, pcm) => {
208
+ ctx.emit('voip_call_participant_audio', { call, participantJid, pcm });
209
+ });
154
210
  this.manager.on('call_error', (error) => {
155
211
  ctx.emit('voip_call_error', error);
156
212
  });
@@ -1,15 +1,15 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import { createNoopLogger } from '../shim/core.js';
3
3
  import { isLidJid } from '../shim/protocol.js';
4
- import { hasNodeChild } from '../shim/transport.js';
4
+ import { findNodeChild, hasNodeChild } from '../shim/transport.js';
5
5
  import { resolvePositive, toError } from '../shim/util.js';
6
6
  import { generateCallKey } from '../crypto/encryption.js';
7
7
  import { WaAudioEngine } from '../media/WaAudioEngine.js';
8
8
  import { parseRelayFromAck } from '../relay/relay-ack.js';
9
- import { buildOfferStanza, decryptCallKey, extractNodeInfo, generateCallId } from '../signaling/signaling.js';
9
+ import { buildCallLinkCreateStanza, buildCallLinkJoinStanza, buildCallLinkQueryStanza, buildCallLinkUrl, buildInitialGroupOfferStanza, buildOfferStanza, callJidFor, decryptCallKey, extractNodeInfo, generateCallId, generateCallStanzaId, GroupCapability, parseCallLink, parseCallLinkCreateAck, parseCallLinkJoinAck, parseCallLinkQueryAck, parseGroupInviteSnapshot } from '../signaling/signaling.js';
10
10
  import { CallDirection, CallMediaType, CallState, EndCallReason } from '../types.js';
11
11
  import { CallInfo } from './call-state.js';
12
- import { WaCallMediaSession } from './WaCallMediaSession.js';
12
+ import { listUserDevices, resolveUserLid, stripDevice, WaCallMediaSession, WaGroupCallSession } from './WaCallMediaSession.js';
13
13
  const DEFAULT_MAX_CONCURRENT_CALLS = 1;
14
14
  export class WaCallManager extends EventEmitter {
15
15
  deps;
@@ -17,6 +17,9 @@ export class WaCallManager extends EventEmitter {
17
17
  logger;
18
18
  maxConcurrentCalls;
19
19
  calls = new Map();
20
+ pendingGroupEvents = new Map();
21
+ linkRequests = new Map();
22
+ linkJoinsInFlight = 0;
20
23
  constructor(config) {
21
24
  super();
22
25
  this.deps = config.deps;
@@ -53,6 +56,223 @@ export class WaCallManager extends EventEmitter {
53
56
  this.emitState(info);
54
57
  return callId;
55
58
  }
59
+ assertCapacity() {
60
+ if (this.activeCallCount >= this.maxConcurrentCalls) {
61
+ throw new Error(`max concurrent calls reached (${this.maxConcurrentCalls})`);
62
+ }
63
+ }
64
+ async startGroupCall(options) {
65
+ this.assertCapacity();
66
+ const callId = generateCallId();
67
+ const mediaType = options.isVideo ? CallMediaType.Video : CallMediaType.Audio;
68
+ const creds = this.deps.authClient.getCurrentCredentials();
69
+ const selfLid = creds?.meLid || creds?.meJid || '';
70
+ const selfUser = stripDevice(selfLid);
71
+ const targets = [...new Set((await Promise.all([...new Set(options.targets ?? [])].map((target) => resolveUserLid(this.deps, target)))).map(stripDevice))].filter((lid) => lid !== selfUser);
72
+ if (targets.length < 2) {
73
+ throw new Error('a group call needs at least two participants besides yourself');
74
+ }
75
+ const participants = [{ jid: selfUser, devices: [{ jid: selfLid, capabilityVersion: 1, capability: GroupCapability.offer }] }];
76
+ for (const lid of targets) {
77
+ const devices = await listUserDevices(this.deps, lid);
78
+ if (devices.length === 0) {
79
+ throw new Error(`no reachable devices for ${lid}`);
80
+ }
81
+ participants.push({ jid: lid, devices: devices.map((jid) => ({ jid })) });
82
+ }
83
+ const info = CallInfo.newGroupOutgoing(callId, callJidFor(callId), selfLid, mediaType, options.groupJid);
84
+ const session = this.createSession(info, { videoConfig: options.videoConfig });
85
+ try {
86
+ await session.initMedia(selfLid);
87
+ const stanza = buildInitialGroupOfferStanza({ callId, creator: selfLid, groupJid: options.groupJid, participants, video: options.isVideo ?? false });
88
+ stanza.attrs.id = generateCallStanzaId();
89
+ session.offerStanzaId = stanza.attrs.id;
90
+ await this.deps.lowLevelCoordinator.sendNode(stanza);
91
+ }
92
+ catch (err) {
93
+ session.cleanup();
94
+ this.calls.delete(callId);
95
+ throw err;
96
+ }
97
+ info.applyTransition({ type: 'offer_sent' });
98
+ this.emitState(info);
99
+ return callId;
100
+ }
101
+ async createCallLink(options = {}) {
102
+ const media = options.isVideo ? 'video' : 'audio';
103
+ const response = await this.deps.lowLevelCoordinator.query(buildCallLinkCreateStanza(media, generateCallStanzaId()), 30000);
104
+ const link = parseCallLinkCreateAck(response);
105
+ return { token: link.token, media: link.media, isVideo: link.media === 'video', url: buildCallLinkUrl(link.token, link.media) };
106
+ }
107
+ async queryCallLink(tokenOrUrl, options = {}) {
108
+ const { token, media: linkMedia } = parseCallLink(tokenOrUrl);
109
+ const media = options.isVideo === undefined ? linkMedia ?? 'audio' : options.isVideo ? 'video' : 'audio';
110
+ const response = await this.deps.lowLevelCoordinator.query(buildCallLinkQueryStanza(token, media, generateCallStanzaId()), 30000);
111
+ const preview = parseCallLinkQueryAck(response);
112
+ return { ...preview, isVideo: preview.media === 'video', url: buildCallLinkUrl(preview.token, preview.media) };
113
+ }
114
+ async joinCallLink(tokenOrUrl, options = {}) {
115
+ this.assertCapacity();
116
+ const { token, media: linkMedia } = parseCallLink(tokenOrUrl);
117
+ const media = options.isVideo === undefined ? linkMedia ?? 'audio' : options.isVideo ? 'video' : 'audio';
118
+ const creds = this.deps.authClient.getCurrentCredentials();
119
+ const selfLid = creds?.meLid || creds?.meJid || '';
120
+ this.linkJoinsInFlight++;
121
+ try {
122
+ const response = await this.deps.lowLevelCoordinator.query(buildCallLinkJoinStanza(token, media, generateCallStanzaId()), 30000);
123
+ const result = parseCallLinkJoinAck(response);
124
+ const info = CallInfo.newLinkJoin(result.callId, callJidFor(result.callId), selfLid, media === 'video' ? CallMediaType.Video : CallMediaType.Audio, token);
125
+ info.callCreator = result.callCreator;
126
+ info.linkUrl = buildCallLinkUrl(token, media);
127
+ const session = this.createSession(info, { videoConfig: options.videoConfig });
128
+ try {
129
+ await session.initMedia(selfLid);
130
+ await session.beginLinkJoin(result);
131
+ await this.flushGroupEvents(result.callId);
132
+ }
133
+ catch (err) {
134
+ session.cleanup();
135
+ this.calls.delete(result.callId);
136
+ throw err;
137
+ }
138
+ return result.callId;
139
+ }
140
+ finally {
141
+ this.linkJoinsInFlight--;
142
+ if (this.linkJoinsInFlight === 0) {
143
+ this.pendingGroupEvents.clear();
144
+ }
145
+ }
146
+ }
147
+ async getCallLink(callId) {
148
+ const info = this.getCall(callId);
149
+ if (!info) {
150
+ throw new Error(`Unknown call ${callId}`);
151
+ }
152
+ if (info.linkUrl) {
153
+ return info.linkUrl;
154
+ }
155
+ if (!this.linkRequests.has(callId)) {
156
+ this.linkRequests.set(callId, this.createCallLink({ isVideo: info.mediaType === CallMediaType.Video })
157
+ .then((link) => {
158
+ info.linkUrl = link.url;
159
+ return link.url;
160
+ })
161
+ .finally(() => this.linkRequests.delete(callId)));
162
+ }
163
+ return this.linkRequests.get(callId);
164
+ }
165
+ getGroupSessionOrThrow(callId) {
166
+ const session = this.getSessionOrThrow(callId);
167
+ if (!(session instanceof WaGroupCallSession)) {
168
+ throw new Error(`Call ${callId} is not a group call`);
169
+ }
170
+ return session;
171
+ }
172
+ async addGroupParticipant(callId, target) {
173
+ await this.getGroupSessionOrThrow(callId).addParticipant(target);
174
+ }
175
+ async ringGroupParticipant(callId, target) {
176
+ await this.getGroupSessionOrThrow(callId).ringParticipant(target);
177
+ }
178
+ async setApprovalRequired(callId, enabled) {
179
+ await this.getGroupSessionOrThrow(callId).setApprovalRequired(enabled);
180
+ }
181
+ async admitParticipant(callId, jid) {
182
+ await this.getGroupSessionOrThrow(callId).admitParticipant(jid);
183
+ }
184
+ async denyParticipant(callId, jid) {
185
+ await this.getGroupSessionOrThrow(callId).denyParticipant(jid);
186
+ }
187
+ getParticipants(callId) {
188
+ return this.getGroupSessionOrThrow(callId).getParticipants();
189
+ }
190
+ bufferGroupEvent(node, method) {
191
+ const callId = extractNodeInfo(node)?.callId;
192
+ if (!callId || this.linkJoinsInFlight === 0) {
193
+ return;
194
+ }
195
+ const queue = this.pendingGroupEvents.get(callId) ?? [];
196
+ queue.push({ node, method });
197
+ this.pendingGroupEvents.set(callId, queue);
198
+ }
199
+ async flushGroupEvents(callId) {
200
+ const queue = this.pendingGroupEvents.get(callId) ?? [];
201
+ this.pendingGroupEvents.delete(callId);
202
+ const session = this.calls.get(callId);
203
+ for (const { node, method } of queue) {
204
+ await session?.[method]?.(node);
205
+ }
206
+ }
207
+ async handleGroupUpdate(node) {
208
+ const session = this.resolveSessionFromNode(node);
209
+ if (!session) {
210
+ this.bufferGroupEvent(node, 'handleGroupUpdate');
211
+ return;
212
+ }
213
+ await session.handleGroupUpdate?.(node);
214
+ }
215
+ async handleGroupEncRekey(node) {
216
+ const session = this.resolveSessionFromNode(node);
217
+ if (!session) {
218
+ this.bufferGroupEvent(node, 'handleGroupEncRekey');
219
+ return;
220
+ }
221
+ await session.handleGroupEncRekey?.(node);
222
+ }
223
+ handleWaitingRoomUpdate(node) {
224
+ const session = this.resolveSessionFromNode(node);
225
+ if (!session) {
226
+ this.bufferGroupEvent(node, 'handleWaitingRoomUpdate');
227
+ return;
228
+ }
229
+ session.handleWaitingRoomUpdate?.(node);
230
+ }
231
+ async handleGroupOffer(nodeInfo) {
232
+ const callId = nodeInfo.callId;
233
+ let snapshot;
234
+ try {
235
+ snapshot = parseGroupInviteSnapshot(nodeInfo.innerNode);
236
+ }
237
+ catch (err) {
238
+ this.logger.warn('group invite parse failed', { callId, message: toError(err).message });
239
+ return;
240
+ }
241
+ const callCreator = nodeInfo.innerNode.attrs?.['call-creator'];
242
+ const mediaType = hasNodeChild(nodeInfo.innerNode, 'video') ? CallMediaType.Video : CallMediaType.Audio;
243
+ const info = CallInfo.newGroupIncoming(callId, callJidFor(callId), callCreator, undefined, mediaType, snapshot.groupJid);
244
+ const atCapacity = this.activeCallCount >= this.maxConcurrentCalls;
245
+ const session = this.createSession(info, { acceptBlocked: atCapacity });
246
+ session.inviteSnapshot = snapshot;
247
+ if (!atCapacity) {
248
+ try {
249
+ await this.activateGroupInvite(session);
250
+ }
251
+ catch (err) {
252
+ this.logger.error('incoming group call activation failed', { callId, message: toError(err).message });
253
+ try {
254
+ info.applyTransition({ type: 'terminated', reason: EndCallReason.Failed });
255
+ }
256
+ catch { }
257
+ this.emit('call_ended', info);
258
+ this.emitState(info);
259
+ session.cleanup();
260
+ this.calls.delete(callId);
261
+ await this.maybeUnblockWaitingCalls();
262
+ return;
263
+ }
264
+ }
265
+ this.emit('call_incoming', info);
266
+ this.emitState(info);
267
+ }
268
+ async activateGroupInvite(session) {
269
+ const creds = this.deps.authClient.getCurrentCredentials();
270
+ await session.initMedia(creds?.meLid || creds?.meJid || '');
271
+ await session.sendIncomingPreaccept();
272
+ if (session.inviteSnapshot) {
273
+ await session.processGroupSnapshot(session.inviteSnapshot);
274
+ }
275
+ }
56
276
  async acceptCall(callId) {
57
277
  const session = this.getSessionOrThrow(callId);
58
278
  if (!session.info.canAccept) {
@@ -158,6 +378,10 @@ export class WaCallManager extends EventEmitter {
158
378
  existing.cleanup();
159
379
  this.calls.delete(callId);
160
380
  }
381
+ if (findNodeChild(nodeInfo.innerNode, 'group_info')) {
382
+ await this.handleGroupOffer(nodeInfo);
383
+ return;
384
+ }
161
385
  const callCreator = nodeInfo.innerNode.attrs?.['call-creator'] || peerJid;
162
386
  const isVideo = hasNodeChild(nodeInfo.innerNode, 'video');
163
387
  const callKey = await decryptCallKey(this.deps, nodeInfo.innerNode, peerJid, this.logger.child({ component: 'signaling' }));
@@ -226,6 +450,9 @@ export class WaCallManager extends EventEmitter {
226
450
  await session.handleCallTransport(node);
227
451
  }
228
452
  async handleCallAck(node) {
453
+ if (['link_create', 'link_query', 'link_join'].includes(node.attrs?.type)) {
454
+ return;
455
+ }
229
456
  const session = this.resolveSessionForOfferAck(node);
230
457
  if (!session)
231
458
  return;
@@ -277,10 +504,26 @@ export class WaCallManager extends EventEmitter {
277
504
  const session = this.resolveSessionFromNode(node);
278
505
  if (!session)
279
506
  return;
280
- session.handleCallTerminate();
507
+ if (session.handleCallTerminate(node) === false) {
508
+ return;
509
+ }
281
510
  this.calls.delete(session.callId);
282
511
  await this.maybeUnblockWaitingCalls();
283
512
  }
513
+ notifyReconnecting() {
514
+ for (const session of this.calls.values()) {
515
+ if (session.info.isActive && !session.info.isEnded) {
516
+ session.delegate.emitReconnecting(session.info, { attempt: 0, max: 0 });
517
+ }
518
+ }
519
+ }
520
+ notifyReconnected() {
521
+ for (const session of this.calls.values()) {
522
+ if (session.info.isActive && !session.info.isEnded && !session.reconnecting) {
523
+ session.delegate.emitReconnected(session.info);
524
+ }
525
+ }
526
+ }
284
527
  destroy() {
285
528
  for (const session of this.calls.values()) {
286
529
  session.cleanup();
@@ -313,7 +556,7 @@ export class WaCallManager extends EventEmitter {
313
556
  info.stateData.acceptBlocked = true;
314
557
  }
315
558
  const sessionLogger = this.logger.child({ callId: info.callId });
316
- const session = new WaCallMediaSession({
559
+ const session = new (info.isGroup ? WaGroupCallSession : WaCallMediaSession)({
317
560
  deps: this.deps,
318
561
  logger: sessionLogger,
319
562
  info,
@@ -333,7 +576,10 @@ export class WaCallManager extends EventEmitter {
333
576
 
334
577
  emitVideoState: (call, videoState) => this.emit('call_video_state', call, videoState),
335
578
 
336
- emitInboundVideo: (call, au) => this.emit('call_inbound_video', call, au)
579
+ emitInboundVideo: (call, au, participantJid) => this.emit('call_inbound_video', call, au, participantJid),
580
+ emitGroupState: (call, state) => this.emit('call_group_state', call, state),
581
+ emitWaitingRoom: (call, room) => this.emit('call_waiting_room', call, room),
582
+ emitParticipantAudio: (call, participantJid, pcm) => this.emit('call_participant_audio', call, participantJid, pcm)
337
583
  }
338
584
  });
339
585
  this.calls.set(info.callId, session);
@@ -358,6 +604,14 @@ export class WaCallManager extends EventEmitter {
358
604
  return session;
359
605
  }
360
606
  resolveSessionForOfferAck(node) {
607
+ const stanzaId = node.attrs?.id;
608
+ if (stanzaId) {
609
+ for (const session of this.calls.values()) {
610
+ if (session.offerStanzaId === stanzaId) {
611
+ return session;
612
+ }
613
+ }
614
+ }
361
615
  const callId = node.attrs?.['call-id'];
362
616
  if (callId) {
363
617
  const session = this.calls.get(callId);
@@ -406,6 +660,11 @@ export class WaCallManager extends EventEmitter {
406
660
  session.info.stateData.acceptBlocked = false;
407
661
  const creds = this.deps.authClient.getCurrentCredentials();
408
662
  const selfLid = creds?.meLid || creds?.meJid || '';
663
+ if (session.info.isGroup) {
664
+ await this.activateGroupInvite(session);
665
+ this.emitState(session.info);
666
+ return;
667
+ }
409
668
  await session.initMedia(selfLid, session.info.peerJid);
410
669
  await session.sendIncomingPreaccept(session.info.peerJid);
411
670
  await session.sendIncomingRelayLatency();