Your IP : 3.22.208.84


Current Path : /var/www/axolotl/data/www/arhangelsk.axolotls.ru/bitrix/js/im/call/
Upload File :
Current File : /var/www/axolotl/data/www/arhangelsk.axolotls.ru/bitrix/js/im/call/plain_call.min.js

(function(){BX.namespace("BX.Call");var e={invite:"im.call.invite",cancel:"im.call.cancel",answer:"im.call.answer",decline:"im.call.decline",hangup:"im.call.hangup",ping:"im.call.ping",negotiationNeeded:"im.call.negotiationNeeded",connectionOffer:"im.call.connectionOffer",connectionAnswer:"im.call.connectionAnswer",iceCandidate:"im.call.iceCandidate"};var t={ping:"Call::ping",negotiationNeeded:"Call::negotiationNeeded",connectionOffer:"Call::connectionOffer",connectionAnswer:"Call::connectionAnswer",iceCandidate:"Call::iceCandidate",voiceStarted:"Call::voiceStarted",voiceStopped:"Call::voiceStopped",microphoneState:"Call::microphoneState",hangup:"Call::hangup",userInviteTimeout:"Call::userInviteTimeout"};var n={offerToReceiveVideo:true,offerToReceiveAudio:true};var i=3e4;var a=1e4;var o=5e3;var l=25e3;var s=5500;BX.Call.PlainCall=function(e){this.superclass.constructor.apply(this,arguments);this.callFromMobile=e.callFromMobile;this.state=e.state||"";this.peers=this.initPeers(this.users);this.signaling=new BX.Call.PlainCall.Signaling({call:this});this.deviceList=[];this.turnServer=(BX.browser.IsFirefox()?BX.message("turn_server_firefox"):BX.message("turn_server"))||"turn.calls.bitrix24.com";this.turnServerLogin=BX.message("turn_server_login")||"bitrix";this.turnServerPassword=BX.message("turn_server_password")||"bitrix";this.pingUsersInterval=setInterval(this.pingUsers.bind(this),o);this.pingBackendInterval=setInterval(this.pingBackend.bind(this),l);this.reinviteTimeout=null;this._onUnloadHandler=this._onUnload.bind(this);this.enableMicAutoParameters=e.enableMicAutoParameters!==false;window.addEventListener("unload",this._onUnloadHandler)};BX.extend(BX.Call.PlainCall,BX.Call.AbstractCall);BX.Call.PlainCall.prototype.initPeers=function(e){var t={};for(var n=0;n<e.length;n++){var i=Number(e[n]);if(i==this.userId)continue;t[i]=this.createPeer(i)}return t};BX.Call.PlainCall.prototype.createPeer=function(e){var t=this;return new BX.Call.PlainCall.Peer({call:this,userId:e,ready:e==this.initiatorId,signalingConnected:e==this.initiatorId,isMobile:e==this.initiatorId&&this.callFromMobile,onStreamReceived:function(e){t.runCallback(BX.Call.Event.onStreamReceived,e)},onStreamRemoved:function(e){t.runCallback(BX.Call.Event.onStreamRemoved,e)},onStateChanged:this.__onPeerStateChanged.bind(this),onInviteTimeout:this.__onPeerInviteTimeout.bind(this),onRTCStatsReceived:this.__onPeerRTCStatsReceived.bind(this)})};BX.Call.PlainCall.prototype.getUsers=function(){var e={};for(var t in this.peers){e[t]=this.peers[t].calculatedState}return e};BX.Call.PlainCall.prototype.isReady=function(){return this.ready};BX.Call.PlainCall.prototype.setVideoEnabled=function(e){e=e===true;if(this.videoEnabled==e){return}this.videoEnabled=e;if(this.ready){this.replaceLocalMediaStream()}};BX.Call.PlainCall.prototype.setMuted=function(e){e=!!e;if(this.muted==e){return}this.muted=e;if(this.localStreams["main"]){var t=this.localStreams["main"].getAudioTracks();if(t[0]){t[0].enabled=!this.muted}}this.signaling.sendMicrophoneState(this.users,!this.muted)};BX.Call.PlainCall.prototype.setCameraId=function(e){if(this.cameraId==e){return}this.cameraId=e;if(this.ready&&this.videoEnabled){BX.debounce(this.replaceLocalMediaStream,100,this)()}};BX.Call.PlainCall.prototype.setMicrophoneId=function(e){if(this.microphoneId==e){return}this.microphoneId=e;if(this.ready){BX.debounce(this.replaceLocalMediaStream,100,this)()}};BX.Call.PlainCall.prototype.getCurrentMicrophoneId=function(){if(!this.localStreams["main"]){return this.microphoneId}var e=this.localStreams["main"].getAudioTracks();if(e.length>0){var t=e[0].getSettings();return t.deviceId}else{return this.microphoneId}};BX.Call.PlainCall.prototype.useHdVideo=function(e){this.videoHd=e===true};BX.Call.PlainCall.prototype.setVideoQuality=function(e){};BX.Call.PlainCall.prototype.stopSendingStream=function(e){};BX.Call.PlainCall.prototype.inviteUsers=function(e){var t=this;if(!BX.type.isPlainObject(e)){e={}}var n=BX.type.isArray(e.users)?e.users:Object.keys(this.peers);this.ready=true;if(e.localStream instanceof MediaStream&&!this.localStreams["main"]){this.localStreams["main"]=e.localStream}this.getLocalMediaStream("main",true).then(function(){return t.signaling.inviteUsers({userIds:n,video:t.videoEnabled?"Y":"N"})}).then(function(e){t.runCallback(BX.Call.Event.onJoin,{local:true});for(var i=0;i<n.length;i++){var a=Number(n[i]);if(!t.peers[a]){t.peers[a]=t.createPeer(a);t.runCallback(BX.Call.Event.onUserInvited,{userId:a})}t.peers[a].onInvited();t.scheduleRepeatInvite()}}).catch(function(e){console.error(e);t.runCallback(BX.Call.Event.onCallFailure,e)})};BX.Call.PlainCall.prototype.scheduleRepeatInvite=function(){clearTimeout(this.reinviteTimeout);this.reinviteTimeout=setTimeout(this.repeatInviteUsers.bind(this),s)};BX.Call.PlainCall.prototype.repeatInviteUsers=function(){clearTimeout(this.reinviteTimeout);if(!this.ready){return}var e=[];for(var t in this.peers){if(this.peers.hasOwnProperty(t)&&this.peers[t].calculatedState===BX.Call.UserState.Calling){e.push(t)}}if(e.length===0){return}this.signaling.inviteUsers({userIds:e,video:this.videoEnabled?"Y":"N"}).then(function(){this.scheduleRepeatInvite()}.bind(this))};BX.Call.PlainCall.prototype.getMediaConstraints=function(e){var t={};var n=e.videoEnabled?{}:false;hdVideo=!!e.hdVideo;var i=navigator.mediaDevices.getSupportedConstraints?navigator.mediaDevices.getSupportedConstraints():{};if(this.microphoneId){t.deviceId={ideal:this.microphoneId}}if(!this.enableMicAutoParameters){if(i.echoCancellation){t.echoCancellation=false}if(i.noiseSuppression){t.noiseSuppression=false}if(i.autoGainControl){t.autoGainControl=false}}if(n){if(this.cameraId){n.deviceId={exact:this.cameraId}}if(hdVideo){n.width={max:1920,min:1280};n.height={max:1080,min:720}}else{n.width={ideal:640};n.height={ideal:360}}}return{audio:t,video:n}};BX.Call.PlainCall.prototype.getUserMedia=function(e){return new Promise(function(t,n){var i=e[0];navigator.mediaDevices.getUserMedia(i).then(function(e){t(e)},function(a){this.log("getUserMedia error: ",a);this.log("Current constraints",i);if(e.length>1){this.getUserMedia(e.slice(1)).then(function(e){t(e)},function(e){n(e)})}else{this.log("Last fallback constraints used, failing");n(a)}}.bind(this))}.bind(this))};BX.Call.PlainCall.prototype.getLocalMediaStream=function(e,t){var n=this;if(!BX.type.isNotEmptyString(e)){e="main"}this.log("Requesting access to media devices");return new Promise(function(i,a){if(n.localStreams[e]){return i(n.localStreams[e])}var o=[];if(n.videoEnabled){if(n.videoHd){o.push(n.getMediaConstraints({videoEnabled:true,hdVideo:true}))}o.push(n.getMediaConstraints({videoEnabled:true,hdVideo:false}));if(t){o.push(n.getMediaConstraints({videoEnabled:false}))}}else{o.push(n.getMediaConstraints({videoEnabled:false}))}n.getUserMedia(o).then(function(t){n.log("Local media stream received");n.localStreams[e]=t;n.runCallback(BX.Call.Event.onLocalMediaReceived,{tag:e,stream:t});if(e==="main"){if(n.muted){var a=t.getAudioTracks();if(a[0]){a[0].enabled=false}}}if(n.deviceList.length===0){navigator.mediaDevices.enumerateDevices().then(function(e){n.deviceList=e;n.runCallback(BX.Call.Event.onDeviceListUpdated,{deviceList:n.deviceList})})}i(n.localStreams[e])}).catch(function(t){n.log("Could not get local media stream.",t);n.log("Request constraints: .",o);n.runCallback("onLocalMediaError",{tag:e,error:t});a(t)})})};BX.Call.PlainCall.prototype.startMediaCapture=function(){return this.getLocalMediaStream()};BX.Call.PlainCall.prototype.attachVoiceDetection=function(){if(this.voiceDetection){this.voiceDetection.destroy()}try{this.voiceDetection=new BX.SimpleVAD({mediaStream:this.localStreams["main"],onVoiceStarted:this.onLocalVoiceStarted.bind(this),onVoiceStopped:this.onLocalVoiceStopped.bind(this)})}catch(e){this.log("Could not attach voice detection to media stream")}};BX.Call.PlainCall.prototype.getDisplayMedia=function(){return new Promise(function(e,t){if(window["BXDesktopSystem"]){navigator.mediaDevices.getUserMedia({video:{mandatory:{chromeMediaSource:"screen",maxWidth:1920,maxHeight:1080,maxFrameRate:5}}}).then(function(t){e(t)},function(e){t(e)})}else if(navigator.mediaDevices.getDisplayMedia){navigator.mediaDevices.getDisplayMedia({video:{width:{max:1920},height:{max:1080},frameRate:{max:5}}}).then(function(t){e(t)},function(e){t(e)})}else{console.error("Screen sharing is not supported");t("Screen sharing is not supported")}})};BX.Call.PlainCall.prototype.startScreenSharing=function(){var e=this;if(this.localStreams["screen"]){return}this.getDisplayMedia().then(function(t){e.localStreams["screen"]=t;t.getVideoTracks().forEach(function(t){t.addEventListener("ended",function(){e.stopScreenSharing()})});e.runCallback(BX.Call.Event.onLocalMediaReceived,{tag:"screen",stream:t});if(e.ready){for(var n in e.peers){if(e.peers[n].calculatedState===BX.Call.UserState.Connected){e.peers[n].sendMedia()}}}}).catch(function(e){this.log(e)}.bind(this))};BX.Call.PlainCall.prototype.stopScreenSharing=function(){if(!this.localStreams["screen"]){return}this.localStreams["screen"].getTracks().forEach(function(e){e.stop()});this.localStreams["screen"]=null;this.runCallback(BX.Call.Event.onLocalMediaReceived,{tag:"main",stream:this.localStreams["main"]});for(var e in this.peers){if(this.peers[e].calculatedState===BX.Call.UserState.Connected){this.peers[e].sendMedia()}}};BX.Call.PlainCall.prototype.isScreenSharingStarted=function(){return this.localStreams["screen"]instanceof MediaStream};BX.Call.PlainCall.prototype.onLocalVoiceStarted=function(){this.signaling.sendVoiceStarted({userId:this.users})};BX.Call.PlainCall.prototype.onLocalVoiceStopped=function(){this.signaling.sendVoiceStopped({userId:this.users})};BX.Call.PlainCall.prototype.answer=function(e){var t=this;if(!BX.type.isPlainObject(e)){e={}}if(this.direction!==BX.Call.Direction.Incoming){throw new Error("Only incoming call could be answered")}this.ready=true;this.videoEnabled=e.useVideo==true;this.enableMicAutoParameters=e.enableMicAutoParameters!==false;if(e.localStream instanceof MediaStream){this.localStreams["main"]=e.localStream}return new Promise(function(e,n){t.getLocalMediaStream("main",true).then(function(){t.runCallback(BX.Call.Event.onJoin,{local:true});return t.signaling.sendAnswer()},function(e){t.runCallback(BX.Call.Event.onCallFailure,e)}).then(function(){e()})})};BX.Call.PlainCall.prototype.decline=function(t,n){this.ready=false;var i={callId:this.id,callInstanceId:this.instanceId};if(typeof t!="undefined"){i.code=t}if(typeof n!="undefined"){i.reason=n}BX.CallEngine.getRestClient().callMethod(e.decline,i).then(function(){this.destroy()}.bind(this))};BX.Call.PlainCall.prototype.hangup=function(){if(!this.ready){var e=new Error("Hangup in wrong state");this.log(e);return}var t=new Error;t.name="Call stack:";this.log("Hangup received \n"+t.stack);this.ready=false;return new Promise(function(e,t){for(var n in this.peers){this.peers[n].disconnect()}this.runCallback(BX.Call.Event.onLeave,{local:true});this.signaling.sendHangup({userId:this.users})}.bind(this))};BX.Call.PlainCall.prototype.pingUsers=function(){if(this.ready){this.signaling.sendPingToUsers({userId:this.users})}};BX.Call.PlainCall.prototype.pingBackend=function(){if(this.ready){this.signaling.sendPingToBackend()}};BX.Call.PlainCall.prototype.getState=function(){};BX.Call.PlainCall.prototype.replaceLocalMediaStream=function(e){var t=this;e=e||"main";if(this.localStreams[e]){BX.webrtc.stopMediaStream(this.localStreams[e]);this.localStreams[e]=null}this.getLocalMediaStream(e).then(function(){if(t.ready){for(var n in t.peers){if(t.peers[n].isReady()){t.peers[n].replaceMediaStream(e)}}}}).catch(function(e){console.error("Could not get access to hardware; don't really know what to do. error:",e)}.bind(this))};BX.Call.PlainCall.prototype.sendAllStreams=function(e){if(!this.peers[e])return;if(!this.peers[e].isReady())return;for(var t in this.localStreams){if(this.localStreams[t]){this.peers[e].sendMedia()}}};BX.Call.PlainCall.prototype.isAnyoneParticipating=function(){for(var e in this.peers){if(this.peers[e].isParticipating()){return true}}return false};BX.Call.PlainCall.prototype.addInvitedUsers=function(e){for(var t=0;t<e.length;t++){var n=Number(e[t]);if(n==this.userId){continue}if(this.peers[n]){if(this.peers[n].calculatedState===BX.Call.UserState.Failed||this.peers[n].calculatedState===BX.Call.UserState.Idle){this.peers[n].onInvited()}}else{this.peers[n]=this.createPeer(n);this.runCallback(BX.Call.Event.onUserInvited,{userId:n});this.peers[n].onInvited()}}};BX.Call.PlainCall.prototype.__onPullEvent=function(e,t,n){var i={"Call::answer":this.__onPullEventAnswer.bind(this),"Call::hangup":this.__onPullEventHangup.bind(this),"Call::ping":this.__onPullEventPing.bind(this),"Call::negotiationNeeded":this.__onPullEventNegotiationNeeded.bind(this),"Call::connectionOffer":this.__onPullEventConnectionOffer.bind(this),"Call::connectionAnswer":this.__onPullEventConnectionAnswer.bind(this),"Call::iceCandidate":this.__onPullEventIceCandidate.bind(this),"Call::voiceStarted":this.__onPullEventVoiceStarted.bind(this),"Call::voiceStopped":this.__onPullEventVoiceStopped.bind(this),"Call::microphoneState":this.__onPullEventMicrophoneState.bind(this),"Call::usersInvited":this.__onPullEventUsersInvited.bind(this),"Call::userInviteTimeout":this.__onPullEventUserInviteTimeout.bind(this),"Call::associatedEntityReplaced":this.__onPullEventAssociatedEntityReplaced.bind(this),"Call::finish":this.__onPullEventFinish.bind(this)};if(i[e]){this.log("Signaling: "+e+"; Parameters: "+JSON.stringify(t));i[e].call(this,t)}};BX.Call.PlainCall.prototype.__onPullEventUsersInvited=function(e){if(!this.ready){return}var t=e.users;this.addInvitedUsers(t)};BX.Call.PlainCall.prototype.__onPullEventUserInviteTimeout=function(e){this.log("__onPullEventUserInviteTimeout",e);var t=e.failedUserId;if(this.peers[t]){this.peers[t].onInviteTimeout(false)}};BX.Call.PlainCall.prototype.__onPullEventAnswer=function(e){var t=Number(e.senderId);if(t==this.userId){return this.__onPullEventAnswerSelf(e)}if(!this.ready){return}if(!this.peers[t]){return}this.peers[t].setSignalingConnected(true);this.peers[t].setReady(true);this.peers[t].isMobile=e.isMobile===true;if(this.ready){this.sendAllStreams(t)}};BX.Call.PlainCall.prototype.__onPullEventAnswerSelf=function(e){if(e.callInstanceId===this.instanceId)return;this.log("Call was answered elsewhere");this.runCallback(BX.Call.Event.onJoin,{local:false})};BX.Call.PlainCall.prototype.__onPullEventHangup=function(e){var t=e.senderId;if(this.userId==t){if(this.instanceId!=e.callInstanceId){this.runCallback(BX.Call.Event.onLeave,{local:false})}return}if(!this.peers[t])return;this.peers[t].disconnect(e.code);this.peers[t].setReady(false);if(e.code==603){this.peers[t].setDeclined(true)}if(!this.isAnyoneParticipating()){this.destroy()}};BX.Call.PlainCall.prototype.__onPullEventPing=function(e){var t=this.peers[e.senderId];if(!t)return;t.setSignalingConnected(true)};BX.Call.PlainCall.prototype.__onPullEventNegotiationNeeded=function(e){if(!this.ready){return}var t=this.peers[e.senderId];if(!t){return}t.setReady(true);if(e.restart){t.reconnect()}else{t.onNegotiationNeeded()}};BX.Call.PlainCall.prototype.__onPullEventConnectionOffer=function(e){if(!this.ready){return}var t=this.peers[e.senderId];if(!t){return}t.setReady(true);t.setUserAgent(e.userAgent);t.setConnectionOffer(e.connectionId,e.sdp)};BX.Call.PlainCall.prototype.__onPullEventConnectionAnswer=function(e){if(!this.ready){return}var t=this.peers[e.senderId];if(!t)return;var n=e.connectionId;t.setUserAgent(e.userAgent);t.setConnectionAnswer(n,e.sdp)};BX.Call.PlainCall.prototype.__onPullEventIceCandidate=function(e){if(!this.ready){return}var t=this.peers[e.senderId];var n;if(!t)return;try{n=e.candidates;for(var i=0;i<n.length;i++){t.addIceCandidate(e.connectionId,n[i])}}catch(e){this.log("Error parsing serialized candidate: ",e)}};BX.Call.PlainCall.prototype.__onPullEventVoiceStarted=function(e){this.runCallback(BX.Call.Event.onUserVoiceStarted,{userId:e.senderId})};BX.Call.PlainCall.prototype.__onPullEventVoiceStopped=function(e){this.runCallback(BX.Call.Event.onUserVoiceStopped,{userId:e.senderId})};BX.Call.PlainCall.prototype.__onPullEventMicrophoneState=function(e){this.runCallback(BX.Call.Event.onUserMicrophoneState,{userId:e.senderId,microphoneState:e.microphoneState})};BX.Call.PlainCall.prototype.__onPullEventAssociatedEntityReplaced=function(e){if(e.call&&e.call.ASSOCIATED_ENTITY){this.associatedEntity=e.call.ASSOCIATED_ENTITY}};BX.Call.PlainCall.prototype.__onPullEventFinish=function(e){this.destroy()};BX.Call.PlainCall.prototype.__onPeerStateChanged=function(e){this.runCallback(BX.Call.Event.onUserStateChanged,e);if(e.state==BX.Call.UserState.Failed||e.state==BX.Call.UserState.Unavailable){if(!this.isAnyoneParticipating()){this.hangup().then(this.destroy.bind(this)).catch(function(e){this.destroy()}.bind(this))}}else if(e.state==BX.Call.UserState.Connected){this.signaling.sendMicrophoneState(e.userId,!this.muted)}};BX.Call.PlainCall.prototype.__onPeerInviteTimeout=function(e){if(!this.ready){return}this.signaling.sendUserInviteTimeout({userId:this.users,failedUserId:e.userId})};BX.Call.PlainCall.prototype.__onPeerRTCStatsReceived=function(e){this.runCallback(BX.Call.Event.onRTCStatsReceived,e)};BX.Call.PlainCall.prototype._onUnload=function(t){if(!this.ready){return}BX.CallEngine.getRestClient().callMethod(e.hangup,{callId:this.id,callInstanceId:this.instanceId});for(var n in this.peers){this.peers[n].disconnect()}};BX.Call.PlainCall.prototype.destroy=function(){for(var e in this.peers){if(this.peers[e]){this.peers[e].destroy()}}for(var t in this.localStreams){if(this.localStreams[t]){BX.webrtc.stopMediaStream(this.localStreams[t]);this.localStreams[t]=null}}window.removeEventListener("unload",this._onUnloadHandler);clearInterval(this.pingUsersInterval);clearInterval(this.pingBackendInterval);clearTimeout(this.reinviteTimeout);this.runCallback(BX.Call.Event.onDestroy)};BX.Call.PlainCall.Signaling=function(e){this.call=e.call};BX.Call.PlainCall.Signaling.prototype.isIceTricklingAllowed=function(){return BX.PULL.isPublishingSupported()};BX.Call.PlainCall.Signaling.prototype.inviteUsers=function(t){return this.__runRestAction(e.invite,t)};BX.Call.PlainCall.Signaling.prototype.sendAnswer=function(t){return this.__runRestAction(e.answer,t)};BX.Call.PlainCall.Signaling.prototype.sendConnectionOffer=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.connectionOffer,n)}else{return this.__runRestAction(e.connectionOffer,n)}};BX.Call.PlainCall.Signaling.prototype.sendConnectionAnswer=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.connectionAnswer,n)}else{return this.__runRestAction(e.connectionAnswer,n)}};BX.Call.PlainCall.Signaling.prototype.sendIceCandidate=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.iceCandidate,n)}else{return this.__runRestAction(e.iceCandidate,n)}};BX.Call.PlainCall.Signaling.prototype.sendNegotiationNeeded=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.negotiationNeeded,n)}else{return this.__runRestAction(e.negotiationNeeded,n)}};BX.Call.PlainCall.Signaling.prototype.sendVoiceStarted=function(e){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.voiceStarted,e)}};BX.Call.PlainCall.Signaling.prototype.sendVoiceStopped=function(e){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.voiceStopped,e)}};BX.Call.PlainCall.Signaling.prototype.sendMicrophoneState=function(e,n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.microphoneState,{userId:e,microphoneState:n},0)}};BX.Call.PlainCall.Signaling.prototype.sendPingToUsers=function(e){if(BX.PULL.isPublishingEnabled()){this.__sendPullEvent(t.ping,e,0)}};BX.Call.PlainCall.Signaling.prototype.sendPingToBackend=function(){var t=!BX.PULL.isPublishingEnabled();this.__runRestAction(e.ping,{retransmit:t})};BX.Call.PlainCall.Signaling.prototype.sendUserInviteTimeout=function(e){if(BX.PULL.isPublishingEnabled()){this.__sendPullEvent(t.userInviteTimeout,e,0)}};BX.Call.PlainCall.Signaling.prototype.sendHangup=function(n){if(BX.PULL.isPublishingSupported()){this.__sendPullEvent(t.hangup,n);n.retransmit=false;return this.__runRestAction(e.hangup,n)}else{n.retransmit=true;return this.__runRestAction(e.hangup,n)}};BX.Call.PlainCall.Signaling.prototype.__sendPullEvent=function(e,t,n){n=n||5;if(!t.userId){throw new Error("userId is not found in data")}if(!BX.type.isArray(t.userId)){t.userId=[t.userId]}t.callInstanceId=this.call.instanceId;t.senderId=this.call.userId;t.callId=this.call.id;t.requestId=BX.Call.Engine.getInstance().getUuidv4();this.call.log("Sending p2p signaling event "+e+"; "+JSON.stringify(t));BX.PULL.sendMessage(t.userId,"im",e,t,n)};BX.Call.PlainCall.Signaling.prototype.__runRestAction=function(e,t){if(!BX.type.isPlainObject(t)){t={}}t.callId=this.call.id;t.callInstanceId=this.call.instanceId;t.requestId=BX.Call.Engine.getInstance().getUuidv4();this.call.log("Sending ajax-based signaling event "+e+"; "+JSON.stringify(t));return BX.CallEngine.getRestClient().callMethod(e,t).catch(function(e){console.error(e)})};BX.Call.PlainCall.Peer=function(e){this.call=e.call;this.userId=e.userId;this.ready=e.ready===true;this.calling=false;this.inviteTimeout=false;this.declined=false;this.busy=false;this.signalingConnected=e.signalingConnected===true;this.failureReason="";this.userAgent="";this.isFirefox=false;this.isChrome=false;this.isMobile=e.isMobile===true;this.calculatedState=this.calculateState();this.localStreams={main:null,screen:null};this.senderMediaStream=null;this.peerConnection=null;this.pendingIceCandidates={};this.localIceCandidates=[];this.callbacks={onStateChanged:BX.type.isFunction(e.onStateChanged)?e.onStateChanged:BX.DoNothing,onInviteTimeout:BX.type.isFunction(e.onInviteTimeout)?e.onInviteTimeout:BX.DoNothing,onStreamReceived:BX.type.isFunction(e.onStreamReceived)?e.onStreamReceived:BX.DoNothing,onStreamRemoved:BX.type.isFunction(e.onStreamRemoved)?e.onStreamRemoved:BX.DoNothing,onRTCStatsReceived:BX.type.isFunction(e.onRTCStatsReceived)?e.onRTCStatsReceived:BX.DoNothing};this.answerTimeout=null;this.callingTimeout=null;this.connectionTimeout=null;this.signalingConnectionTimeout=null;this.candidatesTimeout=null;this.statsInterval=null;this.connectionOfferReplyTimeout=null;this.negotiationNeededReplyTimeout=null;this.reconnectAfterDisconnectTimeout=null;this.connectionAttempt=0;this._onPeerConnectionIceCandidateHandler=this._onPeerConnectionIceCandidate.bind(this);this._onPeerConnectionIceConnectionStateChangeHandler=this._onPeerConnectionIceConnectionStateChange.bind(this);this._onPeerConnectionIceGatheringStateChangeHandler=this._onPeerConnectionIceGatheringStateChange.bind(this);this._onPeerConnectionTrackHandler=this._onPeerConnectionTrack.bind(this);this._onPeerConnectionRemoveStreamHandler=this._onPeerConnectionRemoveStream.bind(this)};BX.Call.PlainCall.Peer.prototype.sendMedia=function(e){var t=[];if(!this.peerConnection){if(!this.isInitiator()){this.log("waiting for the other side to send connection offer");this.sendNegotiationNeeded(false);return}}if(this.call.localStreams["main"]){t=t.concat(this.call.localStreams["main"].getAudioTracks())}if(this.call.localStreams["screen"]){t=t.concat(this.call.localStreams["screen"].getVideoTracks())}else if(this.call.localStreams["main"]){t=t.concat(this.call.localStreams["main"].getVideoTracks())}this.log("User: "+this.userId+"; Sending media streams. Tracks: "+t.map(function(e){return e.id}).join("; "));if(t.length===0){this.log("No media streams to send");return}if(this.peerConnection){this.peerConnection.getSenders().forEach(function(e){this.peerConnection.removeTrack(e)}.bind(this))}else{var n=BX.Call.Engine.getInstance().getUuidv4();this._createPeerConnection(n)}if(this.senderMediaStream&&this.senderMediaStream.getTracks().length>0){this.log("removing old tracks");this.senderMediaStream.getTracks().forEach(function(e){this.senderMediaStream.removeTrack(e)},this)}this.senderMediaStream=new MediaStream;t.forEach(function(e){this.senderMediaStream.addTrack(e);this.peerConnection.addTrack(e,this.senderMediaStream)},this);if(!e){this.createAndSendOffer()}};BX.Call.PlainCall.Peer.prototype.replaceMediaStream=function(e){if(this.isRenegotiationSupported()){this.sendMedia()}else{this.localStreams[e]=this.call.getLocalStream(e);this.reconnect()}};BX.Call.PlainCall.Peer.prototype.isInitiator=function(){return this.call.userId<this.userId};BX.Call.PlainCall.Peer.prototype.isRenegotiationSupported=function(){return BX.browser.IsChrome()&&this.isChrome};BX.Call.PlainCall.Peer.prototype.setReady=function(e){this.ready=e;if(this.ready){this.declined=false;this.busy=false}if(this.calling){clearTimeout(this.callingTimeout);this.calling=false}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.isReady=function(){return this.ready};BX.Call.PlainCall.Peer.prototype.onInvited=function(){this.ready=false;this.inviteTimeout=false;this.declined=false;this.calling=true;if(this.callingTimeout){clearTimeout(this.callingTimeout)}this.callingTimeout=setTimeout(function(){this.onInviteTimeout(true)}.bind(this),3e4);this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.onInviteTimeout=function(e){clearTimeout(this.callingTimeout);this.calling=false;this.inviteTimeout=true;if(e){this.callbacks.onInviteTimeout({userId:this.userId})}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.setUserAgent=function(e){this.userAgent=e;this.isFirefox=e.toLowerCase().indexOf("firefox")!=-1;this.isChrome=e.toLowerCase().indexOf("chrome")!=-1;this.isMobile=e==="Bitrix Mobile"};BX.Call.PlainCall.Peer.prototype.getUserAgent=function(){return this.userAgent};BX.Call.PlainCall.Peer.prototype.isParticipating=function(){if(this.calling)return true;if(this.declined||this.busy)return false;if(this.peerConnection){var e=this.peerConnection.iceConnectionState;if(e=="checking"||e=="connected"||e=="completed"){return true}}return false};BX.Call.PlainCall.Peer.prototype.setSignalingConnected=function(e){this.signalingConnected=e;this.updateCalculatedState();if(this.signalingConnected)this.refreshSignalingTimeout();else this.stopSignalingTimeout()};BX.Call.PlainCall.Peer.prototype.isSignalingConnected=function(){return this.signalingConnected};BX.Call.PlainCall.Peer.prototype.setDeclined=function(e){this.declined=e;if(this.calling){clearTimeout(this.callingTimeout);this.calling=false}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.setBusy=function(e){this.busy=e;if(this.calling){clearTimeout(this.callingTimeout);this.calling=false}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.isDeclined=function(){return this.declined};BX.Call.PlainCall.Peer.prototype.updateCalculatedState=function(){var e=this.calculateState();if(this.calculatedState!=e){this.callbacks.onStateChanged({userId:this.userId,state:e,previousState:this.calculatedState,isMobile:this.isMobile});this.calculatedState=e}};BX.Call.PlainCall.Peer.prototype.calculateState=function(){if(this.peerConnection){if(this.failureReason!==""){return BX.Call.UserState.Failed}if(this.peerConnection.iceConnectionState==="connected"||this.peerConnection.iceConnectionState==="completed"){return BX.Call.UserState.Connected}return BX.Call.UserState.Connecting}if(this.calling)return BX.Call.UserState.Calling;if(this.inviteTimeout)return BX.Call.UserState.Unavailable;if(this.declined)return BX.Call.UserState.Declined;if(this.busy)return BX.Call.UserState.Busy;if(this.ready)return BX.Call.UserState.Ready;return BX.Call.UserState.Idle};BX.Call.PlainCall.Peer.prototype.getSignaling=function(){return this.call.signaling};BX.Call.PlainCall.Peer.prototype.startStatisticsGathering=function(){clearInterval(this.statsInterval);this.statsInterval=setInterval(function(){if(!this.peerConnection){return false}this.peerConnection.getStats().then(function(e){this.callbacks.onRTCStatsReceived({userId:this.userId,stats:e})}.bind(this))}.bind(this),1e3)};BX.Call.PlainCall.Peer.prototype.stopStatisticsGathering=function(){clearInterval(this.statsInterval);this.statsInterval=null};BX.Call.PlainCall.Peer.prototype.updateCandidatesTimeout=function(){if(this.candidatesTimeout){clearTimeout(this.candidatesTimeout)}this.candidatesTimeout=setTimeout(this.sendIceCandidates.bind(this),500)};BX.Call.PlainCall.Peer.prototype.sendIceCandidates=function(){this.candidatesTimeout=null;this.log("User "+this.userId+": sending ICE candidates due to the timeout");if(this.localIceCandidates.length>0){this.getSignaling().sendIceCandidate({userId:this.userId,connectionId:this.peerConnection._id,candidates:this.localIceCandidates});this.localIceCandidates=[]}else{this.log("User "+this.userId+": ICE candidates pool is empty")}};BX.Call.PlainCall.Peer.prototype._createPeerConnection=function(e){this.log("User "+this.userId+": Creating peer connection");var t={iceServers:[{urls:"stun:"+this.call.turnServer},{urls:"turn:"+this.call.turnServer,username:this.call.turnServerLogin,credential:this.call.turnServerPassword}]};this.localIceCandidates=[];var n=new RTCPeerConnection(t);n._id=e;n.addEventListener("icecandidate",this._onPeerConnectionIceCandidateHandler);n.addEventListener("iceconnectionstatechange",this._onPeerConnectionIceConnectionStateChangeHandler);n.addEventListener("icegatheringstatechange",this._onPeerConnectionIceGatheringStateChangeHandler);n.addEventListener("negotiationneeded",this._onPeerConnectionNegotiationNeededHandler);n.addEventListener("track",this._onPeerConnectionTrackHandler);n.addEventListener("removestream",this._onPeerConnectionRemoveStreamHandler);this.peerConnection=n;this.failureReason="";this.updateCalculatedState();this.startStatisticsGathering()};BX.Call.PlainCall.Peer.prototype._destroyPeerConnection=function(){if(!this.peerConnection)return;var e=this.peerConnection._id;this.log("User "+this.userId+": Destroying peer connection "+e);this.stopStatisticsGathering();this.peerConnection.removeEventListener("icecandidate",this._onPeerConnectionIceCandidateHandler);this.peerConnection.removeEventListener("iceconnectionstatechange",this._onPeerConnectionIceConnectionStateChangeHandler);this.peerConnection.removeEventListener("icegatheringstatechange",this._onPeerConnectionIceGatheringStateChangeHandler);this.peerConnection.removeEventListener("negotiationneeded",this._onPeerConnectionNegotiationNeededHandler);this.peerConnection.removeEventListener("track",this._onPeerConnectionTrackHandler);this.peerConnection.removeEventListener("removestream",this._onPeerConnectionRemoveStreamHandler);this.localIceCandidates=[];if(this.pendingIceCandidates[e]){delete this.pendingIceCandidates[e]}this.peerConnection.close();this.peerConnection=null};BX.Call.PlainCall.Peer.prototype._onPeerConnectionIceCandidate=function(e){var t=e.candidate;var n=e.target;this.log("User "+this.userId+": ICE candidate discovered. Candidate: "+(t?t.candidate:t));if(t){if(this.getSignaling().isIceTricklingAllowed()){this.getSignaling().sendIceCandidate({userId:this.userId,connectionId:n._id,candidates:[t.toJSON()]})}else{this.localIceCandidates.push(t.toJSON());this.updateCandidatesTimeout()}}};BX.Call.PlainCall.Peer.prototype._onPeerConnectionIceConnectionStateChange=function(e){this.log("User "+this.userId+": ICE connection state changed. New state: "+this.peerConnection.iceConnectionState);if(this.peerConnection.iceConnectionState==="connected"){this.connectionAttempt=0;clearTimeout(this.reconnectAfterDisconnectTimeout)}else if(this.peerConnection.iceConnectionState==="failed"){this.log("ICE connection failed. Trying to restore connection immediately");this.reconnect()}else if(this.peerConnection.iceConnectionState==="disconnected"){this.log("ICE connection lost. Waiting 5 seconds before trying to restore it");clearTimeout(this.reconnectAfterDisconnectTimeout);this.reconnectAfterDisconnectTimeout=setTimeout(function(){this.reconnect()}.bind(this),5e3)}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype._onPeerConnectionIceGatheringStateChange=function(e){var t=e.target;this.log("User "+this.userId+": ICE gathering state changed to : "+t.iceGatheringState);if(t.iceGatheringState==="complete"){this.log("User "+this.userId+": ICE gathering complete");if(!this.getSignaling().isIceTricklingAllowed()){if(this.localIceCandidates.length>0){this.getSignaling().sendIceCandidate({userId:this.userId,connectionId:t._id,candidates:this.localIceCandidates});this.localIceCandidates=[]}else{this.log("User "+this.userId+": ICE candidates already sent")}}}};BX.Call.PlainCall.Peer.prototype._onPeerConnectionNegotiationNeeded=function(e){this.log("User "+this.userId+": needed negotiation for peer connection");this.log("signaling state: ",e.target.signalingState);this.log("ice connection state: ",e.target.iceConnectionState);this.log("pendingRemoteDescription: ",e.target.pendingRemoteDescription);if(e.target.iceConnectionState!=="new"&&e.target.iceConnectionState!=="connected"&&e.target.iceConnectionState!=="completed"){this.log("User "+this.userId+": wrong connection state");return}if(this.isInitiator()){this.createAndSendOffer()}else{this.sendNegotiationNeeded(this.peerConnection._forceReconnect===true)}};BX.Call.PlainCall.Peer.prototype._onPeerConnectionTrack=function(e){this.log("User "+this.userId+": media track received: ",e.track.id+" ("+e.track.kind+")");this.callbacks.onStreamReceived({userId:this.userId,kind:e.track.kind,stream:e.streams[0]})};BX.Call.PlainCall.Peer.prototype._onPeerConnectionRemoveStream=function(e){this.log("User: "+this.userId+"_onPeerConnectionRemoveStream: ",e);this.callbacks.onStreamRemoved({userId:this.userId,stream:e.stream})};BX.Call.PlainCall.Peer.prototype.stopSignalingTimeout=function(){clearTimeout(this.signalingConnectionTimeout)};BX.Call.PlainCall.Peer.prototype.refreshSignalingTimeout=function(){clearTimeout(this.signalingConnectionTimeout);this.signalingConnectionTimeout=setTimeout(this._onLostSignalingConnection.bind(this),i)};BX.Call.PlainCall.Peer.prototype._onLostSignalingConnection=function(){this.setSignalingConnected(false)};BX.Call.PlainCall.Peer.prototype._onConnectionOfferReplyTimeout=function(e){this.log("did not receive connection answer for connection "+e);this.reconnect()};BX.Call.PlainCall.Peer.prototype._onNegotiationNeededReplyTimeout=function(){this.log("did not receive connection offer in time");this.reconnect()};BX.Call.PlainCall.Peer.prototype.setConnectionOffer=function(e,t){this.log("User "+this.userId+": applying connection offer for connection "+e);clearTimeout(this.negotiationNeededReplyTimeout);this.negotiationNeededReplyTimeout=null;if(!this.call.isReady())return;if(!this.isReady())return;if(this.peerConnection){if(this.peerConnection._id!==e){this._destroyPeerConnection();this._createPeerConnection(e)}}else{this._createPeerConnection(e)}this.applyOfferAndSendAnswer(t)};BX.Call.PlainCall.Peer.prototype.createAndSendOffer=function(e){var t=this;connectionConfig=n;for(var i in e){connectionConfig[i]=e[i]}t.peerConnection.createOffer(connectionConfig).then(function(e){t.log("User "+t.userId+": Created connection offer.");t.log("Applying local description");return t.peerConnection.setLocalDescription(e)}).then(function(){t.sendOffer()})};BX.Call.PlainCall.Peer.prototype.sendOffer=function(){var e=this.peerConnection._id;clearTimeout(this.connectionOfferReplyTimeout);this.connectionOfferReplyTimeout=setTimeout(function(){this._onConnectionOfferReplyTimeout(e)}.bind(this),a);this.getSignaling().sendConnectionOffer({userId:this.userId,connectionId:e,sdp:this.peerConnection.localDescription.sdp,userAgent:navigator.userAgent})};BX.Call.PlainCall.Peer.prototype.sendNegotiationNeeded=function(e){e=e===true;clearTimeout(this.negotiationNeededReplyTimeout);this.negotiationNeededReplyTimeout=setTimeout(function(){this._onNegotiationNeededReplyTimeout()}.bind(this),a);var t={userId:this.userId};if(e){t.restart=true}this.getSignaling().sendNegotiationNeeded(t)};BX.Call.PlainCall.Peer.prototype.applyOfferAndSendAnswer=function(e){var t=this;var n=new RTCSessionDescription({type:"offer",sdp:e});var i=this.peerConnection;this.log("User: "+this.userId+"; Applying remote offer");this.log("User: "+this.userId+"; Peer ice connection state ",i.iceConnectionState);i.setRemoteDescription(n).then(function(){if(i.iceConnectionState==="new"){t.sendMedia(true)}return t.peerConnection.createAnswer()}).then(function(e){t.log("Created connection answer.");t.log("Applying local description.");return t.peerConnection.setLocalDescription(e)}).then(function(){t.applyPendingIceCandidates();t.getSignaling().sendConnectionAnswer({userId:t.userId,connectionId:t.peerConnection._id,sdp:t.peerConnection.localDescription.sdp,userAgent:navigator.userAgent})}).catch(function(e){t.failureReason=e.toString();t.updateCalculatedState();t.log("Could not apply remote offer",e);console.error("Could not apply remote offer",e)})};BX.Call.PlainCall.Peer.prototype.setConnectionAnswer=function(e,t){var n=this;if(!this.peerConnection)return;if(this.peerConnection._id!=e){this.log("Could not apply answer, for unknown connection "+e);return}if(this.peerConnection.signalingState!=="have-local-offer"){this.log("Could not apply answer, wrong peer connection signaling state "+this.peerConnection.signalingState);return}var i=new RTCSessionDescription({type:"answer",sdp:t});clearTimeout(this.connectionOfferReplyTimeout);this.log("User: "+this.userId+"; Applying remote answer");this.peerConnection.setRemoteDescription(i).then(function(){n.applyPendingIceCandidates()}).catch(function(e){n.failureReason=e.toString();n.updateCalculatedState();n.log(e)})};BX.Call.PlainCall.Peer.prototype.addIceCandidate=function(e,t){if(!this.peerConnection)return;if(this.peerConnection._id!=e){this.log("Error: Candidate for unknown connection "+e);return}if(this.peerConnection.remoteDescription&&this.peerConnection.remoteDescription.type){this.peerConnection.addIceCandidate(t).then(function(){this.log("User: "+this.userId+"; Added remote ICE candidate: "+(t?t.candidate:t))}.bind(this)).catch(function(e){this.log(e)}.bind(this))}else{if(!this.pendingIceCandidates[e]){this.pendingIceCandidates[e]=[]}this.pendingIceCandidates[e].push(t)}};BX.Call.PlainCall.Peer.prototype.applyPendingIceCandidates=function(){var e=this;if(!this.peerConnection||!this.peerConnection.remoteDescription.type)return;var t=this.peerConnection._id;if(BX.type.isArray(this.pendingIceCandidates[t])){this.pendingIceCandidates[t].forEach(function(t){e.peerConnection.addIceCandidate(t).then(function(){this.log("User: "+this.userId+"; Added remote ICE candidate: "+(t?t.candidate:t))}.bind(this))},this);e.pendingIceCandidates[t]=[]}};BX.Call.PlainCall.Peer.prototype.onNegotiationNeeded=function(){if(this.peerConnection){if(this.peerConnection.signalingState=="have-local-offer"){this.sendOffer()}else{this.createAndSendOffer({iceRestart:true})}}else{this.sendMedia()}};BX.Call.PlainCall.Peer.prototype.reconnect=function(){clearTimeout(this.reconnectAfterDisconnectTimeout);this.connectionAttempt++;if(this.connectionAttempt>3){this.log("Error: Too many reconnection attempts, giving up");this.failureReason="Could not connect to user in time";this.updateCalculatedState();return}this.log("Trying to restore ICE connection. Attempt "+this.connectionAttempt);if(this.isInitiator()){this._destroyPeerConnection();this.sendMedia()}else{this.sendNegotiationNeeded(true)}};BX.Call.PlainCall.Peer.prototype.disconnect=function(){this._destroyPeerConnection()};BX.Call.PlainCall.Peer.prototype.log=function(){this.call.log.apply(this.call,arguments)};BX.Call.PlainCall.Peer.prototype.destroy=function(){this.disconnect();if(this.voiceDetection){this.voiceDetection.destroy();this.voiceDetection=null}for(var e in this.localStreams){this.localStreams[e]=null}clearTimeout(this.answerTimeout);this.answerTimeout=null;clearTimeout(this.connectionTimeout);this.connectionTimeout=null;clearTimeout(this.signalingConnectionTimeout);this.signalingConnectionTimeout=null;this.callbacks.onStateChanged=BX.DoNothing;this.callbacks.onStreamReceived=BX.DoNothing;this.callbacks.onStreamRemoved=BX.DoNothing}})();
//# sourceMappingURL=plain_call.map.js