sip-connector 6.17.0 → 6.18.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/dist/index.es5.js +1 -1
- package/dist/index.es5.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/tools/getUserAgent.d.ts +9 -0
- package/dist/tools/getUserAgent.d.ts.map +1 -0
- package/dist/tools/getUserAgent.js +22 -0
- package/dist/tools/getUserAgent.js.map +1 -0
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +3 -1
- package/dist/tools/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@krivega/cancelable-promise"),require("events-constructor"),require("stack-promises"),require("debug"),require("lodash/debounce"),require("sequent-promises"),require("lodash/flow"),require("lodash/split")):"function"==typeof define&&define.amd?define(["exports","@krivega/cancelable-promise","events-constructor","stack-promises","debug","lodash/debounce","sequent-promises","lodash/flow","lodash/split"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sipConnector={},e.cancelablePromise,e.Events,e.createStackPromises,e.debug,e.debounce,e.sequentPromises,e.flow,e.split)}(this,(function(e,t,s,n,i,r,o,a,c){"use strict";function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=d(s),h=d(n),u=d(i),m=d(r),g=d(o),_=d(a),S=d(c);const E=e=>e.getStats().then((e=>{const t=(s="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===s)));var s;return null==t?void 0:t.mimeType}));function C(e,t,s,n){return new(s||(s=Promise))((function(i,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const f="Request Timeout",v="Rejected",p="Not Found",R="Terminated",N="Canceled",P="Bad Media Description";var T=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:f,SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:v,REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:p,ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:R,WEBRTC_ERROR:"WebRTC Error",CANCELED:N,NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:P,RTP_TIMEOUT:"RTP Timeout"});const M="incomingCall",A="declinedIncomingCall",b="failedIncomingCall",w="terminatedIncomingCall",I="connecting",O="connected",y="disconnected",D="newRTCSession",U="registered",k="unregistered",q="registrationFailed",F="sipEvent",B="availableSecondRemoteStream",x="notAvailableSecondRemoteStream",L="mustStopPresentation",W="shareState",H="enterRoom",V="useLicense",j="peerconnection:confirmed",X="peerconnection:ontrack",Y="channels",$="channels:notify",G="ended:fromserver",J="main-cam-control",K="admin-stop-main-cam",z="admin-start-main-cam",Q="admin-stop-mic",Z="admin-start-mic",ee="admin-force-sync-media-state",te="participant:added-to-list-moderators",se="participant:removed-from-list-moderators",ne="participant:move-request-to-conference",ie="participant:move-request-to-stream",re="participant:canceling-word-request",oe="webcast:started",ae="webcast:stopped",ce="account:changed",de="account:deleted",le="conference:participant-token-issued",he="ended",ue="confirmed",me="peerconnection",ge="failed",_e="newDTMF",Se="newInfo",Ee="presentation:ended",Ce="presentation:failed",fe=[M,A,w,b,re,ie,ne,$,le,ce,de,oe,ae,te,se],ve=[I,O,y,D,U,k,q,"newMessage",F],pe=[B,x,L,W,H,V,j,X,Y,G,J,z,K,Q,Z,ee],Re=[he,I,"sending","reinvite","replaces","refer","progress","accepted",ue,me,ge,"muted","unmuted",_e,Se,"hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end",Ee,Ce],Ne=[...ve,...fe],Pe=[...Re,...pe];var Te=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:fe,UA_JSSIP_EVENT_NAMES:ve,SESSION_SYNTHETICS_EVENT_NAMES:pe,SESSION_JSSIP_EVENT_NAMES:Re,UA_EVENT_NAMES:Ne,SESSION_EVENT_NAMES:Pe});const Me="application/vinteo.webrtc.sharedesktop",Ae="application/vinteo.webrtc.maincam",be="X-WEBRTC-INPUT-CHANNELS",we="X-WEBRTC-OUTPUT-CHANNELS",Ie="X-WEBRTC-SYNC",Oe="x-webrtc-share-state",ye="YOUCANRECEIVECONTENT",De="CONTENTEND";const Ue=e=>e.trim().replace(/ /g,"_"),ke=(qe=1e5,Fe=99999999,()=>Math.floor(Math.random()*(Fe-qe))+qe);var qe,Fe;const Be=(e,{videoMode:t,audioMode:s}={})=>{if(!e||"recvonly"===t&&"recvonly"===s)return;const n=[..."recvonly"===s?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],i=new MediaStream(n);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},xe=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,Le=xe(1),We=xe(void 0),He=(e,t,s)=>{const n=e.getParameters();n.encodings&&0!==n.encodings.length||(n.encodings=[{}]);const[i]=n.encodings,r=i.scaleResolutionDownBy,o=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&Le(s,t))return s})(t.scaleResolutionDownBy,r);let a=!1;void 0!==o&&(n.encodings[0].scaleResolutionDownBy=o,a=!0);const c=i.maxBitrate,d=((e,t)=>{if(We(e,t))return e})(t.maxBitrate,c);return void 0!==d&&(n.encodings[0].maxBitrate=d,a=!0),a?(s&&s(n),e.setParameters(n).then((()=>({parameters:n,isChanged:a})))):Promise.resolve({parameters:n,isChanged:a})},Ve="local",je="remote";var Xe,Ye,$e,Ge;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(Xe||(Xe={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(Ye||(Ye={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}($e||($e={})),e.EUseLicense=void 0,(Ge=e.EUseLicense||(e.EUseLicense={})).AUDIO="AUDIO",Ge.VIDEO="VIDEO",Ge.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION";const Je="SipConnector";const Ke=(e,t)=>!!e&&!!t&&e.toLowerCase().includes(t.toLowerCase()),ze=e=>1e6*e,Qe=ze(.06),Ze=ze(4),et=(e,t)=>(e=>Ke(e,"av1"))(t)?.6*e:e,tt=(e,t)=>{const s=(e=>e<=64?Qe:e<=128?ze(.12):e<=256?ze(.25):e<=384?ze(.32):e<=426?ze(.38):e<=640?ze(.5):e<=848?ze(.7):e<=1280?ze(1):e<=1920?ze(2):Ze)(e);return et(s,t)},st=h.default(),nt=e=>(st.add(e),st().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),it=({sender:e,scaleResolutionDownBy:t,maxBitrate:s,onSetParameters:n})=>nt((()=>He(e,{scaleResolutionDownBy:t,maxBitrate:s},n))),rt=({sender:e,codec:t},s)=>{const n=(e=>et(Qe,e))(t);return it({sender:e,maxBitrate:n,onSetParameters:s,scaleResolutionDownBy:200})},ot=({sender:e,track:t,codec:s},n)=>{const i=t.getSettings().width,r=tt(i,s);return it({sender:e,maxBitrate:r,onSetParameters:n,scaleResolutionDownBy:1})},at=({mainCam:e,resolutionMainCam:t,sender:s,track:n,codec:i},r)=>{switch(e){case Xe.PAUSE_MAIN_CAM:return rt({sender:s,codec:i},r);case Xe.RESUME_MAIN_CAM:return ot({sender:s,track:n,codec:i},r);case Xe.MAX_MAIN_CAM_RESOLUTION:return t?(({sender:e,track:t,resolution:s,codec:n},i)=>{const r=t.getSettings(),o=r.width,a=r.height,[c,d]=s.split("x"),l=o/+c,h=a/+d,u=Math.max(l,h,1),m=tt(+c,n);return it({sender:e,maxBitrate:m,onSetParameters:i,scaleResolutionDownBy:u})})({sender:s,track:n,codec:i,resolution:t},r):ot({sender:s,track:n,codec:i},r);default:return ot({sender:s,track:n,codec:i},r)}},ct={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},dt=({mainCam:e,resolutionMainCam:t,connection:s,onSetParameters:n,ignoreForCodec:i})=>C(void 0,void 0,void 0,(function*(){const r=(e=>e.find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)})))(s.getSenders());if(!r||!r.track)return ct;const o=yield E(r);return Ke(o,i)?ct:at({mainCam:e,resolutionMainCam:t,sender:r,codec:o,track:r.track},n)})),lt="sip-connector",ht=u.default(lt),ut="purgatory",mt=e=>e===ut,gt=e=>()=>(ht("getRemoteStreams"),e.getRemoteStreams()),_t=e=>({track:t})=>{(({kind:e,readyState:t})=>"video"===e&&"live"===t)(t)&&e()},St=({getRemoteStreams:e,setRemoteStreams:t})=>m.default((()=>{const s=e();ht("remoteStreams",s),s&&t(s)}),200),Et=e=>{const{url:t,cause:s}=e;let n=t;return s!==P&&s!==p||(n=`${e.message.to.uri.user}@${e.message.to.uri.host}`),n};var Ct;!function(e){e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK"}(Ct||(Ct={}));var ft=Object.freeze({__proto__:null,getLinkError:Et,getTypeFromError:(e=new Error)=>{var t;const{cause:s,socket:n}=e;let i=Ct.CONNECT_SERVER_FAILED;return"Forbidden"===s?i=Ct.WRONG_USER_OR_PASSWORD:s===P?i=Ct.BAD_MEDIA_ERROR:s===p?i=Ct.NOT_FOUND_ERROR:n&&3===(null===(t=null==n?void 0:n._ws)||void 0===t?void 0:t.readyState)?i=Ct.WS_CONNECTION_FAILED:Et(e)&&(i=Ct.CONNECT_SERVER_FAILED_BY_LINK),i},getValuesFromError:(e=new Error)=>{const{code:t,cause:s,message:n}=e,i=Et(e),r={};return n&&(r.message=n),i&&(r.link=i),t&&(r.code=t),s&&(r.cause=s),r},get EErrorTypes(){return Ct}});var vt=Object.freeze({__proto__:null,PURGATORY_CONFERENCE_NUMBER:ut,createSyncMediaState:({sipConnector:e})=>{const t=(e,t)=>(s={isSyncForced:!1})=>s.isSyncForced?e():t(),s=(e=>t=>(ht("onStartMainCam"),e.onSession("admin-start-main-cam",t)))(e),n=(e=>t=>(ht("onStopMainCam"),e.onSession("admin-stop-main-cam",t)))(e),i=(e=>t=>(ht("onStartMic"),e.onSession("admin-start-mic",t)))(e),r=(e=>t=>(ht("onStopMic"),e.onSession("admin-stop-mic",t)))(e);let o=()=>{},a=()=>{},c=()=>{},d=()=>{};return{start:e=>{(({onStartMainCamForced:e,onStartMainCamNotForced:l,onStopMainCamForced:h,onStopMainCamNotForced:u,onStartMicForced:m,onStartMicNotForced:g,onStopMicForced:_,onStopMicNotForced:S})=>{const E=t(e,l);o=s(E);const C=t(h,u);a=n(C);const f=t(m,g);c=i(f);const v=t(_,S);d=r(v)})(e)},stop:()=>{o(),a(),c(),d()}}},error:ft,getExtraHeaders:({sessionId:e,remoteAddress:t,isMutedAudio:s,isMutedVideo:n,isRegistered:i,isPresentationCall:r})=>{const o=[],a=s?"0":"1",c=n?"0":"1";return o.push(`X-Vinteo-Mic-State: ${a}`),o.push(`X-Vinteo-MainCam-State: ${c}`),i||o.push("X-Vinteo-Purgatory-Call: yes"),e&&o.push(`X-Vinteo-Session: ${e}`),r&&o.push("X-Vinteo-Presentation-Call: yes"),t&&o.push(`X-Vinteo-Remote: ${t}`),o},hasPurgatory:mt,resolveAnswerIncomingCall:e=>t=>{const{mediaStream:s,extraHeaders:n,iceServers:i,degradationPreference:r,setRemoteStreams:o,onBeforeProgressCall:a,onSuccessProgressCall:c,onEnterPurgatory:d,onEnterConference:l,onFailProgressCall:h,onFinishProgressCall:u,onEndedCall:m}=t,g=St({setRemoteStreams:o,getRemoteStreams:gt(e)}),_=_t(g);ht("answerIncomingCall",t);let S,E=!1;const C=(ht("subscribeEnterConference: onEnterConference",l),d||l?e.onSession("enterRoom",(e=>{ht("enterRoom",{_room:e,isSuccessProgressCall:E}),S=e,mt(S)?d&&d():l&&l({isSuccessProgressCall:E})})):()=>{});if(ht("onBeforeProgressCall"),a){a((()=>{const{remoteCallerData:t}=e,{incomingNumber:s}=t;return s})())}return e.answerToIncomingCall({mediaStream:s,extraHeaders:n,iceServers:i,degradationPreference:r,ontrack:_}).then((t=>(ht("onSuccess"),E=!0,g(),c&&c({isPurgatory:mt(S)}),e.onceRaceSession(["ended","failed"],(()=>{C(),m&&m()})),t))).catch((e=>{throw ht("onFail"),h&&h(),C(),e})).finally((()=>{ht("onFinish"),u&&u()}))},resolveAskPermissionToEnableCam:e=>()=>e.isCallActive?(ht("askPermissionToEnableCam"),e.askPermissionToEnableCam()):Promise.resolve(),resolveCallToServer:e=>t=>{const{conference:s,mediaStream:n,extraHeaders:i,iceServers:r,degradationPreference:o,setRemoteStreams:a,onBeforeProgressCall:c,onSuccessProgressCall:d,onEnterPurgatory:l,onEnterConference:h,onFailProgressCall:u,onFinishProgressCall:m,onEndedCall:g}=t,_=St({setRemoteStreams:a,getRemoteStreams:gt(e)}),S=_t(_);ht("callToServer",t);let E,C=!1;const f=(ht("subscribeEnterConference: onEnterConference",h),l||h?e.onSession("enterRoom",(e=>{ht("enterRoom",{_room:e,isSuccessProgressCall:C}),E=e,mt(E)?l&&l():h&&h({isSuccessProgressCall:C})})):()=>{});return ht("onBeforeProgressCall"),c&&c(s),(ht("startCall"),e.call({mediaStream:n,extraHeaders:i,iceServers:r,degradationPreference:o,number:s,ontrack:S})).then((t=>(ht("onSuccess"),C=!0,_(),d&&d({isPurgatory:mt(E)}),e.onceRaceSession(["ended","failed"],(()=>{f(),g&&g()})),t))).catch((e=>{throw ht("onFail"),u&&u(),f(),e})).finally((()=>{ht("onFinish"),m&&m()}))},resolveConnectToServer:e=>{const s=e=>{if(!t.isCanceledError(e))throw e;return!1};return t=>{const{userAgent:n,sipWebSocketServerURL:i,sipServerUrl:r,remoteAddress:o,displayName:a,name:c,password:d,isRegisteredUser:l,sdpSemantics:h,isDisconnectOnFail:u}=t;return ht("connectToServer",t),e.connect({userAgent:n,sdpSemantics:h,sipWebSocketServerURL:i,sipServerUrl:r,remoteAddress:o,displayName:a,password:d,user:c,register:l}).then((()=>(ht("connectToServer then"),!0))).catch((t=>(ht("connectToServer catch: error",t),u?e.disconnect().then((()=>s(t))).catch((()=>s(t))):s(t))))}},resolveDisconnectFromServer:e=>()=>(ht("disconnectFromServer"),e.disconnect().then((()=>(ht("disconnectFromServer: then"),!1))).catch((e=>(ht("disconnectFromServer: catch",e),!1)))),resolveGetRemoteStreams:gt,resolveOnMustStopPresentation:e=>t=>(ht("onMustStopPresentation"),e.onSession("mustStopPresentation",t)),resolveOnUseLicense:e=>t=>(ht("onUseLicense"),e.onSession("useLicense",t)),resolveSendMediaState:e=>({isEnabledCam:t,isEnabledMic:s})=>e.isCallActive?(ht("sendMediaState"),e.sendMediaState({cam:t,mic:s})):Promise.resolve(),resolveSendRefusalToTurnOnCam:e=>()=>e.isCallActive?(ht("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch((e=>{ht("sendRefusalToTurnOnCam: error",e)}))):Promise.resolve(),resolveSendRefusalToTurnOnMic:e=>()=>e.isCallActive?(ht("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch((e=>{ht("sendRefusalToTurnOnMic: error",e)}))):Promise.resolve(),resolveStartPresentation:({maxBitrate:e=1e6,sipConnector:t})=>({mediaStream:s,isP2P:n=!1})=>(ht("startPresentation"),t.startPresentation(s,{isP2P:n,maxBitrate:e})),resolveStopShareSipConnector:({sipConnector:e})=>({isP2P:t=!1}={isP2P:!1})=>(ht("stopShareSipConnector"),e.stopPresentation({isP2P:t}).catch(ht)),resolveUpdatePresentation:({sipConnector:e,maxBitrate:t=1e6})=>({mediaStream:s,isP2P:n=!1})=>(ht("updatePresentation"),e.updatePresentation(s,{isP2P:n,maxBitrate:t})),resolveUpdateRemoteStreams:St,sendDTMFAccumulated:({accumulatedKeys:e,sendKey:t,canRunTask:s})=>{const n=(e=>_.default((e=>S.default(e,"")),(t=>t.map((t=>()=>e(t))))))(t),i=n(e);return g.default(i,s)}});Object.defineProperty(e,"debug",{enumerable:!0,get:function(){return u.default}}),e.causes=T,e.default=class{constructor({JsSIP:e}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger(I,void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const n=this.incomingSession,i=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(A,i),t(n.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if(e===je){this.incomingSession=t;const e=this.remoteCallerData;t.on(ge,(({originator:t})=>{this.removeIncomingSession(),t!==Ve?this._uaEvents.trigger(b,e):this._uaEvents.trigger(w,e)})),this._uaEvents.trigger(M,e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:n=!1,sipServerUrl:i,sipWebSocketServerURL:r,remoteAddress:o,extraHeaders:a=[],sdpSemantics:c="plan-b",sessionTimers:d=!1,registerExpires:l=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:u=6,userAgent:m})=>C(this,void 0,void 0,(function*(){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!s)throw new Error("password is required for authorized connection");let g;this._connectionConfiguration={sipServerUrl:i,displayName:e,register:n,user:t,password:s},this._init({sipServerUrl:i,sipWebSocketServerURL:r}),g=n&&t?t.trim():ke();const _={password:s,register:n,display_name:Ue(e),user_agent:m,sdp_semantics:c,sockets:[this.socket],uri:this.getSipServerUrl(g),session_timers:d,register_expires:l,connection_recovery_min_interval:h,connection_recovery_max_interval:u};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!_.register,this.ua=new this.JsSIP.UA(_),this._uaEvents.eachTriggers(((e,t)=>{const s=ve.find((e=>e===t));s&&this.ua.on(s,e)}));const S=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(o),E=[...S,...a];return this.ua.registrator().setExtraHeaders(E),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{i(),e(this.ua)},n=e=>{i(),t(e)},i=()=>{this.off(U,s),this.off(q,n),this.off(O,s),this.off(y,n)};(()=>{this.isRegisterConfig?(this.on(U,s),this.on(q,n)):this.on(O,s),this.on(y,n)})(),this.on(D,this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,n)=>{let i=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(i=this.ua.set("display_name",Ue(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=i||r;r&&this.isRegisterConfig?this.register().then((()=>s(o))).catch(n):o?s(o):n(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>C(this,void 0,void 0,(function*(){this.off(D,this.handleNewRTCSession);const e=new Promise((e=>{this.once(y,(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(y,void 0)):this._uaEvents.trigger(y,void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:n,iceServers:i,videoMode:r,audioMode:o,degradationPreference:a,offerToReceiveAudio:c=!0,offerToReceiveVideo:d=!0})=>new Promise(((l,h)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(l).catch(h),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Be(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:n,videoMode:i,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const s=Re.find((e=>e===t));s&&d.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const l=Be(e,{videoMode:i,audioMode:r});d.answer({extraHeaders:s,videoMode:i,audioMode:r,degradationPreference:o,mediaStream:l,pcConfig:{iceServers:n}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const n=()=>{this.offSession(me,a),this.offSession(ue,c)},i=()=>{this.offSession(ge,r),this.offSession(he,r)},r=e=>{n(),i(),s(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger(X,o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger(j,o),n(),i(),t(o)};(()=>{this.onSession(me,a),this.onSession(ue,c)})(),(()=>{this.onSession(ge,r),this.onSession(he,r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{const n=this.session;n?(this.onceSession(_e,(({originator:e})=>{e===Ve&&t()})),n.sendDTMF(e,{duration:120,interToneGap:600})):s(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>C(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case ye:this._sessionEvents.trigger(B,void 0);break;case De:this._sessionEvents.trigger(x,void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger(L,void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader(be),s=e.getHeader(we);if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger(Y,e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(se,t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(te,t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(oe,s)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(ae,s)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger(ce,void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger(de,void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const n={conference:e,participant:t,jwt:s};this._uaEvents.trigger(le,n)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger($,t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ne,t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(re,t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ie,t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger(H,t)},this._triggerShareState=e=>{const t=e.getHeader(Oe);this._sessionEvents.trigger(W,t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader(Ie),n=s===$e.ADMIN_SYNC_FORCED;if(t===Xe.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(z,{isSyncForced:n});else if(t===Xe.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(K,{isSyncForced:n});else if(t!==Xe.RESUME_MAIN_CAM&&t!==Xe.PAUSE_MAIN_CAM||!s){const s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger(J,{mainCam:t,resolutionMainCam:s})}else this._sessionEvents.trigger(ee,{isSyncForced:n})},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC"),s=e.getHeader(Ie)===$e.ADMIN_SYNC_FORCED;t===Ye.ADMIN_START_MIC?this._sessionEvents.trigger(Z,{isSyncForced:s}):t===Ye.ADMIN_STOP_MIC&&this._sessionEvents.trigger(Q,{isSyncForced:s})},this._triggerUseLicense=e=>{const t=e.getHeader("X-WEBRTC-USE-LICENSE");this._sessionEvents.trigger(V,t)},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,n=s.getHeader("content-type");if(n)switch(n){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case Me:this._triggerShareState(s);break;case Ae:this._triggerMainCamControl(s);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(s);break;case"application/vinteo.webrtc.uselic":this._triggerUseLicense(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;t===je&&this._sessionEvents.trigger(G,e),this._restoreSession()},this.JsSIP=e,this._sessionEvents=new l.default(Pe),this._uaEvents=new l.default(Ne),this._cancelableConnect=new t.CancelableRequest(this._connect,{moduleName:Je,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new t.CancelableRequest(this._createUa,{moduleName:Je}),this._cancelableDisconnect=new t.CancelableRequest(this._disconnect,{moduleName:Je}),this._cancelableSet=new t.CancelableRequest(this._set,{moduleName:Je}),this._cancelableCall=new t.CancelableRequest(this._call,{moduleName:Je}),this._cancelableAnswer=new t.CancelableRequest(this._answer,{moduleName:Je}),this._cancelableSendDTMF=new t.CancelableRequest(this._sendDTMF,{moduleName:Je}),this.onSession(W,this._handleShareState),this.onSession(Se,this._handleNewInfo),this.on(F,this._handleSipEvent),this.onSession(ge,this._handleEnded),this.onSession(he,this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on(U,e),this.ua.on(q,t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on(k,e),this.ua.unregister()):t(new Error("ua is not registered"))}))}sendOptions(e,t,s){return this.ua?new Promise(((n,i)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{n()},failed:e=>{i(e)}}})}catch(e){i(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo(Ae,void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}_sendPresentation(e,t,{maxBitrate:s,degradationPreference:n,isNeedReinvite:i=!0,isP2P:r=!1}){const o=Be(t);this._streamPresentationCurrent=o;const a=r?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"],c=e.sendInfo(Me,void 0,{extraHeaders:a}).then((()=>e.startPresentation(o,i,n))).then((()=>{const{connection:e}=this;if(!e||void 0===s)return;return((e,t,s)=>{const n=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return n?He(n,{maxBitrate:s}):Promise.resolve()})(e.getSenders(),t,s)})).then((()=>t)).catch((e=>{throw this._sessionEvents.trigger(Ce,e),e}));return this.promisePendingStartPresentation=c,c.finally((()=>{this.promisePendingStartPresentation=void 0}))}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:n,degradationPreference:i}={}){const r=this.establishedSession;return r?this._streamPresentationCurrent?Promise.reject(new Error("Presentation is already started")):this._sendPresentation(r,e,{isNeedReinvite:t,isP2P:s,maxBitrate:n,degradationPreference:i}):Promise.reject(new Error("No session established"))}stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation||Promise.resolve();const n=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],i=this.establishedSession;return i&&t&&(s=s.then((()=>i.sendInfo(Me,void 0,{extraHeaders:n}))).then((()=>i.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger(Ce,e),e}))),!i&&t&&this._sessionEvents.trigger(Ee,t),this.promisePendingStopPresentation=s,s.finally((()=>{this._resetPresentation()}))}updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:n}={}){return C(this,void 0,void 0,(function*(){const i=this.establishedSession;return i?this._streamPresentationCurrent?(this.promisePendingStartPresentation&&(yield this.promisePendingStartPresentation),this._sendPresentation(i,e,{isP2P:t,maxBitrate:s,degradationPreference:n,isNeedReinvite:!1})):Promise.reject(new Error("Presentation has not started yet")):Promise.reject(new Error("No session established"))}))}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,n,i,r;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(n=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===n?void 0:n.uri.host,incomingNumber:null===(r=null===(i=null==this?void 0:this.incomingSession)||void 0===i?void 0:i.remote_identity)||void 0===r?void 0:r.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!(!this.ua||!this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,n=this._remoteStreams[s]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[s]=n,n}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,n)=>{if("audio"===s.kind)return;const i=s,r=e[n-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(i,o);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession(Y)}waitSyncMediaState(){return this.waitSession(ee)}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}sendMediaState({cam:e,mic:t},s={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const n=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},s),{extraHeaders:n}))}_sendRefusalToTurnOn(e,t={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const s=[`X-Vinteo-Media-Type: ${"mic"==e?0:1}`];return this.session.sendInfo("application/vinteo.webrtc.refusal",void 0,Object.assign(Object.assign({},t),{extraHeaders:s}))}sendRefusalToTurnOnMic(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",e)}sendRefusalToTurnOnCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",e)}},e.disableDebug=()=>{u.default.enable(`-${lt}`)},e.enableDebug=()=>{u.default.enable(`${lt}`)},e.eventNames=Te,e.getCodecFromSender=E,e.hasCanceledCallError=(e=new Error)=>{const{originator:s,cause:n}=e;return!!t.isCanceledError(e)||"string"==typeof n&&(n===f||n===v||s===Ve&&(n===N||n===R))},e.resolveVideoSendingBalancer=(e,{ignoreForCodec:t,onSetParameters:s}={})=>{const n=()=>{const{connection:n}=e;return n?dt({connection:n,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))};let i=n;const r=n=>{i=()=>{const{mainCam:i,resolutionMainCam:r}=n,{connection:o}=e;return o?dt({mainCam:i,resolutionMainCam:r,connection:o,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))},i()};return{subscribe:()=>{e.onSession("main-cam-control",r)},unsubscribe:()=>{e.offSession("main-cam-control",r)},balanceByTrack:n,resetMainCamControl(){i=n},reBalance:()=>i()}},e.tools=vt,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@krivega/cancelable-promise"),require("events-constructor"),require("stack-promises"),require("debug"),require("lodash/debounce"),require("sequent-promises"),require("lodash/flow"),require("lodash/split")):"function"==typeof define&&define.amd?define(["exports","@krivega/cancelable-promise","events-constructor","stack-promises","debug","lodash/debounce","sequent-promises","lodash/flow","lodash/split"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sipConnector={},e.cancelablePromise,e.Events,e.createStackPromises,e.debug,e.debounce,e.sequentPromises,e.flow,e.split)}(this,(function(e,t,s,n,i,r,o,a,c){"use strict";function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=d(s),h=d(n),u=d(i),m=d(r),g=d(o),_=d(a),S=d(c);const E=e=>e.getStats().then((e=>{const t=(s="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===s)));var s;return null==t?void 0:t.mimeType}));function C(e,t,s,n){return new(s||(s=Promise))((function(i,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const f="Request Timeout",v="Rejected",p="Not Found",R="Terminated",N="Canceled",P="Bad Media Description";var T=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:f,SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:v,REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:p,ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:R,WEBRTC_ERROR:"WebRTC Error",CANCELED:N,NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:P,RTP_TIMEOUT:"RTP Timeout"});const M="incomingCall",A="declinedIncomingCall",b="failedIncomingCall",w="terminatedIncomingCall",I="connecting",O="connected",y="disconnected",D="newRTCSession",U="registered",k="unregistered",q="registrationFailed",F="sipEvent",B="availableSecondRemoteStream",x="notAvailableSecondRemoteStream",L="mustStopPresentation",W="shareState",H="enterRoom",V="useLicense",j="peerconnection:confirmed",X="peerconnection:ontrack",$="channels",Y="channels:notify",G="ended:fromserver",J="main-cam-control",K="admin-stop-main-cam",z="admin-start-main-cam",Q="admin-stop-mic",Z="admin-start-mic",ee="admin-force-sync-media-state",te="participant:added-to-list-moderators",se="participant:removed-from-list-moderators",ne="participant:move-request-to-conference",ie="participant:move-request-to-stream",re="participant:canceling-word-request",oe="webcast:started",ae="webcast:stopped",ce="account:changed",de="account:deleted",le="conference:participant-token-issued",he="ended",ue="confirmed",me="peerconnection",ge="failed",_e="newDTMF",Se="newInfo",Ee="presentation:ended",Ce="presentation:failed",fe=[M,A,w,b,re,ie,ne,Y,le,ce,de,oe,ae,te,se],ve=[I,O,y,D,U,k,q,"newMessage",F],pe=[B,x,L,W,H,V,j,X,$,G,J,z,K,Q,Z,ee],Re=[he,I,"sending","reinvite","replaces","refer","progress","accepted",ue,me,ge,"muted","unmuted",_e,Se,"hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end",Ee,Ce],Ne=[...ve,...fe],Pe=[...Re,...pe];var Te=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:fe,UA_JSSIP_EVENT_NAMES:ve,SESSION_SYNTHETICS_EVENT_NAMES:pe,SESSION_JSSIP_EVENT_NAMES:Re,UA_EVENT_NAMES:Ne,SESSION_EVENT_NAMES:Pe});const Me="application/vinteo.webrtc.sharedesktop",Ae="application/vinteo.webrtc.maincam",be="X-WEBRTC-INPUT-CHANNELS",we="X-WEBRTC-OUTPUT-CHANNELS",Ie="X-WEBRTC-SYNC",Oe="x-webrtc-share-state",ye="YOUCANRECEIVECONTENT",De="CONTENTEND";const Ue=e=>e.trim().replace(/ /g,"_"),ke=(qe=1e5,Fe=99999999,()=>Math.floor(Math.random()*(Fe-qe))+qe);var qe,Fe;const Be=(e,{videoMode:t,audioMode:s}={})=>{if(!e||"recvonly"===t&&"recvonly"===s)return;const n=[..."recvonly"===s?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],i=new MediaStream(n);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},xe=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,Le=xe(1),We=xe(void 0),He=(e,t,s)=>{const n=e.getParameters();n.encodings&&0!==n.encodings.length||(n.encodings=[{}]);const[i]=n.encodings,r=i.scaleResolutionDownBy,o=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&Le(s,t))return s})(t.scaleResolutionDownBy,r);let a=!1;void 0!==o&&(n.encodings[0].scaleResolutionDownBy=o,a=!0);const c=i.maxBitrate,d=((e,t)=>{if(We(e,t))return e})(t.maxBitrate,c);return void 0!==d&&(n.encodings[0].maxBitrate=d,a=!0),a?(s&&s(n),e.setParameters(n).then((()=>({parameters:n,isChanged:a})))):Promise.resolve({parameters:n,isChanged:a})},Ve="local",je="remote";var Xe,$e,Ye,Ge;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(Xe||(Xe={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}($e||($e={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}(Ye||(Ye={})),e.EUseLicense=void 0,(Ge=e.EUseLicense||(e.EUseLicense={})).AUDIO="AUDIO",Ge.VIDEO="VIDEO",Ge.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION";const Je="SipConnector";const Ke=(e,t)=>!!e&&!!t&&e.toLowerCase().includes(t.toLowerCase()),ze=e=>1e6*e,Qe=ze(.06),Ze=ze(4),et=(e,t)=>(e=>Ke(e,"av1"))(t)?.6*e:e,tt=(e,t)=>{const s=(e=>e<=64?Qe:e<=128?ze(.12):e<=256?ze(.25):e<=384?ze(.32):e<=426?ze(.38):e<=640?ze(.5):e<=848?ze(.7):e<=1280?ze(1):e<=1920?ze(2):Ze)(e);return et(s,t)},st=h.default(),nt=e=>(st.add(e),st().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),it=({sender:e,scaleResolutionDownBy:t,maxBitrate:s,onSetParameters:n})=>nt((()=>He(e,{scaleResolutionDownBy:t,maxBitrate:s},n))),rt=({sender:e,codec:t},s)=>{const n=(e=>et(Qe,e))(t);return it({sender:e,maxBitrate:n,onSetParameters:s,scaleResolutionDownBy:200})},ot=({sender:e,track:t,codec:s},n)=>{const i=t.getSettings().width,r=tt(i,s);return it({sender:e,maxBitrate:r,onSetParameters:n,scaleResolutionDownBy:1})},at=({mainCam:e,resolutionMainCam:t,sender:s,track:n,codec:i},r)=>{switch(e){case Xe.PAUSE_MAIN_CAM:return rt({sender:s,codec:i},r);case Xe.RESUME_MAIN_CAM:return ot({sender:s,track:n,codec:i},r);case Xe.MAX_MAIN_CAM_RESOLUTION:return t?(({sender:e,track:t,resolution:s,codec:n},i)=>{const r=t.getSettings(),o=r.width,a=r.height,[c,d]=s.split("x"),l=o/+c,h=a/+d,u=Math.max(l,h,1),m=tt(+c,n);return it({sender:e,maxBitrate:m,onSetParameters:i,scaleResolutionDownBy:u})})({sender:s,track:n,codec:i,resolution:t},r):ot({sender:s,track:n,codec:i},r);default:return ot({sender:s,track:n,codec:i},r)}},ct={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},dt=({mainCam:e,resolutionMainCam:t,connection:s,onSetParameters:n,ignoreForCodec:i})=>C(void 0,void 0,void 0,(function*(){const r=(e=>e.find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)})))(s.getSenders());if(!r||!r.track)return ct;const o=yield E(r);return Ke(o,i)?ct:at({mainCam:e,resolutionMainCam:t,sender:r,codec:o,track:r.track},n)})),lt="sip-connector",ht=u.default(lt),ut="purgatory",mt=e=>e===ut,gt=e=>()=>(ht("getRemoteStreams"),e.getRemoteStreams()),_t=e=>({track:t})=>{(({kind:e,readyState:t})=>"video"===e&&"live"===t)(t)&&e()},St=({getRemoteStreams:e,setRemoteStreams:t})=>m.default((()=>{const s=e();ht("remoteStreams",s),s&&t(s)}),200),Et=e=>{const{url:t,cause:s}=e;let n=t;return s!==P&&s!==p||(n=`${e.message.to.uri.user}@${e.message.to.uri.host}`),n};var Ct;!function(e){e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK"}(Ct||(Ct={}));var ft=Object.freeze({__proto__:null,getLinkError:Et,getTypeFromError:(e=new Error)=>{var t;const{cause:s,socket:n}=e;let i=Ct.CONNECT_SERVER_FAILED;return"Forbidden"===s?i=Ct.WRONG_USER_OR_PASSWORD:s===P?i=Ct.BAD_MEDIA_ERROR:s===p?i=Ct.NOT_FOUND_ERROR:n&&3===(null===(t=null==n?void 0:n._ws)||void 0===t?void 0:t.readyState)?i=Ct.WS_CONNECTION_FAILED:Et(e)&&(i=Ct.CONNECT_SERVER_FAILED_BY_LINK),i},getValuesFromError:(e=new Error)=>{const{code:t,cause:s,message:n}=e,i=Et(e),r={};return n&&(r.message=n),i&&(r.link=i),t&&(r.code=t),s&&(r.cause=s),r},get EErrorTypes(){return Ct}});var vt=Object.freeze({__proto__:null,PURGATORY_CONFERENCE_NUMBER:ut,createSyncMediaState:({sipConnector:e})=>{const t=(e,t)=>(s={isSyncForced:!1})=>s.isSyncForced?e():t(),s=(e=>t=>(ht("onStartMainCam"),e.onSession("admin-start-main-cam",t)))(e),n=(e=>t=>(ht("onStopMainCam"),e.onSession("admin-stop-main-cam",t)))(e),i=(e=>t=>(ht("onStartMic"),e.onSession("admin-start-mic",t)))(e),r=(e=>t=>(ht("onStopMic"),e.onSession("admin-stop-mic",t)))(e);let o=()=>{},a=()=>{},c=()=>{},d=()=>{};return{start:e=>{(({onStartMainCamForced:e,onStartMainCamNotForced:l,onStopMainCamForced:h,onStopMainCamNotForced:u,onStartMicForced:m,onStartMicNotForced:g,onStopMicForced:_,onStopMicNotForced:S})=>{const E=t(e,l);o=s(E);const C=t(h,u);a=n(C);const f=t(m,g);c=i(f);const v=t(_,S);d=r(v)})(e)},stop:()=>{o(),a(),c(),d()}}},error:ft,getExtraHeaders:({sessionId:e,remoteAddress:t,isMutedAudio:s,isMutedVideo:n,isRegistered:i,isPresentationCall:r})=>{const o=[],a=s?"0":"1",c=n?"0":"1";return o.push(`X-Vinteo-Mic-State: ${a}`),o.push(`X-Vinteo-MainCam-State: ${c}`),i||o.push("X-Vinteo-Purgatory-Call: yes"),e&&o.push(`X-Vinteo-Session: ${e}`),r&&o.push("X-Vinteo-Presentation-Call: yes"),t&&o.push(`X-Vinteo-Remote: ${t}`),o},getUserAgent:({isUnifiedSdpSemantic:e,appVersion:t,browserName:s,browserVersion:n,appName:i})=>{const r=e?(({appName:e,appVersion:t,browserName:s,browserVersion:n})=>{const i=`${e} ${t}`;let r;return r=s?`${s} ${n}, ${i}`:i,`ChromeNew - ${r}`})({appVersion:t,browserName:s,browserVersion:n,appName:i}):"Chrome";return r},hasPurgatory:mt,resolveAnswerIncomingCall:e=>t=>{const{mediaStream:s,extraHeaders:n,iceServers:i,degradationPreference:r,setRemoteStreams:o,onBeforeProgressCall:a,onSuccessProgressCall:c,onEnterPurgatory:d,onEnterConference:l,onFailProgressCall:h,onFinishProgressCall:u,onEndedCall:m}=t,g=St({setRemoteStreams:o,getRemoteStreams:gt(e)}),_=_t(g);ht("answerIncomingCall",t);let S,E=!1;const C=(ht("subscribeEnterConference: onEnterConference",l),d||l?e.onSession("enterRoom",(e=>{ht("enterRoom",{_room:e,isSuccessProgressCall:E}),S=e,mt(S)?d&&d():l&&l({isSuccessProgressCall:E})})):()=>{});if(ht("onBeforeProgressCall"),a){a((()=>{const{remoteCallerData:t}=e,{incomingNumber:s}=t;return s})())}return e.answerToIncomingCall({mediaStream:s,extraHeaders:n,iceServers:i,degradationPreference:r,ontrack:_}).then((t=>(ht("onSuccess"),E=!0,g(),c&&c({isPurgatory:mt(S)}),e.onceRaceSession(["ended","failed"],(()=>{C(),m&&m()})),t))).catch((e=>{throw ht("onFail"),h&&h(),C(),e})).finally((()=>{ht("onFinish"),u&&u()}))},resolveAskPermissionToEnableCam:e=>()=>e.isCallActive?(ht("askPermissionToEnableCam"),e.askPermissionToEnableCam()):Promise.resolve(),resolveCallToServer:e=>t=>{const{conference:s,mediaStream:n,extraHeaders:i,iceServers:r,degradationPreference:o,setRemoteStreams:a,onBeforeProgressCall:c,onSuccessProgressCall:d,onEnterPurgatory:l,onEnterConference:h,onFailProgressCall:u,onFinishProgressCall:m,onEndedCall:g}=t,_=St({setRemoteStreams:a,getRemoteStreams:gt(e)}),S=_t(_);ht("callToServer",t);let E,C=!1;const f=(ht("subscribeEnterConference: onEnterConference",h),l||h?e.onSession("enterRoom",(e=>{ht("enterRoom",{_room:e,isSuccessProgressCall:C}),E=e,mt(E)?l&&l():h&&h({isSuccessProgressCall:C})})):()=>{});return ht("onBeforeProgressCall"),c&&c(s),(ht("startCall"),e.call({mediaStream:n,extraHeaders:i,iceServers:r,degradationPreference:o,number:s,ontrack:S})).then((t=>(ht("onSuccess"),C=!0,_(),d&&d({isPurgatory:mt(E)}),e.onceRaceSession(["ended","failed"],(()=>{f(),g&&g()})),t))).catch((e=>{throw ht("onFail"),u&&u(),f(),e})).finally((()=>{ht("onFinish"),m&&m()}))},resolveConnectToServer:e=>{const s=e=>{if(!t.isCanceledError(e))throw e;return!1};return t=>{const{userAgent:n,sipWebSocketServerURL:i,sipServerUrl:r,remoteAddress:o,displayName:a,name:c,password:d,isRegisteredUser:l,sdpSemantics:h,isDisconnectOnFail:u}=t;return ht("connectToServer",t),e.connect({userAgent:n,sdpSemantics:h,sipWebSocketServerURL:i,sipServerUrl:r,remoteAddress:o,displayName:a,password:d,user:c,register:l}).then((()=>(ht("connectToServer then"),!0))).catch((t=>(ht("connectToServer catch: error",t),u?e.disconnect().then((()=>s(t))).catch((()=>s(t))):s(t))))}},resolveDisconnectFromServer:e=>()=>(ht("disconnectFromServer"),e.disconnect().then((()=>(ht("disconnectFromServer: then"),!1))).catch((e=>(ht("disconnectFromServer: catch",e),!1)))),resolveGetRemoteStreams:gt,resolveOnMustStopPresentation:e=>t=>(ht("onMustStopPresentation"),e.onSession("mustStopPresentation",t)),resolveOnUseLicense:e=>t=>(ht("onUseLicense"),e.onSession("useLicense",t)),resolveSendMediaState:e=>({isEnabledCam:t,isEnabledMic:s})=>e.isCallActive?(ht("sendMediaState"),e.sendMediaState({cam:t,mic:s})):Promise.resolve(),resolveSendRefusalToTurnOnCam:e=>()=>e.isCallActive?(ht("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch((e=>{ht("sendRefusalToTurnOnCam: error",e)}))):Promise.resolve(),resolveSendRefusalToTurnOnMic:e=>()=>e.isCallActive?(ht("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch((e=>{ht("sendRefusalToTurnOnMic: error",e)}))):Promise.resolve(),resolveStartPresentation:({maxBitrate:e=1e6,sipConnector:t})=>({mediaStream:s,isP2P:n=!1})=>(ht("startPresentation"),t.startPresentation(s,{isP2P:n,maxBitrate:e})),resolveStopShareSipConnector:({sipConnector:e})=>({isP2P:t=!1}={isP2P:!1})=>(ht("stopShareSipConnector"),e.stopPresentation({isP2P:t}).catch(ht)),resolveUpdatePresentation:({sipConnector:e,maxBitrate:t=1e6})=>({mediaStream:s,isP2P:n=!1})=>(ht("updatePresentation"),e.updatePresentation(s,{isP2P:n,maxBitrate:t})),resolveUpdateRemoteStreams:St,sendDTMFAccumulated:({accumulatedKeys:e,sendKey:t,canRunTask:s})=>{const n=(e=>_.default((e=>S.default(e,"")),(t=>t.map((t=>()=>e(t))))))(t),i=n(e);return g.default(i,s)}});Object.defineProperty(e,"debug",{enumerable:!0,get:function(){return u.default}}),e.causes=T,e.default=class{constructor({JsSIP:e}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger(I,void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const n=this.incomingSession,i=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(A,i),t(n.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if(e===je){this.incomingSession=t;const e=this.remoteCallerData;t.on(ge,(({originator:t})=>{this.removeIncomingSession(),t!==Ve?this._uaEvents.trigger(b,e):this._uaEvents.trigger(w,e)})),this._uaEvents.trigger(M,e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:n=!1,sipServerUrl:i,sipWebSocketServerURL:r,remoteAddress:o,extraHeaders:a=[],sdpSemantics:c="plan-b",sessionTimers:d=!1,registerExpires:l=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:u=6,userAgent:m})=>C(this,void 0,void 0,(function*(){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!s)throw new Error("password is required for authorized connection");let g;this._connectionConfiguration={sipServerUrl:i,displayName:e,register:n,user:t,password:s},this._init({sipServerUrl:i,sipWebSocketServerURL:r}),g=n&&t?t.trim():ke();const _={password:s,register:n,display_name:Ue(e),user_agent:m,sdp_semantics:c,sockets:[this.socket],uri:this.getSipServerUrl(g),session_timers:d,register_expires:l,connection_recovery_min_interval:h,connection_recovery_max_interval:u};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!_.register,this.ua=new this.JsSIP.UA(_),this._uaEvents.eachTriggers(((e,t)=>{const s=ve.find((e=>e===t));s&&this.ua.on(s,e)}));const S=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(o),E=[...S,...a];return this.ua.registrator().setExtraHeaders(E),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{i(),e(this.ua)},n=e=>{i(),t(e)},i=()=>{this.off(U,s),this.off(q,n),this.off(O,s),this.off(y,n)};(()=>{this.isRegisterConfig?(this.on(U,s),this.on(q,n)):this.on(O,s),this.on(y,n)})(),this.on(D,this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,n)=>{let i=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(i=this.ua.set("display_name",Ue(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=i||r;r&&this.isRegisterConfig?this.register().then((()=>s(o))).catch(n):o?s(o):n(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>C(this,void 0,void 0,(function*(){this.off(D,this.handleNewRTCSession);const e=new Promise((e=>{this.once(y,(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(y,void 0)):this._uaEvents.trigger(y,void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:n,iceServers:i,videoMode:r,audioMode:o,degradationPreference:a,offerToReceiveAudio:c=!0,offerToReceiveVideo:d=!0})=>new Promise(((l,h)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(l).catch(h),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Be(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:n,videoMode:i,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const s=Re.find((e=>e===t));s&&d.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const l=Be(e,{videoMode:i,audioMode:r});d.answer({extraHeaders:s,videoMode:i,audioMode:r,degradationPreference:o,mediaStream:l,pcConfig:{iceServers:n}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const n=()=>{this.offSession(me,a),this.offSession(ue,c)},i=()=>{this.offSession(ge,r),this.offSession(he,r)},r=e=>{n(),i(),s(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger(X,o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger(j,o),n(),i(),t(o)};(()=>{this.onSession(me,a),this.onSession(ue,c)})(),(()=>{this.onSession(ge,r),this.onSession(he,r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{const n=this.session;n?(this.onceSession(_e,(({originator:e})=>{e===Ve&&t()})),n.sendDTMF(e,{duration:120,interToneGap:600})):s(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>C(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case ye:this._sessionEvents.trigger(B,void 0);break;case De:this._sessionEvents.trigger(x,void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger(L,void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader(be),s=e.getHeader(we);if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger($,e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(se,t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(te,t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(oe,s)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(ae,s)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger(ce,void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger(de,void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const n={conference:e,participant:t,jwt:s};this._uaEvents.trigger(le,n)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger(Y,t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ne,t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(re,t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ie,t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger(H,t)},this._triggerShareState=e=>{const t=e.getHeader(Oe);this._sessionEvents.trigger(W,t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader(Ie),n=s===Ye.ADMIN_SYNC_FORCED;if(t===Xe.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(z,{isSyncForced:n});else if(t===Xe.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(K,{isSyncForced:n});else if(t!==Xe.RESUME_MAIN_CAM&&t!==Xe.PAUSE_MAIN_CAM||!s){const s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger(J,{mainCam:t,resolutionMainCam:s})}else this._sessionEvents.trigger(ee,{isSyncForced:n})},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC"),s=e.getHeader(Ie)===Ye.ADMIN_SYNC_FORCED;t===$e.ADMIN_START_MIC?this._sessionEvents.trigger(Z,{isSyncForced:s}):t===$e.ADMIN_STOP_MIC&&this._sessionEvents.trigger(Q,{isSyncForced:s})},this._triggerUseLicense=e=>{const t=e.getHeader("X-WEBRTC-USE-LICENSE");this._sessionEvents.trigger(V,t)},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,n=s.getHeader("content-type");if(n)switch(n){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case Me:this._triggerShareState(s);break;case Ae:this._triggerMainCamControl(s);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(s);break;case"application/vinteo.webrtc.uselic":this._triggerUseLicense(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;t===je&&this._sessionEvents.trigger(G,e),this._restoreSession()},this.JsSIP=e,this._sessionEvents=new l.default(Pe),this._uaEvents=new l.default(Ne),this._cancelableConnect=new t.CancelableRequest(this._connect,{moduleName:Je,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new t.CancelableRequest(this._createUa,{moduleName:Je}),this._cancelableDisconnect=new t.CancelableRequest(this._disconnect,{moduleName:Je}),this._cancelableSet=new t.CancelableRequest(this._set,{moduleName:Je}),this._cancelableCall=new t.CancelableRequest(this._call,{moduleName:Je}),this._cancelableAnswer=new t.CancelableRequest(this._answer,{moduleName:Je}),this._cancelableSendDTMF=new t.CancelableRequest(this._sendDTMF,{moduleName:Je}),this.onSession(W,this._handleShareState),this.onSession(Se,this._handleNewInfo),this.on(F,this._handleSipEvent),this.onSession(ge,this._handleEnded),this.onSession(he,this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on(U,e),this.ua.on(q,t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on(k,e),this.ua.unregister()):t(new Error("ua is not registered"))}))}sendOptions(e,t,s){return this.ua?new Promise(((n,i)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{n()},failed:e=>{i(e)}}})}catch(e){i(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo(Ae,void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}_sendPresentation(e,t,{maxBitrate:s,degradationPreference:n,isNeedReinvite:i=!0,isP2P:r=!1}){const o=Be(t);this._streamPresentationCurrent=o;const a=r?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"],c=e.sendInfo(Me,void 0,{extraHeaders:a}).then((()=>e.startPresentation(o,i,n))).then((()=>{const{connection:e}=this;if(!e||void 0===s)return;return((e,t,s)=>{const n=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return n?He(n,{maxBitrate:s}):Promise.resolve()})(e.getSenders(),t,s)})).then((()=>t)).catch((e=>{throw this._sessionEvents.trigger(Ce,e),e}));return this.promisePendingStartPresentation=c,c.finally((()=>{this.promisePendingStartPresentation=void 0}))}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:n,degradationPreference:i}={}){const r=this.establishedSession;return r?this._streamPresentationCurrent?Promise.reject(new Error("Presentation is already started")):this._sendPresentation(r,e,{isNeedReinvite:t,isP2P:s,maxBitrate:n,degradationPreference:i}):Promise.reject(new Error("No session established"))}stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation||Promise.resolve();const n=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],i=this.establishedSession;return i&&t&&(s=s.then((()=>i.sendInfo(Me,void 0,{extraHeaders:n}))).then((()=>i.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger(Ce,e),e}))),!i&&t&&this._sessionEvents.trigger(Ee,t),this.promisePendingStopPresentation=s,s.finally((()=>{this._resetPresentation()}))}updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:n}={}){return C(this,void 0,void 0,(function*(){const i=this.establishedSession;return i?this._streamPresentationCurrent?(this.promisePendingStartPresentation&&(yield this.promisePendingStartPresentation),this._sendPresentation(i,e,{isP2P:t,maxBitrate:s,degradationPreference:n,isNeedReinvite:!1})):Promise.reject(new Error("Presentation has not started yet")):Promise.reject(new Error("No session established"))}))}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,n,i,r;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(n=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===n?void 0:n.uri.host,incomingNumber:null===(r=null===(i=null==this?void 0:this.incomingSession)||void 0===i?void 0:i.remote_identity)||void 0===r?void 0:r.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!(!this.ua||!this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,n=this._remoteStreams[s]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[s]=n,n}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,n)=>{if("audio"===s.kind)return;const i=s,r=e[n-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(i,o);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession($)}waitSyncMediaState(){return this.waitSession(ee)}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}sendMediaState({cam:e,mic:t},s={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const n=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},s),{extraHeaders:n}))}_sendRefusalToTurnOn(e,t={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const s=[`X-Vinteo-Media-Type: ${"mic"==e?0:1}`];return this.session.sendInfo("application/vinteo.webrtc.refusal",void 0,Object.assign(Object.assign({},t),{extraHeaders:s}))}sendRefusalToTurnOnMic(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",e)}sendRefusalToTurnOnCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",e)}},e.disableDebug=()=>{u.default.enable(`-${lt}`)},e.enableDebug=()=>{u.default.enable(`${lt}`)},e.eventNames=Te,e.getCodecFromSender=E,e.hasCanceledCallError=(e=new Error)=>{const{originator:s,cause:n}=e;return!!t.isCanceledError(e)||"string"==typeof n&&(n===f||n===v||s===Ve&&(n===N||n===R))},e.resolveVideoSendingBalancer=(e,{ignoreForCodec:t,onSetParameters:s}={})=>{const n=()=>{const{connection:n}=e;return n?dt({connection:n,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))};let i=n;const r=n=>{i=()=>{const{mainCam:i,resolutionMainCam:r}=n,{connection:o}=e;return o?dt({mainCam:i,resolutionMainCam:r,connection:o,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))},i()};return{subscribe:()=>{e.onSession("main-cam-control",r)},unsubscribe:()=>{e.offSession("main-cam-control",r)},balanceByTrack:n,resetMainCamControl(){i=n},reBalance:()=>i()}},e.tools=vt,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|