{"version":3,"file":"callEventHandler.js","names":["_logger","require","_call","_event","_client","_groupCall3","_room","RING_GRACE_PERIOD","CallEventHandlerEvent","exports","CallEventHandler","constructor","client","_defineProperty2","default","Map","currentEventBuffer","callEventBuffer","eventBufferPromiseChain","then","evaluateEventBuffer","event","push","content","getContent","call_id","nextSeqByCall","has","set","seq","undefined","nextSeq","get","toDeviceEventBuffers","buffer","index","findIndex","e","splice","callId","nextEvent","shift","calls","candidateEventsByCall","start","on","ClientEvent","Sync","onSync","RoomEvent","Timeline","onRoomTimeline","ToDeviceEvent","onToDeviceEvent","stop","removeListener","eventBuffer","Promise","all","map","decryptEventIfNeeded","callEvents","filter","eventType","getType","startsWith","ignoreCallIds","Set","EventType","CallAnswer","CallHangup","add","CallInvite","handleCallEvent","logger","error","_getGroupCallById","_getGroupCallById$roo","emit","ReceivedVoipEvent","callRoomId","getRoomId","groupCallEventHandler","getGroupCallById","conf_id","room","roomId","groupCallId","type","senderId","getSender","call","opponentDeviceId","groupCall","warn","device_id","GroupCallEvent","Error","GroupCallUnknownDeviceError","dest_session_id","getSessionId","weSentTheEvent","credentials","userId","getDeviceId","_this$client$getTurnS","_createNewMatrixCall","_groupCall","getLocalAge","lifetime","state","CallState","Ended","invitee","getUserId","timeUntilTurnCresExpire","getTurnServersExpiry","Date","now","info","createNewMatrixCall","forceTURN","opponentSessionId","sender_session_id","log","stats","getGroupCallStats","initStats","initWithInvite","CallError","code","GroupCallErrorCode","UnknownDevice","_groupCall2","ev","onRemoteIceCandidatesReceived","existingCall","thisCall","values","_call$getOpponentMemb","isCalling","WaitLocalMedia","CreateOffer","InviteSent","includes","direction","CallDirection","Outbound","getOpponentMember","replacedBy","hangup","CallErrorCode","Replaced","Incoming","CallCandidates","CallReject","_createNewMatrixCall2","initWithHangup","onHangupReceived","onRejectReceived","delete","hasPeerConnection","party_id","ourPartyId","Ringing","onAnsweredElsewhere","onAnswerReceived","CallSelectAnswer","onSelectAnswerReceived","CallNegotiate","onNegotiateReceived","CallAssertedIdentity","CallAssertedIdentityPrefix","onAssertedIdentityReceived","CallSDPStreamMetadataChanged","CallSDPStreamMetadataChangedPrefix","onSDPStreamMetadataChangedReceived"],"sources":["../../src/webrtc/callEventHandler.ts"],"sourcesContent":["/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"../models/event\";\nimport { logger } from \"../logger\";\nimport { CallDirection, CallError, CallErrorCode, CallState, createNewMatrixCall, MatrixCall } from \"./call\";\nimport { EventType } from \"../@types/event\";\nimport { ClientEvent, MatrixClient } from \"../client\";\nimport { MCallAnswer, MCallHangupReject } from \"./callEventTypes\";\nimport { GroupCall, GroupCallErrorCode, GroupCallEvent, GroupCallUnknownDeviceError } from \"./groupCall\";\nimport { RoomEvent } from \"../models/room\";\n\n// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some\n// time to press the 'accept' button\nconst RING_GRACE_PERIOD = 3000;\n\nexport enum CallEventHandlerEvent {\n Incoming = \"Call.incoming\",\n}\n\nexport type CallEventHandlerEventHandlerMap = {\n /**\n * Fires whenever an incoming call arrives.\n * @param call - The incoming call.\n * @example\n * ```\n * matrixClient.on(\"Call.incoming\", function(call){\n * call.answer(); // auto-answer\n * });\n * ```\n */\n [CallEventHandlerEvent.Incoming]: (call: MatrixCall) => void;\n};\n\nexport class CallEventHandler {\n // XXX: Most of these are only public because of the tests\n public calls: Map;\n public callEventBuffer: MatrixEvent[];\n public nextSeqByCall: Map = new Map();\n public toDeviceEventBuffers: Map> = new Map();\n\n private client: MatrixClient;\n private candidateEventsByCall: Map>;\n private eventBufferPromiseChain?: Promise;\n\n public constructor(client: MatrixClient) {\n this.client = client;\n this.calls = new Map();\n // The sync code always emits one event at a time, so it will patiently\n // wait for us to finish processing a call invite before delivering the\n // next event, even if that next event is a hangup. We therefore accumulate\n // all our call events and then process them on the 'sync' event, ie.\n // each time a sync has completed. This way, we can avoid emitting incoming\n // call events if we get both the invite and answer/hangup in the same sync.\n // This happens quite often, eg. replaying sync from storage, catchup sync\n // after loading and after we've been offline for a bit.\n this.callEventBuffer = [];\n this.candidateEventsByCall = new Map>();\n }\n\n public start(): void {\n this.client.on(ClientEvent.Sync, this.onSync);\n this.client.on(RoomEvent.Timeline, this.onRoomTimeline);\n this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n }\n\n public stop(): void {\n this.client.removeListener(ClientEvent.Sync, this.onSync);\n this.client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);\n this.client.removeListener(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n }\n\n private onSync = (): void => {\n // Process the current event buffer and start queuing into a new one.\n const currentEventBuffer = this.callEventBuffer;\n this.callEventBuffer = [];\n\n // Ensure correct ordering by only processing this queue after the previous one has finished processing\n if (this.eventBufferPromiseChain) {\n this.eventBufferPromiseChain = this.eventBufferPromiseChain.then(() =>\n this.evaluateEventBuffer(currentEventBuffer),\n );\n } else {\n this.eventBufferPromiseChain = this.evaluateEventBuffer(currentEventBuffer);\n }\n };\n\n private async evaluateEventBuffer(eventBuffer: MatrixEvent[]): Promise {\n await Promise.all(eventBuffer.map((event) => this.client.decryptEventIfNeeded(event)));\n\n const callEvents = eventBuffer.filter((event) => {\n const eventType = event.getType();\n return eventType.startsWith(\"m.call.\") || eventType.startsWith(\"org.matrix.call.\");\n });\n\n const ignoreCallIds = new Set();\n\n // inspect the buffer and mark all calls which have been answered\n // or hung up before passing them to the call event handler.\n for (const event of callEvents) {\n const eventType = event.getType();\n\n if (eventType === EventType.CallAnswer || eventType === EventType.CallHangup) {\n ignoreCallIds.add(event.getContent().call_id);\n }\n }\n\n // Process call events in the order that they were received\n for (const event of callEvents) {\n const eventType = event.getType();\n const callId = event.getContent().call_id;\n\n if (eventType === EventType.CallInvite && ignoreCallIds.has(callId)) {\n // This call has previously been answered or hung up: ignore it\n continue;\n }\n\n try {\n await this.handleCallEvent(event);\n } catch (e) {\n logger.error(\"CallEventHandler evaluateEventBuffer() caught exception handling call event\", e);\n }\n }\n }\n\n private onRoomTimeline = (event: MatrixEvent): void => {\n this.callEventBuffer.push(event);\n };\n\n private onToDeviceEvent = (event: MatrixEvent): void => {\n const content = event.getContent();\n\n if (!content.call_id) {\n this.callEventBuffer.push(event);\n return;\n }\n\n if (!this.nextSeqByCall.has(content.call_id)) {\n this.nextSeqByCall.set(content.call_id, 0);\n }\n\n if (content.seq === undefined) {\n this.callEventBuffer.push(event);\n return;\n }\n\n const nextSeq = this.nextSeqByCall.get(content.call_id) || 0;\n\n if (content.seq !== nextSeq) {\n if (!this.toDeviceEventBuffers.has(content.call_id)) {\n this.toDeviceEventBuffers.set(content.call_id, []);\n }\n\n const buffer = this.toDeviceEventBuffers.get(content.call_id)!;\n const index = buffer.findIndex((e) => e.getContent().seq > content.seq);\n\n if (index === -1) {\n buffer.push(event);\n } else {\n buffer.splice(index, 0, event);\n }\n } else {\n const callId = content.call_id;\n this.callEventBuffer.push(event);\n this.nextSeqByCall.set(callId, content.seq + 1);\n\n const buffer = this.toDeviceEventBuffers.get(callId);\n\n let nextEvent = buffer && buffer.shift();\n\n while (nextEvent && nextEvent.getContent().seq === this.nextSeqByCall.get(callId)) {\n this.callEventBuffer.push(nextEvent);\n this.nextSeqByCall.set(callId, nextEvent.getContent().seq + 1);\n nextEvent = buffer!.shift();\n }\n }\n };\n\n private async handleCallEvent(event: MatrixEvent): Promise {\n this.client.emit(ClientEvent.ReceivedVoipEvent, event);\n\n const content = event.getContent();\n const callRoomId =\n event.getRoomId() || this.client.groupCallEventHandler!.getGroupCallById(content.conf_id)?.room?.roomId;\n const groupCallId = content.conf_id;\n const type = event.getType() as EventType;\n const senderId = event.getSender()!;\n let call = content.call_id ? this.calls.get(content.call_id) : undefined;\n\n let opponentDeviceId: string | undefined;\n\n let groupCall: GroupCall | undefined;\n if (groupCallId) {\n groupCall = this.client.groupCallEventHandler!.getGroupCallById(groupCallId);\n\n if (!groupCall) {\n logger.warn(\n `CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=${groupCallId}, type=${type})`,\n );\n return;\n }\n\n opponentDeviceId = content.device_id;\n\n if (!opponentDeviceId) {\n logger.warn(\n `CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=${senderId})`,\n );\n groupCall.emit(GroupCallEvent.Error, new GroupCallUnknownDeviceError(senderId));\n return;\n }\n\n if (content.dest_session_id !== this.client.getSessionId()) {\n logger.warn(\n \"CallEventHandler handleCallEvent() call event does not match current session id - ignoring\",\n );\n return;\n }\n }\n\n const weSentTheEvent =\n senderId === this.client.credentials.userId &&\n (opponentDeviceId === undefined || opponentDeviceId === this.client.getDeviceId()!);\n\n if (!callRoomId) return;\n\n if (type === EventType.CallInvite) {\n // ignore invites you send\n if (weSentTheEvent) return;\n // expired call\n if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) return;\n // stale/old invite event\n if (call && call.state === CallState.Ended) return;\n\n if (call) {\n logger.warn(\n `CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=${content.call_id})`,\n );\n }\n\n if (content.invitee && content.invitee !== this.client.getUserId()) {\n return; // This invite was meant for another user in the room\n }\n\n const timeUntilTurnCresExpire = (this.client.getTurnServersExpiry() ?? 0) - Date.now();\n logger.info(\n \"CallEventHandler handleCallEvent() current turn creds expire in \" + timeUntilTurnCresExpire + \" ms\",\n );\n call =\n createNewMatrixCall(this.client, callRoomId, {\n forceTURN: this.client.forceTURN,\n opponentDeviceId,\n groupCallId,\n opponentSessionId: content.sender_session_id,\n }) ?? undefined;\n if (!call) {\n logger.log(\n `CallEventHandler handleCallEvent() this client does not support WebRTC (callId=${content.call_id})`,\n );\n // don't hang up the call: there could be other clients\n // connected that do support WebRTC and declining the\n // the call on their behalf would be really annoying.\n return;\n }\n\n call.callId = content.call_id;\n const stats = groupCall?.getGroupCallStats();\n if (stats) {\n call.initStats(stats);\n }\n\n try {\n await call.initWithInvite(event);\n } catch (e) {\n if (e instanceof CallError) {\n if (e.code === GroupCallErrorCode.UnknownDevice) {\n groupCall?.emit(GroupCallEvent.Error, e);\n } else {\n logger.error(e);\n }\n }\n }\n this.calls.set(call.callId, call);\n\n // if we stashed candidate events for that call ID, play them back now\n if (this.candidateEventsByCall.get(call.callId)) {\n for (const ev of this.candidateEventsByCall.get(call.callId)!) {\n call.onRemoteIceCandidatesReceived(ev);\n }\n }\n\n // Were we trying to call that user (room)?\n let existingCall: MatrixCall | undefined;\n for (const thisCall of this.calls.values()) {\n const isCalling = [CallState.WaitLocalMedia, CallState.CreateOffer, CallState.InviteSent].includes(\n thisCall.state,\n );\n\n if (\n call.roomId === thisCall.roomId &&\n thisCall.direction === CallDirection.Outbound &&\n call.getOpponentMember()?.userId === thisCall.invitee &&\n isCalling\n ) {\n existingCall = thisCall;\n break;\n }\n }\n\n if (existingCall) {\n if (existingCall.callId > call.callId) {\n logger.log(\n `CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=${call.callId}, outgoingId=${existingCall.callId})`,\n );\n existingCall.replacedBy(call);\n } else {\n logger.log(\n `CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=${call.callId}, outgoingId=${existingCall.callId})`,\n );\n call.hangup(CallErrorCode.Replaced, true);\n }\n } else {\n this.client.emit(CallEventHandlerEvent.Incoming, call);\n }\n return;\n } else if (type === EventType.CallCandidates) {\n if (weSentTheEvent) return;\n\n if (!call) {\n // store the candidates; we may get a call eventually.\n if (!this.candidateEventsByCall.has(content.call_id)) {\n this.candidateEventsByCall.set(content.call_id, []);\n }\n this.candidateEventsByCall.get(content.call_id)!.push(event);\n } else {\n call.onRemoteIceCandidatesReceived(event);\n }\n return;\n } else if ([EventType.CallHangup, EventType.CallReject].includes(type)) {\n // Note that we also observe our own hangups here so we can see\n // if we've already rejected a call that would otherwise be valid\n if (!call) {\n // if not live, store the fact that the call has ended because\n // we're probably getting events backwards so\n // the hangup will come before the invite\n call =\n createNewMatrixCall(this.client, callRoomId, {\n opponentDeviceId,\n opponentSessionId: content.sender_session_id,\n }) ?? undefined;\n if (call) {\n call.callId = content.call_id;\n call.initWithHangup(event);\n this.calls.set(content.call_id, call);\n }\n } else {\n if (call.state !== CallState.Ended) {\n if (type === EventType.CallHangup) {\n call.onHangupReceived(content as MCallHangupReject);\n } else {\n call.onRejectReceived(content as MCallHangupReject);\n }\n\n // @ts-expect-error typescript thinks the state can't be 'ended' because we're\n // inside the if block where it wasn't, but it could have changed because\n // on[Hangup|Reject]Received are side-effecty.\n if (call.state === CallState.Ended) this.calls.delete(content.call_id);\n }\n }\n return;\n }\n\n // The following events need a call and a peer connection\n if (!call || !call.hasPeerConnection) {\n logger.info(\n `CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=${type})`,\n );\n return;\n }\n // Ignore remote echo\n if (event.getContent().party_id === call.ourPartyId) return;\n\n switch (type) {\n case EventType.CallAnswer:\n if (weSentTheEvent) {\n if (call.state === CallState.Ringing) {\n call.onAnsweredElsewhere(content as MCallAnswer);\n }\n } else {\n call.onAnswerReceived(event);\n }\n break;\n case EventType.CallSelectAnswer:\n call.onSelectAnswerReceived(event);\n break;\n\n case EventType.CallNegotiate:\n call.onNegotiateReceived(event);\n break;\n\n case EventType.CallAssertedIdentity:\n case EventType.CallAssertedIdentityPrefix:\n call.onAssertedIdentityReceived(event);\n break;\n\n case EventType.CallSDPStreamMetadataChanged:\n case EventType.CallSDPStreamMetadataChangedPrefix:\n call.onSDPStreamMetadataChangedReceived(event);\n break;\n }\n }\n}\n"],"mappings":";;;;;;;;AAiBA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AACA,IAAAE,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