12345678910111213 |
- /*!
- - Name HS_CTI
- - FileName hs-cti
- - Version 1.0.9
- - JS Standard es6
- - Author platformfe
- - Built on 2024/11/27 10:37:38
- - GitHub
- - Branch main
- - CommitID 987d86cd91cde7d1c235ad106d79fc92c305b8ff
- - CommitMessage fix: 修改socket地址
- */
- import{Web as e,UserAgent as t,UserAgentState as i,Registerer as s,RegistererState as n,Inviter as o,Invitation as r,Session as a,Messager as l,RequestPendingError as c,SessionState as d}from"sip.js";import g from"socket.io-client";function h(e,t,i,s){var n,o=arguments.length,r=o<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(r=(o<3?n(r):o>3?n(t,i,r):n(t,i))||r);return o>3&&r&&Object.defineProperty(t,i,r),r}function u(e,t,i,s){return new(i||(i=Promise))((function(n,o){function r(e){try{l(s.next(e))}catch(e){o(e)}}function a(e){try{l(s.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class p{constructor(s,n={}){Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedSessions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optionsPingFailure",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"optionsPingRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optionsPingRunning",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"optionsPingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationAttemptTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registerer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registererOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registererRegisterOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldBeConnected",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"shouldBeRegistered",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"attemptingReconnection",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.delegate=n.delegate,this.options=Object.assign({aor:"",autoStop:!0,delegate:{},iceStopWaitingOnServerReflexive:!1,managedSessionFactory:this.managedSessionFactory,maxSimultaneousSessions:2,media:{},optionsPingInterval:-1,optionsPingRequestURI:"",reconnectionAttempts:3,reconnectionDelay:3,registrationRetry:!1,registrationRetryInterval:3,registerGuard:null,registererOptions:{},registererRegisterOptions:{},sendDTMFUsingSessionDescriptionHandler:!1,userAgentOptions:{}},p.stripUndefinedProperties(n));const o=Object.assign({},n.userAgentOptions);if(o.transportConstructor||(o.transportConstructor=e.Transport),o.transportOptions||(o.transportOptions={server:s}),!o.uri&&n.aor){const e=t.makeURI(n.aor);if(!e)throw new Error(`Failed to create valid URI from ${n.aor}`);o.uri=e}if(this.userAgent=new t(o),this.userAgent.delegate={onConnect:()=>{this.logger.log("Connected"),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.shouldBeRegistered&&this.register(),this.options.optionsPingInterval>0&&this.optionsPingStart()},onDisconnect:e=>u(this,void 0,void 0,(function*(){var t,i,s,n;this.logger.log("Disconnected");let o=!1;this.options.optionsPingInterval>0&&(o=this.optionsPingFailure,this.optionsPingFailure=!1,this.optionsPingStop()),e||o?(this.registerer&&(this.logger.log("Disposing of registerer..."),this.registerer.dispose().catch((e=>{this.logger.debug("Error occurred disposing of registerer after connection with server was lost."),this.logger.debug(e.toString())})),this.registerer=void 0),this.managedSessions.slice().map((e=>e.session)).forEach((e=>u(this,void 0,void 0,(function*(){this.logger.log("Disposing of session..."),e.dispose().catch((e=>{this.logger.debug("Error occurred disposing of a session after connection with server was lost."),this.logger.debug(e.toString())}))})))),this.shouldBeConnected&&(null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onReconnectStart)||void 0===i||i.call(t),this.attemptReconnection())):null===(n=null===(s=this.delegate)||void 0===s?void 0:s.onServerDisconnect)||void 0===n||n.call(s,e)})),onInvite:e=>{this.logger.log(`[${e.id}] Received INVITE`);const t=this.options.maxSimultaneousSessions;if(0!==t&&this.managedSessions.length>t)return this.logger.warn(`[${e.id}] Session already in progress, rejecting INVITE...`),void e.reject().then((()=>{this.logger.log(`[${e.id}] Rejected INVITE`)})).catch((t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())}));const i={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,i),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived(e):(this.logger.warn(`[${e.id}] No handler available, rejecting INVITE...`),e.reject().then((()=>{this.logger.log(`[${e.id}] Rejected INVITE`)})).catch((t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())})))},onMessage:e=>{e.accept().then((()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e)}))},onNotify:e=>{e.accept().then((()=>{this.delegate&&this.delegate.onNotificationReceived&&this.delegate.onNotificationReceived(e)}))}},this.registererOptions=Object.assign({},n.registererOptions),this.registererRegisterOptions=Object.assign({},n.registererRegisterOptions),this.options.registrationRetry){this.registererRegisterOptions.requestDelegate=this.registererRegisterOptions.requestDelegate||{};const e=this.registererRegisterOptions.requestDelegate.onReject;this.registererRegisterOptions.requestDelegate.onReject=t=>{e&&e(t),this.attemptRegistration()}}this.logger=this.userAgent.getLogger("sip.SessionManager"),window.addEventListener("online",(()=>{this.logger.log("Online"),this.shouldBeConnected&&this.connect()})),this.options.autoStop&&window.addEventListener("beforeunload",(()=>u(this,void 0,void 0,(function*(){this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.userAgent.state!==i.Stopped&&(yield this.userAgent.stop())}))))}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t)),{})}getLocalMediaStream(t){const i=t.sessionDescriptionHandler;if(i){if(!(i instanceof e.SessionDescriptionHandler))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return i.localMediaStream}}getRemoteMediaStream(t){const i=t.sessionDescriptionHandler;if(i){if(!(i instanceof e.SessionDescriptionHandler))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return i.remoteMediaStream}}getLocalAudioTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find((e=>"audio"===e.kind))}getLocalVideoTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find((e=>"video"===e.kind))}getRemoteAudioTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find((e=>"audio"===e.kind))}getRemoteVideoTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find((e=>"video"===e.kind))}connect(){return u(this,void 0,void 0,(function*(){return this.logger.log("Connecting UserAgent..."),this.shouldBeConnected=!0,this.userAgent.state!==i.Started?this.userAgent.start():this.userAgent.reconnect()}))}disconnect(){return u(this,void 0,void 0,(function*(){return this.logger.log("Disconnecting UserAgent..."),this.userAgent.state===i.Stopped?Promise.resolve():(this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.registerer=void 0,this.userAgent.stop())}))}isConnected(){return this.userAgent.isConnected()}register(e){return u(this,void 0,void 0,(function*(){return this.logger.log("Registering UserAgent..."),this.shouldBeRegistered=!0,void 0!==e&&(this.registererRegisterOptions=Object.assign({},e)),this.registerer||(this.registerer=new s(this.userAgent,this.registererOptions),this.registerer.stateChange.addListener((e=>{switch(e){case n.Initial:break;case n.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case n.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered(),this.shouldBeRegistered&&this.attemptRegistration();break;case n.Terminated:break;default:throw new Error("Unknown registerer state.")}}))),this.attemptRegistration(!0)}))}unregister(e){return u(this,void 0,void 0,(function*(){return this.logger.log("Unregistering UserAgent..."),this.shouldBeRegistered=!1,this.registerer?this.registerer.unregister(e).then((()=>{})):(this.logger.warn("No registerer to unregister."),Promise.resolve())}))}call(i,s,n){return u(this,void 0,void 0,(function*(){this.logger.log("Beginning Session...");const r=this.options.maxSimultaneousSessions;if(0!==r&&this.managedSessions.length>r)return Promise.reject(new Error("Maximum number of sessions already exists."));const a=t.makeURI(i);if(!a)return Promise.reject(new Error(`Failed to create a valid URI from "${i}"`));if(s||(s={}),s.sessionDescriptionHandlerOptions||(s.sessionDescriptionHandlerOptions={}),s.sessionDescriptionHandlerOptions.constraints||(s.sessionDescriptionHandlerOptions.constraints=this.constraints),s.earlyMedia){(n=n||{}).requestDelegate=n.requestDelegate||{};const e=n.requestDelegate.onProgress;n.requestDelegate.onProgress=t=>{183===t.message.statusCode&&this.setupRemoteMedia(l),e&&e(t)}}this.options.iceStopWaitingOnServerReflexive&&(s.delegate=s.delegate||{},s.delegate.onSessionDescriptionHandler=t=>{if(!(t instanceof e.SessionDescriptionHandler))throw new Error("Session description handler not instance of SessionDescriptionHandler");t.peerConnectionDelegate={onicecandidate:e=>{var i;if("srflx"===(null===(i=e.candidate)||void 0===i?void 0:i.type)){this.logger.log(`[${l.id}] Found srflx ICE candidate, stop waiting...`);t.iceGatheringComplete()}}}});const l=new o(this.userAgent,a,s);return this.sendInvite(l,s,n).then((()=>l))}))}hangup(e){return u(this,void 0,void 0,(function*(){return this.logger.log(`[${e.id}] Hangup...`),this.sessionExists(e)?this.terminate(e):Promise.reject(new Error("Session does not exist."))}))}answer(e,t){return u(this,void 0,void 0,(function*(){return this.logger.log(`[${e.id}] Accepting Invitation...`),this.sessionExists(e)?e instanceof r?(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),e.accept(t)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}))}decline(e){return u(this,void 0,void 0,(function*(){return this.logger.log(`[${e.id}] Rejecting Invitation...`),this.sessionExists(e)?e instanceof r?e.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}))}hold(e){return u(this,void 0,void 0,(function*(){return this.logger.log(`[${e.id}] Holding session...`),this.setHold(e,!0)}))}unhold(e){return u(this,void 0,void 0,(function*(){return this.logger.log(`[${e.id}] Unholding session...`),this.setHold(e,!1)}))}isHeld(e){const t=this.sessionManaged(e);return!!t&&t.held}mute(e){this.logger.log(`[${e.id}] Disabling media tracks...`),this.setMute(e,!0)}unmute(e){this.logger.log(`[${e.id}] Enabling media tracks...`),this.setMute(e,!1)}isMuted(e){const t=this.sessionManaged(e);return!!t&&t.muted}sendDTMF(e,t){return u(this,void 0,void 0,(function*(){if(this.logger.log(`[${e.id}] Sending DTMF...`),!/^[0-9A-D#*,]$/.exec(t))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.logger.log(`[${e.id}] Sending DTMF tone: ${t}`),this.options.sendDTMFUsingSessionDescriptionHandler)return e.sessionDescriptionHandler?e.sessionDescriptionHandler.sendDtmf(t)?Promise.resolve():Promise.reject(new Error("Failed to send DTMF")):Promise.reject(new Error("Session desciption handler undefined."));{const i={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+t+"\r\nDuration="+2e3}};return e.info({requestOptions:i}).then((()=>{}))}}))}transfer(e,i,s){return u(this,void 0,void 0,(function*(){if(this.logger.log(`[${e.id}] Referring session...`),i instanceof a)return e.refer(i,s).then((()=>{}));const n=t.makeURI(i);return n?e.refer(n,s).then((()=>{})):Promise.reject(new Error(`Failed to create a valid URI from "${i}"`))}))}message(e,i){return u(this,void 0,void 0,(function*(){this.logger.log("Sending message...");const s=t.makeURI(e);return s?new l(this.userAgent,s,i).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}))}get constraints(){let e={audio:!0,video:!1};return this.options.media.constraints&&(e=Object.assign({},this.options.media.constraints)),e}attemptReconnection(e=1){var t,i;const s=this.options.reconnectionAttempts,n=this.options.reconnectionDelay;if(this.shouldBeConnected){if(this.attemptingReconnection&&this.logger.log("Reconnection attempt already in progress"),e>s)return this.logger.log("Reconnection maximum attempts reached"),void(null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onReconnectFailed)||void 0===i||i.call(t));1===e?this.logger.log(`Reconnection attempt ${e} of ${s} - trying`):this.logger.log(`Reconnection attempt ${e} of ${s} - trying in ${n} seconds`),this.attemptingReconnection=!0,setTimeout((()=>{if(!this.shouldBeConnected)return this.logger.log(`Reconnection attempt ${e} of ${s} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then((()=>{this.logger.log(`Reconnection attempt ${e} of ${s} - succeeded`),this.attemptingReconnection=!1})).catch((t=>{this.logger.log(`Reconnection attempt ${e} of ${s} - failed`),this.logger.error(t.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)}))}),1===e?0:1e3*n)}else this.logger.log("Should not be connected currently")}attemptRegistration(e=!1){if(this.logger.log("Registration attempt "+(e?"without delay":"")),!this.shouldBeRegistered)return this.logger.log("Should not be registered currently"),Promise.resolve();if(void 0!==this.registrationAttemptTimeout)return this.logger.log("Registration attempt already in progress"),Promise.resolve();const t=()=>this.registerer?this.isConnected()?this.userAgent.state===i.Stopped?(this.logger.log("User agent stopped"),Promise.resolve()):this.options.registerGuard?this.options.registerGuard().catch((e=>{throw this.logger.log("Register guard rejected will making registration attempt"),e})).then((e=>e||!this.registerer?Promise.resolve():this.registerer.register(this.registererRegisterOptions).then((()=>{})))):this.registerer.register(this.registererRegisterOptions).then((()=>{})):(this.logger.log("User agent not connected"),Promise.resolve()):(this.logger.log("Registerer undefined"),Promise.resolve());return new Promise(((i,s)=>{this.registrationAttemptTimeout=setTimeout((()=>{t().then((()=>{this.registrationAttemptTimeout=void 0,i()})).catch((e=>{this.registrationAttemptTimeout=void 0,e instanceof c?i():s(e)}))}),e?0:(e=>{const t=2*e;return 1e3*(Math.random()*(t-e)+e)})(this.options.registrationRetryInterval))}))}cleanupMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");t.mediaLocal&&t.mediaLocal.video&&(t.mediaLocal.video.srcObject=null,t.mediaLocal.video.pause()),t.mediaRemote&&(t.mediaRemote.audio&&(t.mediaRemote.audio.srcObject=null,t.mediaRemote.audio.pause()),t.mediaRemote.video&&(t.mediaRemote.video.srcObject=null,t.mediaRemote.video.pause()))}enableReceiverTracks(t,i){if(!this.sessionExists(t))throw new Error("Session does not exist.");const s=t.sessionDescriptionHandler;if(!(s instanceof e.SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");s.enableReceiverTracks(i)}enableSenderTracks(t,i){if(!this.sessionExists(t))throw new Error("Session does not exist.");const s=t.sessionDescriptionHandler;if(!(s instanceof e.SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");s.enableSenderTracks(i)}initSession(e,t){this.sessionAdd(e),this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(e),e.stateChange.addListener((t=>{switch(this.logger.log(`[${e.id}] Session state changed to ${t}`),t){case d.Initial:case d.Establishing:break;case d.Established:this.setupLocalMedia(e),this.setupRemoteMedia(e),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered(e);break;case d.Terminating:case d.Terminated:this.sessionExists(e)&&(this.cleanupMedia(e),this.sessionRemove(e),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup(e));break;default:throw new Error("Unknown session state.")}})),e.delegate=e.delegate||{},e.delegate.onInfo=t=>{var i;if(void 0===(null===(i=this.delegate)||void 0===i?void 0:i.onCallDTMFReceived))return void t.reject();const s=t.request.getHeader("content-type");if(!s||!/^application\/dtmf-relay/i.exec(s))return void t.reject();const n=t.request.body.split("\r\n",2);if(2!==n.length)return void t.reject();let o;const r=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(void 0!==n[0]&&r.test(n[0])&&(o=n[0].replace(r,"$2")),!o)return void t.reject();let a;const l=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;void 0!==n[1]&&l.test(n[1])&&(a=parseInt(n[1].replace(l,"$2"),10)),a?t.accept().then((()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!o||!a)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(e,o,a)}})).catch((e=>{this.logger.error(e.message)})):t.reject()},e.delegate.onRefer=e=>{e.accept().then((()=>this.sendInvite(e.makeInviter(t),t))).catch((e=>{this.logger.error(e.message)}))}}optionsPingRun(e,t,i){if(this.options.optionsPingInterval<1)throw new Error("Invalid options ping interval.");this.optionsPingRunning||(this.optionsPingRunning=!0,this.optionsPingTimeout=setTimeout((()=>{this.optionsPingTimeout=void 0;const s=()=>{this.optionsPingFailure=!1,this.optionsPingRunning&&(this.optionsPingRunning=!1,this.optionsPingRun(e,t,i))},n=()=>{this.logger.error("OPTIONS ping failed"),this.optionsPingFailure=!0,this.optionsPingRunning=!1,this.userAgent.transport.disconnect().catch((e=>this.logger.error(e)))},o=this.userAgent.userAgentCore,r=o.makeOutgoingRequestMessage("OPTIONS",e,t,i,{});this.optionsPingRequest=o.request(r,{onAccept:()=>{this.optionsPingRequest=void 0,s()},onReject:e=>{this.optionsPingRequest=void 0,408===e.message.statusCode||503===e.message.statusCode?n():s()}})}),1e3*this.options.optionsPingInterval))}optionsPingStart(){let e,i,s;if(this.logger.log("OPTIONS pings started"),this.options.optionsPingRequestURI){if(e=t.makeURI(this.options.optionsPingRequestURI),!e)throw new Error("Failed to create Request URI.");i=this.userAgent.contact.uri.clone(),s=this.userAgent.contact.uri.clone()}else{if(!this.options.aor)return void this.logger.error("You have enabled sending OPTIONS pings and as such you must provide either a) an AOR to register, or b) an RURI to use for the target of the OPTIONS ping requests. ");{const n=t.makeURI(this.options.aor);if(!n)throw new Error("Failed to create URI.");e=n.clone(),e.user=void 0,i=n.clone(),s=n.clone()}}this.optionsPingRun(e,i,s)}optionsPingStop(){this.logger.log("OPTIONS pings stopped"),this.optionsPingRunning=!1,this.optionsPingFailure=!1,this.optionsPingRequest&&(this.optionsPingRequest.dispose(),this.optionsPingRequest=void 0),this.optionsPingTimeout&&(clearTimeout(this.optionsPingTimeout),this.optionsPingTimeout=void 0)}sendInvite(e,t,i){return u(this,void 0,void 0,(function*(){return this.initSession(e,t),e.invite(i).then((()=>{this.logger.log(`[${e.id}] Sent INVITE`)}))}))}managedSessionFactory(e,t){return{session:t,held:!1,muted:!1}}sessionAdd(e){const t=this.managedSessionFactory(this,e);this.managedSessions.push(t)}sessionExists(e){return void 0!==this.sessionManaged(e)}sessionManaged(e){return this.managedSessions.find((t=>t.session.id===e.id))}sessionRemove(e){this.managedSessions=this.managedSessions.filter((t=>t.session.id!==e.id))}setHold(t,i){return u(this,void 0,void 0,(function*(){if(!this.sessionExists(t))return Promise.reject(new Error("Session does not exist."));if(this.isHeld(t)===i)return Promise.resolve();if(!(t.sessionDescriptionHandler instanceof e.SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s={requestDelegate:{onAccept:()=>{const e=this.sessionManaged(t);void 0!==e&&(e.held=i,this.enableReceiverTracks(t,!e.held),this.enableSenderTracks(t,!e.held&&!e.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(t,e.held))},onReject:()=>{this.logger.warn(`[${t.id}] Re-invite request was rejected`);const e=this.sessionManaged(t);void 0!==e&&(e.held=!i,this.enableReceiverTracks(t,!e.held),this.enableSenderTracks(t,!e.held&&!e.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(t,e.held))}}},n=t.sessionDescriptionHandlerOptionsReInvite;n.hold=i,t.sessionDescriptionHandlerOptionsReInvite=n;const o=this.sessionManaged(t);if(!o)throw new Error("Managed session is undefiend.");return o.held=i,t.invite(s).then((()=>{const e=this.sessionManaged(t);void 0!==e&&(this.enableReceiverTracks(t,!e.held),this.enableSenderTracks(t,!e.held&&!e.muted))})).catch((e=>{throw o.held=!i,e instanceof c&&this.logger.error(`[${t.id}] A hold request is already in progress.`),e}))}))}setMute(e,t){if(!this.sessionExists(e))return void this.logger.warn(`[${e.id}] A session is required to enabled/disable media tracks`);if(e.state!==d.Established)return void this.logger.warn(`[${e.id}] An established session is required to enable/disable media tracks`);const i=this.sessionManaged(e);void 0!==i&&(i.muted=t,this.enableSenderTracks(e,!i.held&&!i.muted))}setupLocalMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const i="function"==typeof this.options.media.local?this.options.media.local(e):this.options.media.local;t.mediaLocal=i;const s=null==i?void 0:i.video;if(s){const t=this.getLocalMediaStream(e);if(!t)throw new Error("Local media stream undefiend.");s.srcObject=t,s.volume=0,s.play().catch((t=>{this.logger.error(`[${e.id}] Failed to play local media`),this.logger.error(t.message)}))}}setupRemoteMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const i="function"==typeof this.options.media.remote?this.options.media.remote(e):this.options.media.remote;t.mediaRemote=i;const s=(null==i?void 0:i.video)||(null==i?void 0:i.audio);if(s){const t=this.getRemoteMediaStream(e);if(!t)throw new Error("Remote media stream undefiend.");s.autoplay=!0,s.srcObject=t,s.play().catch((t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)})),t.onaddtrack=()=>{this.logger.log("Remote media onaddtrack"),s.load(),s.play().catch((t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)}))}}}terminate(e){return u(this,void 0,void 0,(function*(){switch(this.logger.log(`[${e.id}] Terminating...`),e.state){case d.Initial:if(e instanceof o)return e.cancel().then((()=>{this.logger.log(`[${e.id}] Inviter never sent INVITE (canceled)`)}));if(e instanceof r)return e.reject().then((()=>{this.logger.log(`[${e.id}] Invitation rejected (sent 480)`)}));throw new Error("Unknown session type.");case d.Establishing:if(e instanceof o)return e.cancel().then((()=>{this.logger.log(`[${e.id}] Inviter canceled (sent CANCEL)`)}));if(e instanceof r)return e.reject().then((()=>{this.logger.log(`[${e.id}] Invitation rejected (sent 480)`)}));throw new Error("Unknown session type.");case d.Established:return e.bye().then((()=>{this.logger.log(`[${e.id}] Session ended (sent BYE)`)}));case d.Terminating:case d.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${e.id}] Terminating in state ${e.state}, no action taken`),Promise.resolve()}))}}class m{constructor(e,t={}){Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=t.delegate,this.options=Object.assign({},t);const i={aor:this.options.aor,delegate:{onCallAnswered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallAnswered)||void 0===t?void 0:t.call(e)},onCallCreated:e=>{var t,i,s,n;this.session=e,null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onCallBegin)||void 0===i||i.call(t,e),null===(n=null===(s=this.delegate)||void 0===s?void 0:s.onCallCreated)||void 0===n||n.call(s)},onCallReceived:e=>{var t,i,s,n;null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onCallReceived)||void 0===i||i.call(t),null===(n=null===(s=this.delegate)||void 0===s?void 0:s.onInvite)||void 0===n||n.call(s,e)},onCallHangup:()=>{var e,t;this.session=void 0,(null===(e=this.delegate)||void 0===e?void 0:e.onCallHangup)&&(null===(t=this.delegate)||void 0===t||t.onCallHangup())},onCallHold:(e,t)=>{var i,s;return null===(s=null===(i=this.delegate)||void 0===i?void 0:i.onCallHold)||void 0===s?void 0:s.call(i,t)},onCallDTMFReceived:(e,t,i)=>{var s,n;return null===(n=null===(s=this.delegate)||void 0===s?void 0:s.onCallDTMFReceived)||void 0===n?void 0:n.call(s,t,i)},onMessageReceived:e=>{var t,i;return null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onMessageReceived)||void 0===i?void 0:i.call(t,e.request.body)},onRegistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onRegistered)||void 0===t?void 0:t.call(e)},onUnregistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onUnregistered)||void 0===t?void 0:t.call(e)},onServerConnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerConnect)||void 0===t?void 0:t.call(e)},onServerDisconnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerDisconnect)||void 0===t?void 0:t.call(e)},onReconnectFailed:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onReconnectFailed)||void 0===t?void 0:t.call(e)},onReconnectStart:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onReconnectStart)||void 0===t?void 0:t.call(e)}},maxSimultaneousSessions:1,media:this.options.media,optionsPingInterval:this.options.optionsPingInterval,optionsPingRequestURI:this.options.aor,reconnectionAttempts:this.options.reconnectionAttempts,reconnectionDelay:this.options.reconnectionDelay,registererOptions:this.options.registererOptions,sendDTMFUsingSessionDescriptionHandler:this.options.sendDTMFUsingSessionDescriptionHandler,userAgentOptions:this.options.userAgentOptions};this.sessionManager=new p(e,i),this.sessionManager.userAgent.stateChange.addListener((e=>{var t,i;null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onUserAgentStateChange)||void 0===i||i.call(t,e)})),this.logger=this.sessionManager.userAgent.getLogger("sip.SimpleUser")}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){return this.session&&this.sessionManager.getLocalMediaStream(this.session)}get remoteMediaStream(){return this.session&&this.sessionManager.getRemoteMediaStream(this.session)}get localAudioTrack(){return this.session&&this.sessionManager.getLocalAudioTrack(this.session)}get localVideoTrack(){return this.session&&this.sessionManager.getLocalVideoTrack(this.session)}get remoteAudioTrack(){return this.session&&this.sessionManager.getRemoteAudioTrack(this.session)}get remoteVideoTrack(){return this.session&&this.sessionManager.getRemoteVideoTrack(this.session)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.sessionManager.connect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.sessionManager.disconnect()}isConnected(){return this.sessionManager.isConnected()}register(e){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.sessionManager.register(e)}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.sessionManager.unregister(e)}call(e,t,i){return this.logger.log(`[${this.id}] Beginning Session...`),this.session?Promise.reject(new Error("Session already exists.")):this.sessionManager.call(e,t,i).then((()=>{}))}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.session?this.sessionManager.hangup(this.session).then((()=>{this.session=void 0})):Promise.reject(new Error("Session does not exist."))}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.sessionManager.answer(this.session,e):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.sessionManager.decline(this.session):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.session?this.sessionManager.hold(this.session):Promise.reject(new Error("Session does not exist."))}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.session?this.sessionManager.unhold(this.session):Promise.reject(new Error("Session does not exist."))}isHeld(){return!!this.session&&this.sessionManager.isHeld(this.session)}mute(){return this.logger.log(`[${this.id}] disabling media tracks...`),this.session&&this.sessionManager.mute(this.session)}unmute(){return this.logger.log(`[${this.id}] enabling media tracks...`),this.session&&this.sessionManager.unmute(this.session)}isMuted(){return!!this.session&&this.sessionManager.isMuted(this.session)}sendDTMF(e){return this.logger.log(`[${this.id}] sending DTMF...`),this.session?this.sessionManager.sendDTMF(this.session,e):Promise.reject(new Error("Session does not exist."))}message(e,t){return this.logger.log(`[${this.id}] sending message...`),this.sessionManager.message(e,t)}}let v=Object.prototype.hasOwnProperty,f="~";function S(){}function b(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function w(e,t,i,s,n){if("function"!=typeof i)throw new TypeError("The listener must be a function");const o=new b(i,s||e,n),r=f?f+t:t;return e._events[r]?e._events[r].fn?e._events[r]=[e._events[r],o]:e._events[r].push(o):(e._events[r]=o,e._eventsCount++),e}function y(e,t){0==--e._eventsCount?e._events=new S:delete e._events[t]}function k(){this._events=new S,this._eventsCount=0}Object.create&&(S.prototype=Object.create(null),(new S).__proto__||(f=!1)),k.prototype.eventNames=function(){let e,t,i=[];if(0===this._eventsCount)return i;for(t in e=this._events)v.call(e,t)&&i.push(f?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},k.prototype.listeners=function(e){const t=f?f+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,o=new Array(n);s<n;s++)o[s]=i[s].fn;return o},k.prototype.listenerCount=function(e){const t=f?f+e:e,i=this._events[t];return i?i.fn?1:i.length:0},k.prototype.emit=function(e,t,i,s,n,o){const r=f?f+e:e;if(!this._events[r])return!1;let a,l,c=this._events[r],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,s),!0;case 5:return c.fn.call(c.context,t,i,s,n),!0;case 6:return c.fn.call(c.context,t,i,s,n,o),!0}for(l=1,a=new Array(d-1);l<d;l++)a[l-1]=arguments[l];c.fn.apply(c.context,a)}else{let n,o=c.length;for(l=0;l<o;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,i);break;case 4:c[l].fn.call(c[l].context,t,i,s);break;default:if(!a)for(n=1,a=new Array(d-1);n<d;n++)a[n-1]=arguments[n];c[l].fn.apply(c[l].context,a)}}return!0},k.prototype.on=function(e,t,i){return w(this,e,t,i,!1)},k.prototype.once=function(e,t,i){return w(this,e,t,i,!0)},k.prototype.removeListener=function(e,t,i,s){const n=f?f+e:e;if(!this._events[n])return this;if(!t)return y(this,n),this;const o=this._events[n];if(o.fn)o.fn!==t||s&&!o.once||i&&o.context!==i||y(this,n);else{for(var r=0,a=[],l=o.length;r<l;r++)(o[r].fn!==t||s&&!o[r].once||i&&o[r].context!==i)&&a.push(o[r]);a.length?this._events[n]=1===a.length?a[0]:a:y(this,n)}return this},k.prototype.removeAllListeners=function(e){let t;return e?(t=f?f+e:e,this._events[t]&&y(this,t)):(this._events=new S,this._eventsCount=0),this},k.prototype.off=k.prototype.removeListener,k.prototype.addListener=k.prototype.on,k.prefixed=f,k.EventEmitter=k,"undefined"!=typeof module&&(module.exports=k);const O=()=>{const e=Date.now(),t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}.${String(t.getMilliseconds()).padStart(3,"0")}`};var _,R,T,P,I,A,C,E,M,j,D,$,L;!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(_||(_={}));class x{constructor(e,t,i){Object.defineProperty(this,"_level",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"label",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._level=e,this.category=t,this.label=i}error(e){this.genericLog(_.error,e)}warn(e){this.genericLog(_.warn,e)}log(e){this.genericLog(_.log,e)}debug(e){this.genericLog(_.debug,e)}genericLog(e,t){this._level>=e&&this.print(e,this.category,this.label,t)}print(e,t,i,s){if("string"==typeof s){const e=[O()];i&&e.push(i),s=e.concat(s).join(" | ")}switch(e){case _.error:console.error(`%c${t}`,"color: blue;",s);break;case _.warn:console.warn(`%c${t}`,"color: blue;",s);break;case _.log:console.log(`%c${t}`,"color: blue;",s);break;case _.debug:console.debug(`%c${t}`,"color: blue;",s)}}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:_.hasOwnProperty(e)?this._level=e:this.error("invalid 'level' parameter value: "+JSON.stringify(e))}}!function(e){e.Manual="manual",e.Robot="robot",e.Monitor="monitor",e.Predictive="predictive",e.Wechat="wechat"}(R||(R={})),function(e){e.All="all",e.Manual="manual",e.Robot="robot",e.Predictive="predictive"}(T||(T={})),function(e){e.Initial="Initial",e.Connecting="Connecting",e.Connected="Connected",e.Ready="Ready",e.ReTry="ReTry",e.Terminated="Terminated"}(P||(P={})),function(e){e.Initial="Initial",e.Started="Started",e.Connecting="Connecting",e.Connected="Connected",e.Ready="Ready",e.ReTry="ReTry",e.Terminated="Terminated"}(I||(I={})),function(e){e.Initial="Initial",e.Ready="Ready",e.ReTry="ReTry",e.Terminated="Terminated"}(A||(A={})),function(e){e.Started="Started",e.Stopped="Stopped"}(C||(C={})),function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(E||(E={})),function(e){e.SdkTerminated="SdkTerminated",e.SdkError="SdkError",e.ServerTerminated="ServerTerminated",e.ServerError="ServerError"}(M||(M={})),function(e){e.CTITerminated="100001",e.GetUserMedia="100002",e.GetInitConfig="100003",e.SocketOnError="110001",e.SocketOnConnectError="110002",e.SocketOnDisconnect="110003",e.SocketRepeatLogin="110004",e.SocketOnReconnectFailed="110007",e.SIPInitUserAgent="120001",e.SIPInitRegister="120002",e.SIPUserAgentStateStopped="120003",e.SIPTransportStateDisconnected="120004",e.SIPRegistererStateTerminated="120005",e.SIPOnDisconnect="120006",e.SIPInitTransport="120007",e.SipHeartBeatErr="120008",e.SIPUnRegistered="120009"}(j||(j={})),function(e){e.Answer="200001",e.Bye="200002",e.InvitationCancel="200003",e.AssignStream="200004",e.FetchError="200005"}(D||(D={})),function(e){e.OnCtiError="OnCtiError",e.OnSessionStatusChange="OnSessionStatusChange",e.OnInitalSuccess="OnInitalSuccess",e.OnAgentWorkReport="OnAgentWorkReport",e.OnRingStart="OnRingStart",e.OnRingEnd="OnRingEnd",e.OnDetectedTone="OnDetectedTone",e.OnAgentReport="OnAgentReport",e.OnCallReportInfo="OnCallReportInfo",e.OnCallRing="OnCallRing",e.OnCallEnd="OnCallEnd",e.OnCallAnswer="OnCallAnswer",e.OnAgentGroupQuery="OnAgentGroupQuery",e.OnMethodResponseEvent="OnMethodResponseEvent",e.OnEventPrompt="OnEventPrompt",e.OnPrompt="OnPrompt"}($||($={})),function(e){e.TrackParams="trackParams",e.ENV="env",e.LoggerLevel="loggerLevel"}(L||(L={}));const H=[[L.TrackParams,{}],[L.ENV,"test"],[L.LoggerLevel,_.debug]],U=new Map,F=()=>{H.forEach(((e,t)=>U.set(e,t)))};F();const N=(e,t,i=!1)=>{i||"object"!=typeof t?U.set(e,t):U.set(e,Object.assign(Object.assign({},U.get(e)),t))},B=()=>(window.HS_CTI_CLIENT_ID||(window.HS_CTI_CLIENT_ID="xxxxxxxxxxxx4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})).replace(/-/g,"")),window.HS_CTI_CLIENT_ID);var q,J,W,V;!function(e){e.RingAudio="_ringAudio",e.WaitAudio="_waitAudio",e.ByeAudio="_byeAudio"}(q||(q={})),function(e){e.FeSocket="fe-socket",e.FeSIP="fe-sip",e.FeMethod="fe-method",e.FeAPI="fe-api",e.FeAPIError="fe-api-error",e.FeIMDown="fe-im-down",e.FeIMCmd="fe-im-cmd",e.FeMedia="fe-media",e.FeStatus="fe-status",e.FeEmit="fe-emit"}(J||(J={})),function(e){e.SetSocketStatus="SetSocketStatus",e.SocketDownEvent="SocketDownEvent"}(W||(W={})),function(e){e.CommonNetworkErrorMsg="对不起,网络状况暂时不佳,请刷新后重试。",e.CustomNetworkErrorMsg="对不起,连接失败,请刷新后重试。如果问题持续出现,请联系我们的技术人员。感谢您的理解和支持。",e.ManualCallAnswerErrorMsg="当前电话未接通,通话已结束,请重试。",e.RobotOrWeChatAnswerErrorMsg="对不起,由于用户挂机等原因,当前电话未接通,请等待下一通电话。",e.SipByeErrorMsg="请稍等,正在挂断。",e.CTIRepeatLoginMsg="当前坐席已被其他终端替代。"}(V||(V={}));const G={checkIn:V.CommonNetworkErrorMsg,checkOut:V.CommonNetworkErrorMsg,setIdle:V.CustomNetworkErrorMsg,setBusy:V.CommonNetworkErrorMsg,makeCall:V.CommonNetworkErrorMsg,answer:V.CommonNetworkErrorMsg,bye:V.CommonNetworkErrorMsg,loadAgentGroupData:V.CommonNetworkErrorMsg,listen:V.CommonNetworkErrorMsg,setActiveService:V.CustomNetworkErrorMsg},Y=["agent_id","saas_id","env","scene"],Q=[...Y,"monitorScene"];class X extends k{constructor(e){super(),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"socketOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"heartBeatDelay",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closeHeartBeatDelay",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"heartBeatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closeHeartBeatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"imRetryCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),window.addEventListener("onunload",this.closeSocket),this.logger=new x(e.loggerLevel,"HsSocket"),this.socket=void 0,this.heartBeatTimer=null,this.closeHeartBeatTimer=null,this.sessionId="",this.socketOptions=e,this.heartBeatDelay=1e3*e.imHeartTime||3e3,this.closeHeartBeatDelay=1e3*e.imHeartTime||3e3,this.imRetryCount=e.imRetryCount||10}initSocket(){this.closeSocket(),this.emit(W.SetSocketStatus,{status:P.Connecting}),this.socket=g(this.socketOptions.imWsServer,{transports:["websocket"],reconnectionAttempts:this.imRetryCount,reconnectionDelay:this.heartBeatDelay,reconnectionDelayMax:this.heartBeatDelay+1e3,timeout:this.heartBeatDelay,reconnection:!0}),this.socket.on("error",(e=>{this.logger.error(`socket_error | ${JSON.stringify(e)}`)})),this.socket.on("connect_error",(e=>{const t=`socket_connect_error | ${JSON.stringify(e)}`;this.logger.warn(t)})),this.socket.on("reconnecting",(e=>{this.logger.error(`socket_warn | socket_reconnecting | ${e}`),this.emit(W.SetSocketStatus,{status:P.ReTry})})),this.socket.on("reconnect",(e=>{this.logger.error(`socket_warn | socket_reconnect | ${e}`),this.emit(W.SetSocketStatus,{status:P.Ready})})),this.socket.on("reconnect_failed",(e=>{this.logger.error(`socket_warn | socket_reconnect_failed | ${e}`),this.emit(W.SetSocketStatus,{status:P.Terminated,code:j.SocketOnReconnectFailed,error:`${e}`})})),this.socket.on("connect",(()=>{this.emit(W.SetSocketStatus,{status:P.Connected}),this.socketLogin()})),this.socket.on("disconnect",(e=>{const t=`socket_disconnect | ${e}`;this.logger.warn(t)})),this.socket.on("common_down_data",(e=>{console.log(e,3434343434),e&&JSON.parse(e)&&JSON.parse(e).data&&this.emit(W.SocketDownEvent,{eventData:JSON.parse(JSON.parse(e).data)})})),this.socket.on("common_down_cmd",(e=>{const{clientSessionId:t}=JSON.parse(e);console.log("dsdsdsdsdsds",t),t===this.sessionId&&(this.logger.error(`socket status | ${P.Terminated} | 坐席在其他页面重新初始化,本页面被踢出`),this.emit(W.SetSocketStatus,{status:P.Terminated,code:j.SocketRepeatLogin,error:"您已在其他页面签入,当前页面连接已断开"}))}))}socketLogin(){const e={userId:this.socketOptions.agent_id};this.socket&&this.socket.emit("login",e,(e=>{console.log(e,"测试一下"),this.emit(W.SetSocketStatus,{status:P.Ready}),N(L.TrackParams,{socket_session_id:e}),this.sessionId=e,this.startHeartbeat()}))}closeSocket(){this.socket&&(this.socket.io.opts.reconnection=!1,this.socket.close(),this.socket.removeAllListeners()),this.socket=void 0,this.sessionId="",this.heartBeatTimer&&(window.clearTimeout(this.heartBeatTimer),this.heartBeatTimer=null),this.closeHeartBeatTimer&&(window.clearTimeout(this.closeHeartBeatTimer),this.closeHeartBeatTimer=null)}startHeartbeat(){this.heartBeatTimer&&(window.clearTimeout(this.heartBeatTimer),this.heartBeatTimer=null),this.closeHeartBeatTimer&&(window.clearTimeout(this.closeHeartBeatTimer),this.closeHeartBeatTimer=null),this.socket&&this.heartbeatEvent()}heartbeatEvent(){this.heartBeatTimer=setTimeout((()=>{this.socket&&this.sendHeartbeat(),this.closeHeartBeatTimer=setTimeout((()=>{this.logger.warn("socket_heart_beat | 心跳超时,即将重新连接"),this.initSocket()}),this.closeHeartBeatDelay)}),this.heartBeatDelay)}sendHeartbeat(){this.socket&&this.socket.emit("heartbeat",JSON.stringify(Object.assign({},this.socketOptions)),(()=>{this.startHeartbeat()}))}}const z=new x(window.ctiLoggerLevel||(Z=L.LoggerLevel,U.get(Z)),"HsApi");var Z;const K=()=>(65536|65536*Math.random()).toString(16).substr(1);function ee({baseUrl:e,url:t,data:i}){return u(this,void 0,void 0,(function*(){const s=K()+K()+K()+K(),n=yield fetch(e+t,{method:"POST",headers:{"Content-Type":"application/json","X-B3-TraceId":s,"X-B3-SpanId":s},body:JSON.stringify(i)});return n.ok||z.error(`api response | ${t} | Request failed with status ${n.status}`),n.json()}))}const te=({baseUrl:e,url:t="",data:i})=>new Promise(((s,n)=>u(void 0,void 0,void 0,(function*(){try{const n=yield ee({baseUrl:e,url:t,data:i}),{code:o,msg:r}=n;console.log(r),0===o?z.log(`api response | ${t} | ${JSON.stringify(n)}`):z.error(`api response | ${t} | ${JSON.stringify(n)}`),s(n)}catch(e){z.error(`api response | ${t} | ${JSON.stringify(e)}`),n(e)}})))),ie="http://192.168.100.159:8090";function se(e){return function(t,i,s){const n=s.value;return s.value=function(...t){if(this.logger.log(`sdk method | ${i} | ${e}`),this.getCTIStatus!==A.Ready){const e={type:M.SdkTerminated,code:j.CTITerminated,msg:G[i],method:i,terminated_source:this._terminatedStatusList};return this.eventEmitAndTrack($.OnCtiError,e),Promise.reject(e)}return n.apply(this,t)},s}}function ne(){return function(e,t,i){const s=i.value;return i.value=function(...e){return u(this,void 0,void 0,(function*(){try{const i=yield s.apply(this,e),{code:n,msg:o}=i;if(0!==n){const e=function(e){return e>=300001&&e<=399999?M.ServerTerminated:M.ServerError}(n),i={type:e,code:n,msg:o,method:t};return this.eventEmitAndTrack($.OnCtiError,i),e===M.ServerTerminated&&this.setCTIStatus(A.Terminated),Promise.reject(i)}return Promise.resolve(i)}catch(e){const i={type:"fetch_error",code:D.FetchError,msg:JSON.stringify(e),method:t};return this.eventEmitAndTrack($.OnCtiError,i),Promise.reject(i)}}))},i}}const oe={_ringAudio:"http://static.fuxicarbon.com/hs-cti/ring.wav",_waitAudio:"http://static.fuxicarbon.com/hs-cti/manual.wav",_byeAudio:"http://static.fuxicarbon.com/hs-cti/bye.wav"};class re extends k{constructor(e){const{saas_id:t,agent_id:i,scene:s,env:n,loggerLevel:o}=e;super(),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"scene",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"agent_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"saas_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_initOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sipUserAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_callId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctiFlowIdList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_baseParams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_waitAudio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ringAudio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_byeAudio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_remoteAudio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctiStatus",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctiStatusList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sipStatus",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sipStatusList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_socketStatus",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_socketStatusList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_callStatus",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_terminatedStatusList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.loggerLevel=window.ctiLoggerLevel||o||_.log,this.logger=new x(this.loggerLevel,"HsCTI"),this._waitAudio=new Audio,this._ringAudio=new Audio,this._byeAudio=new Audio,this._remoteAudio=new Audio,this.saas_id=t,this.agent_id=i,this.scene=s,this._callId="",N(L.ENV,n),N(L.LoggerLevel,this.loggerLevel),this._baseParams={agent_id:i,saas_id:t,scene:s};const r={agent_id:i,vcc_id:t,scene:s};if(s===R.Monitor){const{monitorScene:t}=e;this._baseParams=Object.assign(Object.assign({},this._baseParams),{monitorScene:t}),N(L.TrackParams,Object.assign(Object.assign({},r),{monitor_scene:t}),!0)}else N(L.TrackParams,r,!0);this.initInstanceOptions(),this.setCTIStatus(A.Initial),this._callStatus=C.Stopped,this._terminatedStatusList=[]}get getCTIStatus(){return this._ctiStatus}get getSocketStatus(){return this._socketStatus}get getSIPStatus(){return this._sipStatus}static getInstance(e){return re.instance||(re.instance=new re(e)),N(L.TrackParams,{clientId:B()}),re.instance}initInstanceOptions(){this._ctiFlowIdList=[],this._ctiStatusList=[],this._sipStatusList=[],this._socketStatusList=[],re.instance=void 0,this._initOptions=void 0,F()}clearSocketAndSip(){var e,t,i;null===(e=this._socket)||void 0===e||e.closeSocket(),null===(t=this._sipUserAgent)||void 0===t||t.unregister(),null===(i=this._sipUserAgent)||void 0===i||i.disconnect(),this._sipUserAgent=void 0}setAudioSrc(e,t){this.logger.debug(`media | 设置等待音 src: ${oe[e]}`),this[e].src=oe[e],this[e].currentTime=0,this[e].autoplay=!1,this[e].loop=t}playAudio(e){this.logger.debug(`media | 播放音频:${e}`),this[e].play()}stopLocalAudio(){switch(this.scene){case R.Robot:case R.Monitor:this.stopAudio(q.RingAudio,!0);break;case R.Manual:this.stopAudio(q.WaitAudio,!0)}}stopAudio(e,t){this.logger.debug(`media | 停止音频播放:${e}`),this[e].src="",setTimeout((()=>{this.setAudioSrc(e,t)}),1e3)}init(){const[e]=this._ctiStatusList.slice(-1);if(e===A.Initial){switch(this.setAudioSrc(q.ByeAudio,!1),this.scene){case R.Robot:case R.Monitor:this.setAudioSrc(q.RingAudio,!0);break;case R.Manual:this.setAudioSrc(q.WaitAudio,!0)}this.getInitConfig()}}getInitConfig(){return u(this,void 0,void 0,(function*(){const e=yield(e=>te({baseUrl:ie,url:"/open/agent/get-init-config",data:e}))(this._baseParams),{code:t,data:i,msg:s}=e;let n=i;n=Object.assign(Object.assign({},n),{imHeartTime:3,imRetryCount:3,fsHeartTime:60,fsRetryCount:3,fsRetryTime:60,fsRegisterExpireTime:84e3,ctiSessionId:"id-"+Date.now()+"-"+Math.floor(1e4*Math.random()),imWsServer:"ws://192.168.100.159:8091/ws/cs-im",imWsPath:"ws/cs-im"}),0===t&&n?(N(L.TrackParams,{sip_server:n.sipServer,cti_session_id:n.ctiSessionId}),this._initOptions=n,this.initSocket(n),this.initSip(n)):this.eventEmitAndTrack($.OnCtiError,{type:M.ServerTerminated,code:j.GetInitConfig,msg:0!==t||n?s:"未查到坐席",method:"getInitConfig",res_code:t})}))}initSocket(e){this.setSocketStatus({status:P.Initial}),this._socket=new X({agent_id:this.agent_id,saas_id:this.saas_id,imWsServer:e.imWsServer,imWsPath:e.imWsPath,imHeartTime:e.imHeartTime,imRetryCount:e.imRetryCount,ctiSessionId:e.ctiSessionId,loggerLevel:this.loggerLevel}),this._socket.on(W.SocketDownEvent,(({eventData:e})=>{const{eventName:t,ext:i}=e;this.logger.log(`socket server down | ${t} | ${JSON.stringify(i)}`),this.handleSocketDownEvent({eventName:t,ext:i})})),this._socket.on(W.SetSocketStatus,(e=>{console.log(`set socket statussdsdsdsdsdsdds | ${JSON.stringify(e)}`),this.setSocketStatus(e)})),this._socket.initSocket()}handleSocketDownEvent({eventName:e,ext:t}){const i=this._baseParams.ctiFlowId,s=t.ctiFlowId;[R.Manual,R.Monitor].includes(this.scene)&&i&&s&&i!==s?this.logger.error(`cti_flow_id | 不一致! fe: ${i}, server: ${s}, eventName: ${e}`):this.serverEventEmit({eventName:e,ext:t})}serverEventEmit({eventName:e,ext:t}){const i=[$.OnRingStart,$.OnDetectedTone,$.OnRingEnd];switch(e){case $.OnRingStart:case $.OnDetectedTone:this.stopLocalAudio();break;case $.OnAgentWorkReport:break;case $.OnCallEnd:this._callStatus=C.Stopped,N(L.TrackParams,{call_id:""});case $.OnRingEnd:}i.includes(e)||this.eventEmitAndTrack(e,t)}initSip(e){this.setSipStatus({status:I.Initial});const t=e.wss_server,i={aor:e.sip_server,reconnectionAttempts:e.fsRetryCount,reconnectionDelay:e.fsRetryTime,optionsPingInterval:e.fsHeartTime,media:{remote:{audio:this._remoteAudio}},userAgentOptions:{gracefulShutdown:!0,authorizationPassword:e.phone_pwd,sessionDescriptionHandlerFactoryOptions:{constraints:{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1},peerConnectionConfiguration:{iceServers:[{urls:e.ice_server}]}}}};i.delegate=this.sipDelegate(),this._sipUserAgent=new m(t,i),this._sipUserAgent.connect().catch((e=>{const t=`SIP UserAgent 启动失败:${JSON.stringify(e)}`;this.logger.error(t),this.setSipStatus({status:I.Terminated,code:j.SIPInitUserAgent,error:t,method:"initSIPJS"})}))}sipDelegate(){return{onServerConnect:()=>{this._sipUserAgent.register()},onServerDisconnect:()=>{this.setSipStatus({status:I.Terminated})},onReconnectStart:()=>{this.setSipStatus({status:I.ReTry})},onReconnectFailed:()=>{this.setSipStatus({status:I.Terminated,code:j.SIPOnDisconnect,error:"超过重连次数,终止重连",method:"onReconnectFailed"}),this.setSipStatus({status:I.Terminated})},onRegistered:()=>{this.setSipStatus({status:I.Ready})},onUserAgentStateChange:e=>{switch(e){case i.Started:this.setSipStatus({status:I.Started});break;case i.Stopped:this.setSipStatus({status:I.Terminated,code:this._sipStatusList.includes(I.Started)?j.SIPUserAgentStateStopped:j.SIPInitUserAgent,error:"SIP UserAgentState 状态停止",method:"onUserAgentStateChange"})}},onInvite:e=>{const t=e.request.getHeader("P-LIBRA-CallId")||"";console.log(t,2888888888),this._callId=t,console.log(t,1888888888),N(L.TrackParams,{call_id:t}),this.sessionStateChangeAndTrack(e.state),[R.Robot,R.Monitor].includes(this.scene)&&(this.playAudio(q.RingAudio),console.log("playAudio",1888888888)),[R.Manual].includes(this.scene)&&(this.answer(),console.log("answer",1888888888)),e.delegate={onCancel:e=>{const t=`sip_invitation_on_cancel | ${JSON.stringify(e)}`;this.logger.error(t),this.eventEmitAndTrack($.OnCtiError,{type:M.SdkError,code:D.InvitationCancel,msg:"当前通话已结束",method:"sipDelegate"},t)}},e.stateChange.addListener((e=>{switch(this.sessionStateChangeAndTrack(e),e){case d.Initial:case d.Establishing:break;case d.Established:[R.Robot,R.Monitor].includes(this.scene)&&this.stopLocalAudio();break;case d.Terminating:break;case d.Terminated:this.playAudio(q.ByeAudio),setTimeout((()=>{this.stopAudio(q.ByeAudio,!1)}),1e3),this.stopLocalAudio(),this._callStatus=C.Stopped,N(L.TrackParams,{call_id:""})}}))}}}sessionStateChangeAndTrack(e){this.eventEmitAndTrack($.OnSessionStatusChange,{status:e});const t=`sip_session_state_${i=e,(i=(i=(i=(i=i.replace(/\s/g,"")).replace(/([A-Z])/g,"_$1")).toLowerCase()).replace(/^_/,"")).replace(/_$/,"")}`;var i;this.logger.log(t)}setCTIStatus(e){if(e===this.getCTIStatus)return;this._ctiStatus=e,this._ctiStatusList.push(e);const t=`cti status | ${e} | ${this._ctiStatusList}`;e===A.Terminated?(this.setSocketStatus({status:P.Terminated}),this.setSipStatus({status:I.Terminated}),this.stopLocalAudio(),this.logger.warn(t)):this.logger.debug(t),e===A.Ready&&(this.setSocketStatus({status:P.Ready}),this.setSipStatus({status:I.Ready}),this._terminatedStatusList=[],this._ctiStatusList.includes(A.ReTry)||this.checkIn())}setSocketStatus({status:e,code:t,error:i}){if(e===this.getSocketStatus)return;this._socketStatus=e,this._socketStatusList.push(e);const s=`socket status | ${e} | ${this._socketStatusList}`;e===P.Terminated?this.logger.warn(s):this.logger.debug(s),this.socketOrSipStatusChange(e,this.getSIPStatus),i&&(this._terminatedStatusList.push(t),this.eventEmitAndTrack($.OnCtiError,{type:M.SdkTerminated,code:t,msg:t===j.SocketRepeatLogin?V.CTIRepeatLoginMsg:V.CommonNetworkErrorMsg,method:"setSocketStatus"},{error_msg:i,socket_status_list:this._socketStatusList,sip_status_list:this._sipStatusList,cti_status_list:this._ctiStatusList}),this.clearSocketAndSip())}setSipStatus({status:e,code:t,error:i,method:s}){if(e===this.getSIPStatus)return;this._sipStatus=e,this._sipStatusList.push(e);const n=`sip status | ${e} | ${this._sipStatusList}`;e===I.Terminated?this.logger.warn(n):this.logger.debug(n),this.socketOrSipStatusChange(this.getSocketStatus,e),i&&(this._terminatedStatusList.push(t),this.eventEmitAndTrack($.OnCtiError,{type:M.SdkTerminated,code:t,msg:V.CommonNetworkErrorMsg,method:s||"setSipStatus"},{error_msg:i,socket_status_list:this._socketStatusList,sip_status_list:this._sipStatusList,cti_status_list:this._ctiStatusList}),this.clearSocketAndSip())}socketOrSipStatusChange(e,t){e===P.Ready&&t===I.Ready&&this.setCTIStatus(A.Ready),e!==P.ReTry&&t!==I.ReTry||this.setCTIStatus(A.ReTry),e!==P.Terminated&&t!==I.Terminated||this.setCTIStatus(A.Terminated)}eventEmitAndTrack(e,t,i){this.logger.debug(`sdk emit | ${e} | ${JSON.stringify(t)}`),e===$.OnCtiError&&(this._callStatus=C.Stopped);try{this.emit(e,t),console.log(i)}catch(i){this.logger.error(`业务监听 ${e} 事件,处理回调时报错: ${i}`)}}checkIn(){return u(this,void 0,void 0,(function*(){const e=yield(t=this._baseParams,te({baseUrl:ie,url:"/open/agent/check-in",data:t}));var t;return 0===e.code&&this.eventEmitAndTrack($.OnInitalSuccess,{saas_id:this.saas_id,agent_id:this.agent_id,scene:this.scene,phoneNum:this._initOptions.phone_num,sipServer:this._initOptions.sip_server}),e}))}checkOut(){return u(this,void 0,void 0,(function*(){return yield(e=this._baseParams,te({baseUrl:ie,url:"/open/agent/check-out",data:e}));var e}))}getCtiFlowId(){return u(this,void 0,void 0,(function*(){const e=yield(e=>te({baseUrl:ie,url:"/open/num/generate",data:e}))(this._baseParams),{code:t,data:i}=e;return 0===t&&(this._baseParams.ctiFlowId=i,this._ctiFlowIdList.push(i),N(L.TrackParams,{cti_flow_id:i,cti_flow_id_list:JSON.stringify(this._ctiFlowIdList)})),e}))}setIdle(){return u(this,void 0,void 0,(function*(){return yield(e=this._baseParams,te({baseUrl:ie,url:"/open/agent/idle",data:e}));var e}))}setBusy(){return u(this,void 0,void 0,(function*(){return yield(e=this._baseParams,te({baseUrl:ie,url:"/open/agent/busy",data:e}));var e}))}makeCall(e){return u(this,void 0,void 0,(function*(){if(this._callStatus!==C.Started)return this._callStatus=C.Started,yield this.getCtiFlowId(),this.playAudio(q.WaitAudio),yield this.serverCall(e)}))}serverCall({called:e,caller:t,ext:i}){return u(this,void 0,void 0,(function*(){const s=Object.assign(Object.assign(Object.assign({},this._baseParams),{called:e,caller:t}),i),n=yield(e=>te({baseUrl:ie,url:"/open/agent/manual-call",data:e}))(s),{code:o,data:r}=n;return 0===o?""===this._callId&&r&&(this._callId=r,N(L.TrackParams,{call_id:r})):(this._callStatus=C.Stopped,this.stopLocalAudio()),n}))}answer(){return new Promise(((e,t)=>{var i;null===(i=this._sipUserAgent)||void 0===i||i.answer({sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}}).then((()=>{e({code:0,data:"answer",msg:"SIP 接起电话成功"}),this.logger.debug("sip_accept_success")})).catch((e=>{const i={type:M.SdkError,code:D.Answer,msg:this.scene===R.Manual?V.ManualCallAnswerErrorMsg:V.RobotOrWeChatAnswerErrorMsg,method:"answer"};t(i),this.eventEmitAndTrack($.OnCtiError,i,`${e}`),this.logger.error(`${$.OnCtiError} | ${e}`)}))}))}bye(){return new Promise(((e,t)=>{var i;null===(i=this._sipUserAgent)||void 0===i||i.hangup().then((()=>{e({code:0,data:"bye",msg:"SIP 挂断电话成功"}),this.logger.debug("sip_bye_success")})).catch((e=>{const i={type:M.SdkError,code:D.Bye,msg:V.SipByeErrorMsg,method:"bye"};t(i),"Session does not exist."!==e.message&&this.eventEmitAndTrack($.OnCtiError,i,`${e}`),this.logger.error(`${$.OnCtiError} | ${e}`)}))}))}serverBye(){return u(this,void 0,void 0,(function*(){try{if(this.bye(),!this._baseParams.ctiFlowId&&this.scene===R.Manual)return;const e=yield this.turnHang();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}))}turnHang(){return u(this,void 0,void 0,(function*(){const e=yield(t=Object.assign(Object.assign({},this._baseParams),{callId:this._callId}),te({baseUrl:ie,url:"/open/agent/manual-hang",data:t}));var t;return this._callId="",e}))}getAgentStatus(){return u(this,void 0,void 0,(function*(){return yield(e=this._baseParams,te({baseUrl:ie,url:"/open/agent/agent-state",data:e}));var e}))}loadAgentGroupData(e){return u(this,void 0,void 0,(function*(){return yield(t=Object.assign(Object.assign({},this._baseParams),{monitorIds:e}),te({baseUrl:ie,url:"/open/monitor/load-agent-group-data",data:t}));var t}))}listen(e){return u(this,void 0,void 0,(function*(){const t=yield this.getCtiFlowId();return t&&0!==t.code?t:yield(i=Object.assign(Object.assign({},this._baseParams),{agent_id:e,leaderAgentId:this.agent_id}),te({baseUrl:ie,url:"/open/agent/listen",data:i}));var i}))}setActiveService(e){return u(this,void 0,void 0,(function*(){return yield(t=Object.assign(Object.assign({},this._baseParams),{serviceId:e}),te({baseUrl:ie,url:"/open/human-service/member-active",data:t}));var t}))}unInit(){return u(this,void 0,void 0,(function*(){yield this.checkOut(),this.setCTIStatus(A.Terminated),this.initInstanceOptions(),this.clearSocketAndSip(),this._callId=""}))}}h([function(e,t,i){const s=i.value;return i.value=function(...e){navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then((()=>(this.logger.debug("media | getUserMedia | 获取浏览器媒体权限成功"),s.apply(this,e)))).catch((e=>{this.logger.error(`media | getUserMedia | ${e}`),this.eventEmitAndTrack($.OnCtiError,{type:M.SdkTerminated,code:j.GetUserMedia,msg:"NotAllowedError"===e.name?"用户拒绝了获取麦克风权限!":"获取麦克风权限失败",method:"getUserMedia"},{source:J.FeMedia,event_name:"get_user_media_error",error:e.name})})):(this.logger.error("media | getUserMedia | 浏览器版本过低,不支持获取媒体权限"),this.eventEmitAndTrack($.OnCtiError,{type:M.SdkTerminated,code:j.GetUserMedia,msg:"浏览器版本过低,不支持获取媒体权限",method:"getUserMedia"},{source:J.FeMedia,event_name:"get_user_media_not_support"}))},i}],re.prototype,"init",null),h([se("签入"),ne()],re.prototype,"checkIn",null),h([se("签出"),ne()],re.prototype,"checkOut",null),h([ne()],re.prototype,"getCtiFlowId",null),h([se("置闲"),ne()],re.prototype,"setIdle",null),h([se("置忙"),ne()],re.prototype,"setBusy",null),h([se("人工外呼")],re.prototype,"makeCall",null),h([ne()],re.prototype,"serverCall",null),h([se("接起")],re.prototype,"answer",null),h([se("挂断")],re.prototype,"bye",null),h([ne()],re.prototype,"turnHang",null),h([ne()],re.prototype,"getAgentStatus",null),h([se("获取监听组成员"),ne()],re.prototype,"loadAgentGroupData",null),h([se("坐席监听"),ne()],re.prototype,"listen",null),h([se("签入人工组"),ne()],re.prototype,"setActiveService",null),h([function(e,t,i){const s=i.value;return i.value=function(...e){const t=e[0];let i=[];return i=t.scene===R.Monitor?Q:Y,i.forEach((e=>{if(!t[e])throw`参数[${e}]为必填参数`})),s.apply(this,e)},i}],re,"getInstance",null);const ae=e=>re.getInstance(e);export{M as CTIErrorType,$ as CTIEvent,A as CTIStatus,C as CallStatus,j as HskTerminatedCode,x as Logger,_ as LoggerLevels,T as MonitorScene,I as SIPStatus,R as Scene,D as SdkErrorCode,E as SessionStatus,P as SocketStatus,ae as getInstance};
|