/*** * Internal utils for callingx library usage from video-client. * See @./registerSDKGlobals.ts for more usage details. */ import { Platform } from 'react-native'; import type { EndCallReason } from '@stream-io/react-native-callingx'; import { getCallingxLibIfAvailable } from '../../push/libs/callingx'; import type { Call, MemberResponse, StreamVideoParticipant, } from '@stream-io/video-client'; import { CallingState, videoLoggerSystem } from '@stream-io/video-client'; const CallingxModule = getCallingxLibIfAvailable(); /** * Gets the call display name. To be used for display in native call screen. */ export function getCallDisplayName( callMembers: MemberResponse[] | undefined, participants: StreamVideoParticipant[] | undefined, currentUserId: string | undefined, ): string { if (!callMembers || !participants || !currentUserId) { return 'Call'; } let names: string[] = []; if (callMembers.length > 0) { // for ringing calls, members array contains all call members from the very early state and participants array is empty in the beginning names = callMembers.flatMap((member) => member.user.id !== currentUserId && member.user.name ? [member.user.name] : [], ); } else if (participants.length > 0) { // for non-ringing calls, members array is empty and we rely on participants array there names = participants.flatMap((participant) => participant.userId !== currentUserId && participant.name ? [participant.name] : [], ); } // if no names are found, we use the name of the current user if (names.length === 0) { names = [ participants.find((participant) => participant.userId === currentUserId) ?.name || 'Call', ]; } return names.sort().join(', '); } /** * Args shared by the callingx call registration APIs: * `(callId, phoneNumber, callerName, hasVideo)`. */ function getCallingxCallArgs(call: Call): [string, string, string, boolean] { const callDisplayName = call.state.custom?.display_name || getCallDisplayName( call.state.members, call.state.participants, call.currentUserId, ); const createdByHandle = call.state.createdBy?.id ?? callDisplayName; return [ call.cid, // unique id for call // handle for the native call UI. On iOS it is shown in CallKit Recents and used for // call-back, so we send the caller's user id (matches the Swift SDK). On Android the // self-managed Telecom address is never displayed and callingx wraps it as // `:`, so we send the call id (matches the Android SDK). Platform.OS === 'android' ? call.id : createdByHandle, callDisplayName, // display name for display in call screen call.state.settings?.video?.enabled ?? false, // is video call? ]; } export async function registerOutgoingCall(call: Call) { if ( !CallingxModule || !CallingxModule.isSetup || call.isOwnTracksLoopbackAllowed ) { return; } const isOutcomingCall = call.ringing && call.isCreatedByMe; if (!isOutcomingCall) { return; } const logger = videoLoggerSystem.getLogger('callingx'); try { logger.debug(`registerOutgoingCall: Registering outgoing call ${call.cid}`); await CallingxModule.startCall(...getCallingxCallArgs(call)); } catch (error) { logger.error( `registerOutgoingCall: Error registering outgoing call in callingx: ${call.cid}`, error, ); } } /** * Starts the call in the callingx library. * It is done by client on every join * Does either of the following: * 1. Sets the state for outgoing calls in the callingx library * 2. Displays the incoming call in the callingx library * 3. Optionally for non-ringing calls also when ongoing calls are enabled. */ export async function joinCallingxCall( call: Call, activeCalls: Call[], isCancelled?: () => boolean, ) { if ( !CallingxModule || !CallingxModule.isSetup || call.isOwnTracksLoopbackAllowed ) { return; } const logger = videoLoggerSystem.getLogger('callingx'); const isNonRingingCallingxRegisteredCall = (c: Call) => !c.ringing && !c.isOwnTracksLoopbackAllowed && CallingxModule.isOngoingCallsEnabled; // should we not register this call in callingx? if (!call.ringing && !CallingxModule.isOngoingCallsEnabled) { return; } try { logger.debug('joinCallingxCall: checking active calls'); const activeCallsToLeave = activeCalls.filter( (c) => c.cid !== call.cid && (c.ringing || isNonRingingCallingxRegisteredCall(c)) && c.state.callingState !== CallingState.LEFT, ); for (const activeCall of activeCallsToLeave) { logger.debug( `joinCallingxCall: leaving currently-active-call:${activeCall.cid} before joining the call:${call.cid}`, ); await activeCall.leave({ reason: 'cancel' }).catch((e) => { logger.error( `joinCallingxCall: failed to leave active call ${activeCall.cid}`, e, ); }); } // Leaving the other calls above can take arbitrarily long, and this join may // have been cancelled meanwhile. Registering now would create a native call // nobody owns. The caller decides, not the call's state: a `Call` reused for // a fresh ring is still `LEFT` here, because `setup()` runs after this. if (isCancelled?.()) { logger.debug( `joinCallingxCall: skipping registration for ${call.cid}: join cancelled while waiting for other calls`, ); return; } logger.debug( `joinCallingxCall: Joining call ${call.cid} ringingType:${call.ringing} isCreatedByMe: ${call.isCreatedByMe}`, ); const callArgs = getCallingxCallArgs(call); if (call.ringing && !call.isCreatedByMe) { await CallingxModule.displayIncomingCall(...callArgs); // never answer a call that was hung up while the OS was displaying it - // the cleanup below ends the registration instead if (isCancelled?.()) return; await CallingxModule.answerIncomingCall(call.cid); } else { await CallingxModule.startCall(...callArgs); } } catch (error) { logger.error( `joinCallingxCall: Error starting call in callingx: ${call.cid} ringingType:${call.ringing} isCreatedByMe: ${call.isCreatedByMe}`, error, ); } finally { // The registration above can outlive the join that asked for it: `leave()` // may land while native is still bringing the call up, and by the time the // caller aborts, the call exists natively with nobody to end it. Ringing // calls have a lifecycle owner that would clean up; ordinary ones do not. // Nothing was registered when the check above already skipped it, and // `endCallingxCall` no-ops for an untracked cid, so this is safe either way. if (isCancelled?.()) { logger.debug( `joinCallingxCall: ending ${call.cid}: join was cancelled while registering`, ); await endCallingxCall(call, 'canceled'); } } } export async function endCallingxCall(call: Call, reason?: EndCallReason) { if ( !CallingxModule || !CallingxModule.isSetup || !CallingxModule.isCallTracked(call.cid) ) { return; } const logger = videoLoggerSystem.getLogger('callingx'); try { logger.debug(`endCallingxCall: Ending call ${call.cid}`); await CallingxModule.endCallWithReason(call.cid, reason ?? 'local'); } catch (error) { logger.error( `endCallingxCall: Error ending call in callingx: ${call.cid}`, error, ); } }