@hiroosy/baileys-lite 0.3.9 → 0.4.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.
@@ -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();