goeasy-rtc-0.3.7.esm.min.js 37 KB

12
  1. function t(t,e,i,s){return new(i||(i=Promise))((function(n,o){function r(t){try{c(s.next(t))}catch(t){o(t)}}function a(t){try{c(s.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(r,a)}c((s=s.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t.RTC_LOST="RTC_LOST",t.RTC_RECONNECT="RTC_RECONNECT",t.RTC_TIMEOUT="RTC_TIMEOUT",t.RTC_ACCEPTED="RTC_ACCEPTED",t.RECEIVED_RTC_REMOTE_FLOW="RECEIVED_RTC_REMOTE_FLOW",t.GOEASY_TIMEOUT="GOEASY_TIMEOUT",t.GOEASY_DISCONNECTED="GOEASY_DISCONNECTED",t.RTC_REMOTE_MIC_CHANGED="RTC_REMOTE_MIC_CHANGED",t.RTC_REMOTE_CAMERA_CHANGED="RTC_REMOTE_CAMERA_CHANGED"}(e||(e={}));var i={exports:{}};!function(t){function e(t){if(t)return function(t){for(var i in e.prototype)t[i]=e.prototype[i];return t}(t)}i.exports=e,e.prototype.on=e.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},e.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n=0;n<s.length;n++)if((i=s[n])===e||i.fn===e){s.splice(n,1);break}return this},e.prototype.emit=function(t){this._callbacks=this._callbacks||{};var e=[].slice.call(arguments,1),i=this._callbacks["$"+t];if(i)for(var s=0,n=(i=i.slice(0)).length;s<n;++s)i[s].apply(this,e);return this},e.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},e.prototype.hasListeners=function(t){return!!this.listeners(t).length}}();var s=i.exports,n={exports:{}},o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(o){var r=new Uint8Array(16);n.exports=function(){return o(r),r}}else{var a=new Array(16);n.exports=function(){for(var t,e=0;e<16;e++)0==(3&e)&&(t=4294967296*Math.random()),a[e]=t>>>((3&e)<<3)&255;return a}}for(var c=[],l=0;l<256;++l)c[l]=(l+256).toString(16).substr(1);var u,d,h=function(t,e){var i=e||0,s=c;return[s[t[i++]],s[t[i++]],s[t[i++]],s[t[i++]],"-",s[t[i++]],s[t[i++]],"-",s[t[i++]],s[t[i++]],"-",s[t[i++]],s[t[i++]],"-",s[t[i++]],s[t[i++]],s[t[i++]],s[t[i++]],s[t[i++]],s[t[i++]]].join("")},m=n.exports,C=h,T=0,E=0;var p=function(t,e,i){var s=e&&i||0,n=e||[],o=(t=t||{}).node||u,r=void 0!==t.clockseq?t.clockseq:d;if(null==o||null==r){var a=m();null==o&&(o=u=[1|a[0],a[1],a[2],a[3],a[4],a[5]]),null==r&&(r=d=16383&(a[6]<<8|a[7]))}var c=void 0!==t.msecs?t.msecs:(new Date).getTime(),l=void 0!==t.nsecs?t.nsecs:E+1,h=c-T+(l-E)/1e4;if(h<0&&void 0===t.clockseq&&(r=r+1&16383),(h<0||c>T)&&void 0===t.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");T=c,E=l,d=r;var p=(1e4*(268435455&(c+=122192928e5))+l)%4294967296;n[s++]=p>>>24&255,n[s++]=p>>>16&255,n[s++]=p>>>8&255,n[s++]=255&p;var R=c/4294967296*1e4&268435455;n[s++]=R>>>8&255,n[s++]=255&R,n[s++]=R>>>24&15|16,n[s++]=R>>>16&255,n[s++]=r>>>8|128,n[s++]=255&r;for(var f=0;f<6;++f)n[s+f]=o[f];return e||C(n)},R=n.exports,f=h;var v=function(t,e,i){var s=e&&i||0;"string"==typeof t&&(e="binary"===t?new Array(16):null,t=null);var n=(t=t||{}).random||(t.rng||R)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e)for(var o=0;o<16;++o)e[s+o]=n[o];return e||f(n)},g=p,y=v,k=y;k.v1=g,k.v4=y;var b=k;class _{support(){return!0}getParams(){return this.params}setData(t){this.active=t.a,this.data=t.d}preConnect(t){}postConnect(){}}const I=s;class A{constructor(){this.emitter=new I}on(t,e){return this.emitter.on(t,e),this}once(t,e){return this.emitter.once(t,e),this}off(t,e){return this.emitter.off(t,e),this}fire(t,e){return this.emitter.emit(t,e),this}}class w{constructor(){this.eventDriver=new A}on(t,e){this.eventDriver.on(t,e)}off(t,e){this.eventDriver.off(t,e)}fire(t,e){this.eventDriver.fire(t,e)}}let S=new class{isDef(t){return!this.isUndef(t)}isUndef(t){return null==t}isPrimitive(t){return"string"==typeof t||"number"==typeof t||"symbol"==typeof t||"boolean"==typeof t}isObject(t){return null!==t&&"object"==typeof t}isPlainObject(t){return"[object Object]"===Object.prototype.toString.call(t)}isRegExp(t){return"[object RegExp]"===Object.prototype.toString.call(t)}isValidArrayIndex(t){let e=parseFloat(String(t));return e>=0&&Math.floor(e)===e&&isFinite(t)}isString(t){return"string"==typeof t}isNumber(t){return"number"==typeof t}isStringOrNumber(t){return this.isString(t)||this.isNumber(t)}isArray(t){return"[object Array]"===Object.prototype.toString.call(t)}isEmpty(t){return this.isArray(t)?0===t.length:this.isObject(t)?!this.isDef(t):!this.isNumber(t)&&(this.isString(t)?""===t.trim():!this.isDef(t))}isNative(t){return"function"==typeof t&&/native code/.test(t.toString())}isFunction(t){return"function"==typeof t}isBoolean(t){return"boolean"==typeof t}isTrue(t){return!0===t}isFalse(t){return!1===t}isNull(t){return null===t}};const D=s;class N{constructor(){this.emitter=new D}on(t,e){if(!S.isString(t))throw Error("event require a string.");if(!S.isFunction(e))throw Error("callback must be a function");this.emitter.on(t,e)}fire(t,e){this.emitter.emit(t,e)}off(t,e){this.emitter.off(t,e)}}class M{static init(t,e,i,s,n,o){this.Socket=t,this.N=e,this.Member=i,this.v=s,this.Platform=n,this.GModules=o}}const L=b;class O{static get(){return L.v1().replace(/-/g,"")}}var P,U,G;(U=P||(P={})).WRITE="WRITE",U.READ="READ",U.NONE="NONE";class q{constructor(t){this.permission=P.NONE,this.singleTimeout=0,this.totalTimeout=0,this.startTime=0,this.complete=!1,this.retried=0,this.unique=!1,this.uuid=O.get(),this.name=t.name,this.params=t.params,this.permission=t.permission,this.totalTimeout=t.totalTimeout,this.singleTimeout=t.singleTimeout,t.unique&&(this.unique=t.unique),this.success=e=>{this.complete||(this.end(),t.success(e))},this.fail=e=>{this.complete||(this.end(),t.fail(e))}}start(){this.startTime=Date.now(),this.initAutoTimeout()}end(){this.complete=!0,clearTimeout(this.timeoutHandler)}initAutoTimeout(){this.timeoutHandler=setTimeout((()=>{this.complete||this.fail({resultCode:408,content:"Host unreachable or timeout"})}),this.totalTimeout)}}class x extends w{static init(){this.i=new x}}class V{constructor(){this.callees=new Array}getDuration(){return Math.floor((Date.now()-this.acceptedAt)/1e3)}}class j{constructor(t,e,i){this.micMuted=!1,this.cameraMuted=!1,this.id=t,this.data=e,this.status=i}}class K{constructor(t){this.call=new V,this.call=t}}class F{static init(){this.eventCenter=new N}static on(t,e){this.eventCenter.on(t,e)}static fire(t,e){this.eventCenter.fire(t,e)}static off(t,e){this.eventCenter.off(t,e)}}!function(t){t.RING="RING",t.USER_RANG="USER_RANG",t.USER_QUIT="USER_QUIT",t.USER_ACCEPTED="USER_ACCEPTED",t.CALL_ENDED="CALL_ENDED",t.USER_MIC_CHANGED="USER_MIC_CHANGED",t.USER_CAMERA_CHANGED="USER_CAMERA_CHANGED"}(G||(G={}));class H{static setStatus(t){this.status&&this.status.destroy(),this.status=t,gt.callContext.call.status=t.name()}static clearStatus(){this.status&&(this.status.destroy(),this.status=null)}}var Q;!function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"}(Q||(Q={}));class W extends _{static init(t){t.c(M),this.module=new W,this.module.name=this.RTC_MODULE_NAME;let e=null;if(this.supportApp()){let t=uni.requireNativePlugin("RTCClientPlugin");t&&(e=t.v())}this.module.params={v:{n:"goeasy-rtc",v:"0.3.7",npv:e}},M.GModules.initModule(this.module)}static check(){if(!this.module)throw new Error("Please init GRTC first.");if(!this.module.active)throw new Error("RTC unavailable. Please confirm if your GoEasy application supports RTC or contact GoEasy team.");if(!this.supportApp()&&!this.supportBrowser())throw new Error("GRTC is only supported in Android and iOS apps developed with UniApp and Browsers");if(!this.supportGoEasyVersion())throw new Error("GRTC is only supported in GoEasy SDK version 2.10.0 or later")}static supportGoEasyVersion(){return M.v.localeCompare("2.10.0",void 0,{numeric:!0,sensitivity:"base"})>=0}static supportApp(){return[M.Platform.type.UNI_ANDROID,M.Platform.type.UNI_IOS].includes(M.Platform.current)}static supportBrowser(){return M.Platform.type.BROWSER===M.Platform.current}support(){return W.supportGoEasyVersion()&&(W.supportApp()||W.supportBrowser())}postConnect(){x.init(),F.init(),kt.init()}}W.RTC_MODULE_NAME="GRTC";let B=new class{isDef(t){return!this.isUndef(t)}isUndef(t){return null==t}isPrimitive(t){return"string"==typeof t||"number"==typeof t||"symbol"==typeof t||"boolean"==typeof t}isObject(t){return null!==t&&"object"==typeof t}isString(t){return"string"==typeof t}isNumber(t){return"number"==typeof t}isStringOrNumber(t){return this.isString(t)||this.isNumber(t)}isArray(t){return"[object Array]"===Object.prototype.toString.call(t)}isEmpty(t){return this.isArray(t)?0===t.length:this.isObject(t)?!this.isDef(t):!this.isNumber(t)&&(this.isString(t)?""===t.trim():!this.isDef(t))}isNative(t){return"function"==typeof t&&/native code/.test(t.toString())}isFunction(t){return"function"==typeof t}};const Y=new class{validateId(t,e){if(B.isEmpty(t))throw{code:400,content:` ${e} is required.`};if(!B.isStringOrNumber(t))throw{code:400,content:`TypeError: ${e} require string or number.`}}validateNotification(t){if(t){if(!B.isObject(t))throw{code:400,content:"TypeError: notification requires an object."};{if(e(t,"title",32),e(t,"body",50),B.isDef(t.sound)&&!B.isString(t.sound))throw{code:400,content:"notification.sound must be a string"};if(B.isDef(t.badge)&&!B.isString(t.badge))throw{code:400,content:"notification.badge must be a string"};t.badge=t.badge||"0";let s=t.vendorOptions;B.isObject(s)&&(i(s,"huawei","category","string"),i(s,"xiaomi","channel_id","string"),i(s,"oppo","channel_id","string"),i(s,"vivo","classification","number"),i(s,"vivo","category","string"))}}function e(t,e,i){if(!(B.isString(t[e])&&t[e].length<=i))throw{code:400,content:`notification.${e} must be a string of no more than ${i} characters`}}function i(t,e,i,s){let n=t[e];if(B.isObject(n)&&B.isDef(n[i])){let t={code:400,content:`notification.vendorOptions.${e}.${i} require a ${s}}`},o=n[i];if("string"===s&&!B.isString(o))throw t;if("number"===s&&!B.isNumber(o))throw t}}}validateObject(t,e){if(B.isUndef(t)||!B.isObject(t))throw{code:400,content:e+" must be an object."}}validateString(t,e){if(B.isUndef(t)||!B.isString(t))throw{code:400,content:e+" must be a string."}}};var $,J,X,z,Z,tt;!function(t){t.ALL_BUSY="ALL_BUSY",t.DIAL_FAILED="DIAL_FAILED",t.CANCELLED="CANCELLED",t.REJECTED="REJECTED",t.HUNG_UP="HUNG_UP",t.RTC_DISCONNECTED="RTC_DISCONNECTED",t.GOEASY_DISCONNECTED="GOEASY_DISCONNECTED",t.HANDLED_ON_ANOTHER_DEVICE="HANDLED_ON_ANOTHER_DEVICE",t.RING_TIMEOUT="RING_TIMEOUT",t.ACCEPT_FAILED="ACCEPT_FAILED",t.DIAL_TIMEOUT="DIAL_TIMEOUT"}($||($={}));class et{}class it{constructor(t,e){this.joined=!1,this.token=e,this.video=t===Q.VIDEO,this.userId=M.Socket.user().id}play(t){}initLocal(){}}class st extends it{constructor(t,i,s){super(i,s),this.client=t,this.client.createRTCClient({vendor:this.token.vendor,userId:this.userId}),plus.globalEvent.addEventListener("connectionLost",(()=>{x.i.fire(e.RTC_LOST)})),plus.globalEvent.addEventListener("connectionRecovery",(t=>{x.i.fire(e.RTC_RECONNECT)})),plus.globalEvent.addEventListener("receivedRemoteFlow",(t=>{x.i.fire(e.RECEIVED_RTC_REMOTE_FLOW,t)})),plus.globalEvent.addEventListener("remoteMicChanged",(t=>{x.i.fire(e.RTC_REMOTE_MIC_CHANGED,t)})),plus.globalEvent.addEventListener("remoteCameraChanged",(t=>{x.i.fire(e.RTC_REMOTE_CAMERA_CHANGED,t)}))}destroy(){plus.globalEvent.removeEventListener("connectionLost"),plus.globalEvent.removeEventListener("connectionRecovery"),plus.globalEvent.removeEventListener("receivedRemoteFlow"),plus.globalEvent.removeEventListener("remoteMicChanged"),plus.globalEvent.removeEventListener("remoteCameraChanged"),this.joined&&(this.leave(),this.joined=!1),this.client.destroyEngine()}join(){return this.token.video=this.video,this.token.userId=this.userId,new Promise(((t,e)=>{this.client.joinChannel(this.token,(()=>{this.userId,this.token.callId,this.joined=!0,t()}),(t=>{this.userId,this.token.callId,e({code:400,content:"Failed to join Channel, error code:"+t})}))}))}push(){this.video?this.client.callVideo():this.client.callAudio()}leave(){this.client.leaveChannel()}accept(){return t(this,void 0,void 0,(function*(){yield this.join(),this.push()}))}muteMic(t){this.client.muteMic({enabled:t})}toggleSpeaker(t){this.client.enableSpeaker({enabled:t})}muteCamera(t){this.client.muteCamera({enabled:t})}switchCamera(){this.client.switchCamera()}}class nt extends et{constructor(){if(super(),this.nativePlugin=uni.requireNativePlugin("RTCClientPlugin"),!this.nativePlugin)throw"Please configure GoEasy RTC native plugin first: https://www.goeasy.io"}createClient(e,i){return t(this,void 0,void 0,(function*(){return new st(this.nativePlugin,e,i)}))}requestPermission(t){return new Promise(((e,i)=>{Q.VIDEO===t?this.nativePlugin.requestVideoCallPermission((t=>{200===t?e():i({code:403,content:"Failed to request video call permission, error code:"+t})})):Q.AUDIO===t?this.nativePlugin.requestVoiceCallPermission((t=>{200===t?e():i({code:403,content:"Failed to request voice call permission, error code:"+t})})):i({code:400,content:"Unsupported media type"})}))}}!function(t){t.QN="QN",t.ALI="ALI",t.TX="TX",t.LK="LK"}(J||(J={}));class ot{constructor(t,e){this.userId=t,this.muted=e}}class rt extends it{constructor(t,e){super(t,e),this.localTracks=[],this.remoteTracks=new Map;this.QNRTC=(()=>{try{return require("qnweb-rtc").default||require("qnweb-rtc")}catch(t){throw new Error("Please run npm install qnweb-rtc")}})(),this.QNRTC.setLogLevel("NONE"),this.client=this.QNRTC.createClient(),this.initListeners()}initListeners(){this.client.on("connection-state-changed",((t,i)=>{"RECONNECTED"===t?x.i.fire(e.RTC_RECONNECT):"DISCONNECTED"===t&&x.i.fire(e.RTC_LOST)})),this.client.on("user-published",((t,e)=>{this.subscribe(t,e)}))}listenRemoteTrackMutedChanged(t){t.on("mute-state-changed",(i=>{let s=t.isAudio(),n=t.userID,o=s?e.RTC_REMOTE_MIC_CHANGED:e.RTC_REMOTE_CAMERA_CHANGED;x.i.fire(o,new ot(n,i))}))}subscribe(i,s){return t(this,void 0,void 0,(function*(){const t=yield this.client.subscribe(s);if(t.audioTracks.length>0&&this.listenRemoteTrackMutedChanged(t.audioTracks[0]),t.videoTracks.length>0&&this.listenRemoteTrackMutedChanged(t.videoTracks[0]),this.remoteTracks.set(i,t),x.i.fire(e.RECEIVED_RTC_REMOTE_FLOW,{userId:i}),!1===this.video)this.playRemoteMicrophoneTracks();else{let t=this.getView(i);t&&this.playRemoteTrack(i,t)}}))}initLocal(){return t(this,void 0,void 0,(function*(){yield this.initLocalTracks()}))}join(){return t(this,void 0,void 0,(function*(){const t=this.token.vendorToken.token;yield this.client.join(t),this.joined=!0}))}push(){return t(this,void 0,void 0,(function*(){yield this.client.publish(this.localTracks)}))}accept(){return t(this,void 0,void 0,(function*(){yield this.join(),yield this.push()}))}initLocalTracks(){return t(this,void 0,void 0,(function*(){this.localTracks.length>0||(this.video?this.localTracks=yield this.QNRTC.createMicrophoneAndCameraTracks():this.localTracks=[yield this.QNRTC.createMicrophoneAudioTrack()])}))}play(e){return t(this,void 0,void 0,(function*(){if(this.video){const t=this.getView(e);this.userId===e?(yield this.initLocalTracks(),this.listenCustomAttributes(t),this.playLocalTrack(t)):(this.listenCustomAttributes(t),this.playRemoteTrack(e,t))}else this.playRemoteMicrophoneTracks()}))}getView(t){const e=document.getElementsByClassName("grtc-video");for(let i=0;i<e.length;i++){const s=e[i];if(s.getAttribute("userId")===t)return s}}listenCustomAttributes(t){new MutationObserver((e=>{e.forEach((e=>{const i=e.oldValue,s=t.getAttribute("userId");B.isEmpty(s)||s===i||(this.userId===s?this.playLocalTrack(t):this.playRemoteTrack(s,t))}))})).observe(t,{attributes:!0,attributeOldValue:!0,attributeFilter:["userid"]})}playRemoteMicrophoneTracks(){const t=document.getElementsByClassName("grtc-audio")[0];t&&this.remoteTracks.forEach(((e,i)=>{for(const i of e.audioTracks)i.play(t)}))}playLocalTrack(t){for(const e of this.localTracks)e.isAudio()||e.play(t,{mirror:!0})}playRemoteTrack(t,e){const i=this.remoteTracks.get(t);if(i)for(const t of[...i.videoTracks,...i.audioTracks])t.play(e)}destroy(){this.joined&&this.leave(),this.releaseMediaTracks()}releaseMediaTracks(){for(const t of this.localTracks)t.destroy();this.localTracks=[],this.remoteTracks.clear()}leave(){return t(this,void 0,void 0,(function*(){yield this.client.leave()}))}requestPermission(e){return t(this,void 0,void 0,(function*(){}))}toggleSpeaker(t){throw new Error("not support.")}muteCamera(t){for(const e of this.localTracks)e.isVideo()&&e.setMuted(t)}muteMic(t){for(const e of this.localTracks)e.isAudio()&&e.setMuted(t)}switchCamera(){throw new Error("not support.")}}class at extends it{constructor(t,e){super(t,e),this.localTracks=[],this.remoteTracks=new Map,this.isFrontFacing=!0,this.LiveKitRTC=this.loadLiveKitRTC(),this.resolution=this.LiveKitRTC.VideoPresets.h720.resolution;const i=new this.LiveKitRTC.DefaultReconnectPolicy([0,1e3,4e3,9e3,16e3]);this.client=new this.LiveKitRTC.Room({adaptiveStream:!1,dynacast:!1,videoCaptureDefaults:{resolution:this.resolution},reconnectPolicy:i}),this.initListeners()}loadLiveKitRTC(){try{return require("livekit-client")}catch(t){throw new Error("Please run npm install livekit-client@2.5.10")}}initListeners(){this.client.on(this.LiveKitRTC.RoomEvent.Reconnected,(()=>{x.i.fire(e.RTC_RECONNECT)})),this.client.on(this.LiveKitRTC.RoomEvent.Disconnected,(()=>{x.i.fire(e.RTC_LOST)})),this.client.on(this.LiveKitRTC.RoomEvent.TrackPublished,((t,e)=>{e.identity,t.setSubscribed(!0)})),this.client.on(this.LiveKitRTC.RoomEvent.ParticipantConnected,(t=>{t.identity,this.listenRemoteParticipant(t)})),this.client.on(this.LiveKitRTC.RoomEvent.TrackSubscribed,((t,e,i)=>{i.identity,this.handleTrackSubscribed(t,e,i)}))}handleTrackSubscribed(t,i,s){let n=s.identity;if(t.kind===this.LiveKitRTC.Track.Kind.Video||t.kind===this.LiveKitRTC.Track.Kind.Audio)if(this.video?t.kind===this.LiveKitRTC.Track.Kind.Video&&x.i.fire(e.RECEIVED_RTC_REMOTE_FLOW,{userId:n}):x.i.fire(e.RECEIVED_RTC_REMOTE_FLOW,{userId:n}),this.updateRemoteTracks(n,t),this.video){let t=this.getVideoView(n);t&&this.playRemoteTrack(n,t)}else this.playRemoteMicTracks()}updateRemoteTracks(t,e){let i=this.remoteTracks.get(t)||[];i.push(e),this.remoteTracks.set(t,i)}listenRemoteParticipant(t){const e=t.identity;t.on(this.LiveKitRTC.RoomEvent.TrackMuted,(t=>this.onTrackMuted(t,e))),t.on(this.LiveKitRTC.RoomEvent.TrackUnmuted,(t=>this.onTrackUnmuted(t,e)))}onTrackMuted(t,i){let s=t.kind;t.kind,s===this.LiveKitRTC.Track.Kind.Video?x.i.fire(e.RTC_REMOTE_CAMERA_CHANGED,new ot(i,!0)):s===this.LiveKitRTC.Track.Kind.Audio&&x.i.fire(e.RTC_REMOTE_MIC_CHANGED,new ot(i,!0))}onTrackUnmuted(t,i){let s=t.kind;s===this.LiveKitRTC.Track.Kind.Video?x.i.fire(e.RTC_REMOTE_CAMERA_CHANGED,new ot(i,!1)):s===this.LiveKitRTC.Track.Kind.Audio&&x.i.fire(e.RTC_REMOTE_MIC_CHANGED,new ot(i,!1))}initLocal(){return t(this,void 0,void 0,(function*(){yield this.initLocalTracks()}))}join(){return t(this,void 0,void 0,(function*(){const t=this.token.vendorToken;yield this.client.connect(t.url,t.token,{autoSubscribe:!1}),this.joined=!0}))}push(){return t(this,void 0,void 0,(function*(){yield Promise.all(this.localTracks.map((t=>this.client.localParticipant.publishTrack(t,{simulcast:!1})))),this.client.remoteParticipants.forEach((t=>{t.trackPublications.forEach((t=>t.setSubscribed(!0))),this.listenRemoteParticipant(t)}))}))}accept(){return t(this,void 0,void 0,(function*(){yield this.join(),yield this.push()}))}initLocalTracks(){return t(this,void 0,void 0,(function*(){const t=yield this.LiveKitRTC.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});if(this.localTracks.push(t),this.video){const t=yield this.LiveKitRTC.createLocalVideoTrack({facingMode:"user"});this.localTracks.push(t)}}))}play(e){return t(this,void 0,void 0,(function*(){if(this.video){const t=this.getVideoView(e);this.listenCustomAttributes(t),this.userId===e?this.playLocalTrack(t):this.playRemoteTrack(e,t)}else this.playRemoteMicTracks()}))}getVideoView(t){const e=document.getElementsByClassName("grtc-video");for(let i=0;i<e.length;i++){const s=e[i];if(s.getAttribute("userId")===t)return s}}listenCustomAttributes(t){new MutationObserver((e=>{e.forEach((e=>{const i=e.oldValue,s=t.getAttribute("userId");B.isEmpty(s)||s===i||(this.userId===s?this.playLocalTrack(t):this.playRemoteTrack(s,t))}))})).observe(t,{attributes:!0,attributeOldValue:!0,attributeFilter:["userid"]})}playRemoteMicTracks(){const t=document.getElementsByClassName("grtc-audio")[0];if(t)for(const e of this.remoteTracks.values())for(const i of e){let e=i.attach();t.appendChild(e)}}playLocalTrack(t){this.playTrack(this.localTracks,t)}playRemoteTrack(t,e){const i=this.remoteTracks.get(t);i&&this.playTrack(i,e)}playTrack(t,e){for(const i of t){let t,s=i.kind,n=i.attach();s===this.LiveKitRTC.Track.Kind.Video?(n.style.width="100%",n.style.height="100%",n.style.objectFit="cover",t=e.querySelector("video")):s===this.LiveKitRTC.Track.Kind.Audio&&(t=e.querySelector("audio")),t?t.replaceWith(n):e.appendChild(n)}}destroy(){this.joined&&this.leave(),this.releaseMediaTracks()}releaseMediaTracks(){for(const t of this.localTracks)t.detach(),t.stop();this.localTracks=[],this.remoteTracks.clear()}leave(){return t(this,void 0,void 0,(function*(){yield this.client.disconnect()}))}toggleSpeaker(t){throw new Error("not support.")}muteCamera(t){for(const e of this.localTracks)e.kind===this.LiveKitRTC.Track.Kind.Video&&this.client.localParticipant.setCameraEnabled(!t)}muteMic(t){for(const e of this.localTracks)e.kind===this.LiveKitRTC.Track.Kind.Audio&&this.client.localParticipant.setMicrophoneEnabled(!t)}switchCamera(){var t;const e=this.client.localParticipant.getTrackPublication(this.LiveKitRTC.Track.Source.Camera);if(!e)return;this.isFrontFacing=!this.isFrontFacing;const i={resolution:this.resolution,facingMode:this.isFrontFacing?"user":"environment"};null===(t=e.videoTrack)||void 0===t||t.restartTrack(i)}}class ct extends et{createClient(e,i){return t(this,void 0,void 0,(function*(){let t,s=i.vendor;if(J.QN===s)t=new rt(e,i);else{if(J.LK!==s)throw J.ALI===s?new Error("ali web rtc not implement"):J.TX===s?new Error("tencent web rtc not implement"):new Error("rtc vendor not support");t=new at(e,i)}return yield t.initLocal(),t}))}requestPermission(e){return new Promise(((i,s)=>t(this,void 0,void 0,(function*(){if(navigator.permissions&&navigator.permissions.query){if("denied"===(yield navigator.permissions.query({name:"microphone"})).state&&s({code:403,content:"Failed to request microphone permission"}),e===Q.VIDEO){"denied"===(yield navigator.permissions.query({name:"camera"})).state&&s({code:403,content:"Failed to request camera permission"})}}i()}))))}}class lt{constructor(t,e,i){this.name=t,this.callId=e,this.data=i}static createCallCommand(t,e,i){let s={calleeIds:t.callees.map((t=>t.id)),mediaType:i.mediaType,groupId:i.groupId,callId:e};return i.notification&&(s.notification=i.notification),new lt(X.CALL,e,s)}}!function(t){t.CALL="CALL",t.QUIT="QUIT",t.BUSY="BUSY",t.ACCEPT="ACCEPT",t.RANG="RANG",t.HANGUP="HANGUP",t.CANCEL="CANCEL",t.REJECT="REJECT",t.RTC_DISCONNECT="RTC_DISCONNECT",t.GET_TOKEN="GET_TOKEN"}(X||(X={})),function(t){t.RTC_CMD="RTC_CMD",t.RTC_PKT="RTC_PKT"}(z||(z={})),function(t){t[t.connect=3e3]="connect",t[t.reconnectionDelayMax=3e3]="reconnectionDelayMax",t[t.commonQuerySingle=2500]="commonQuerySingle",t[t.commonQueryTotal=12e3]="commonQueryTotal",t[t.commonRequestSingle=1700]="commonRequestSingle",t[t.commonRequestTotal=12e3]="commonRequestTotal",t[t.commonInfiniteSingle=1700]="commonInfiniteSingle",t[t.commonInfiniteTotal=864e5]="commonInfiniteTotal"}(Z||(Z={}));class ut{static init(){W.supportApp()?this.rtcPlugin=new nt:this.rtcPlugin=new ct}static initClient(e,i){return t(this,void 0,void 0,(function*(){let t=yield this.getNewToken(i);return this.vendorClient=yield this.rtcPlugin.createClient(e,t),t.callId}))}static getNewToken(e){return t(this,void 0,void 0,(function*(){let t={name:X.GET_TOKEN};return e&&(t.callId=e),new Promise(((e,i)=>{let s=new q({name:z.RTC_CMD,params:t,permission:P.WRITE,singleTimeout:Z.commonRequestSingle,totalTimeout:Z.commonRequestTotal,success:t=>{e(t.content)},fail:t=>{i(t)}});M.Socket.e(s)}))}))}}class dt{onRTCRemoteFlow(t){}onUserAcceptPacket(t){}onUserRang(e){return t(this,void 0,void 0,(function*(){gt.updateMemberStatus(e.callerId,"Ringing");const t=yield M.Member.i.getData(e.callerId),i={id:e.callerId,data:t.get(e.callerId)};F.fire(G.USER_RANG,{user:i})}))}onUserQuit(e){return t(this,void 0,void 0,(function*(){return Promise.resolve()}))}onRTCTimeout(){}onGoEasyDisconnected(){gt.destroyWithEvent($.GOEASY_DISCONNECTED)}destroy(){}muteMic(t){}toggleSpeaker(t){}switchCamera(){ut.vendorClient.switchCamera()}muteCamera(t){ut.vendorClient.muteCamera(t),gt.muteMemberCamera(M.Socket.user().id,t)}play(t){ut.vendorClient.play(t)}onRTCRemoteMicChanged(t){}onRTCRemoteCameraChanged(e){return t(this,void 0,void 0,(function*(){}))}}class ht{static sendRequest(t){return new Promise(((e,i)=>{let s=new q({name:z.RTC_CMD,params:t,permission:P.WRITE,singleTimeout:Z.commonRequestSingle,totalTimeout:Z.commonRequestTotal,success:t=>{e(t)},fail:t=>{i({code:400,content:t.content})}});M.Socket.e(s)}))}}class mt extends dt{constructor(){super(),gt.callContext.call.acceptedAt=Date.now()}name(){return"InCall"}accept(){return Promise.reject("The call has already been accepted")}end(){const t=new lt(X.HANGUP,gt.callContext.call.id);ht.sendRequest(t),gt.destroyWithEvent($.HUNG_UP)}onRTCTimeout(){const t=new lt(X.RTC_DISCONNECT,gt.callContext.call.id);ht.sendRequest(t),gt.destroyWithEvent($.RTC_DISCONNECTED)}onUserQuit(e){return t(this,void 0,void 0,(function*(){gt.updateMemberStatus(e.userId,"Quit");const t=yield M.Member.i.getData(e.userId),i={id:e.userId,data:t.get(e.userId)};!0===e.ended?gt.destroyWithEvent(e.reason,i):F.fire(G.USER_QUIT,{user:i,reason:e.reason})}))}onRTCRemoteFlow(e){return t(this,void 0,void 0,(function*(){const t=gt.callContext.call;gt.updateMemberStatus(e.userId,t.status);const i=yield M.Member.i.getData(e.userId),s={id:e.userId,data:i.get(e.userId)};F.fire(G.USER_ACCEPTED,{user:s})}))}muteMic(t){ut.vendorClient.muteMic(t),gt.muteMemberMic(M.Socket.user().id,t)}toggleSpeaker(t){ut.vendorClient.toggleSpeaker(t),gt.toggleSpeaker(t)}onRTCRemoteMicChanged(e){return t(this,void 0,void 0,(function*(){let t=e.userId;gt.muteMemberMic(t,e.muted);const i={user:{id:t,data:(yield M.Member.i.getData(t)).get(t)},micMuted:e.muted};F.fire(G.USER_MIC_CHANGED,i)}))}onRTCRemoteCameraChanged(e){return t(this,void 0,void 0,(function*(){let t=e.userId;gt.muteMemberCamera(t,e.muted);const i={user:{id:t,data:(yield M.Member.i.getData(t)).get(t)},cameraMuted:e.muted};F.fire(G.USER_CAMERA_CHANGED,i)}))}}class Ct extends dt{constructor(){super(),this.dialTimeoutId=setTimeout((()=>{gt.destroyWithEvent($.DIAL_TIMEOUT)}),45e3)}name(){return"Dialing"}onUserQuit(e){return t(this,void 0,void 0,(function*(){gt.updateMemberStatus(e.userId,"Quit");const t=yield M.Member.i.getData(e.userId),i={id:e.userId,data:t.get(e.userId)};!0===e.ended?gt.destroyWithEvent(e.reason,i):F.fire(G.USER_QUIT,{user:i,reason:e.reason})}))}accept(){return Promise.reject("Cannot accept the call during dialing.")}end(){const t=new lt(X.CANCEL,gt.callContext.call.id);ht.sendRequest(t),gt.destroyWithEvent($.CANCELLED)}onRTCRemoteFlow(e){return t(this,void 0,void 0,(function*(){H.setStatus(new mt),ut.vendorClient.push();const t=gt.callContext.call;t.caller.status=t.status,gt.updateMemberStatus(e.userId,t.status);const i=yield M.Member.i.getData(e.userId),s={id:e.userId,data:i.get(e.userId)};F.fire(G.USER_ACCEPTED,{user:s})}))}destroy(){clearTimeout(this.dialTimeoutId)}}class Tt{static initNotificationAssembler(){M.N.addAssembler({assemble:t=>({callId:t.callId}),support:t=>!!t.callId})}static createLocalNotification(t){const e=M.N.supportAppNotification();let i=t.notification;if(!B.isObject(i)||!e)return;let s={callId:t.callId};M.N.createLocalNotification(i.title,i.body,s,i.sound,i.badge)}}class Et extends dt{constructor(){super(),this.startAccept=!1;const t=Date.now()-gt.callContext.call.time;t>0&&(this.ringTimeoutId=setTimeout((()=>{gt.destroyWithEvent($.RING_TIMEOUT)}),45e3-t))}name(){return"Ringing"}accept(){return new Promise(((i,s)=>t(this,void 0,void 0,(function*(){try{if(this.startAccept)return void s("The call has already been accepted.");this.startAccept=!0;const t=()=>{x.i.off(e.RTC_ACCEPTED,t),i()};x.i.on(e.RTC_ACCEPTED,t),yield ut.vendorClient.join(),ut.vendorClient.push()}catch(t){console.warn("accept failed:",t),gt.destroyWithEvent($.ACCEPT_FAILED),s(t)}}))))}onUserAcceptPacket(t){t.userId===M.Socket.user().id&&gt.destroyWithEvent($.HANDLED_ON_ANOTHER_DEVICE)}onUserQuit(e){return t(this,void 0,void 0,(function*(){try{yield this.startPromise}catch(t){return void console.warn("ring error",t)}gt.updateMemberStatus(e.userId,"Quit");const t=yield M.Member.i.getData(e.userId),i={id:e.userId,data:t.get(e.userId)};e.userId===M.Socket.user().id?gt.destroyWithEvent($.HANDLED_ON_ANOTHER_DEVICE):!0===e.ended?gt.destroyWithEvent(e.reason,i):F.fire(G.USER_QUIT,{user:i,reason:e.reason})}))}end(){const t=new lt(X.REJECT,gt.callContext.call.id);ht.sendRequest(t),gt.destroyWithEvent($.REJECTED)}onRTCRemoteFlow(i){return t(this,void 0,void 0,(function*(){H.setStatus(new mt);const t=new lt(X.ACCEPT,gt.callContext.call.id);yield ht.sendRequest(t);let s=gt.callContext.call;"Quit"!==s.caller.status&&(s.caller.status=s.status),gt.updateMemberStatus(M.Socket.user().id,s.status),gt.updateMemberStatus(i.userId,s.status),x.i.fire(e.RTC_ACCEPTED)}))}onUserRang(e){return t(this,void 0,void 0,(function*(){}))}destroy(){clearTimeout(this.ringTimeoutId)}startRing(e){this.startPromise=new Promise(((i,s)=>t(this,void 0,void 0,(function*(){try{Tt.createLocalNotification(e);const t=H.status.name(),s=gt.callContext.call;s.status=t;const n=e.users.map((t=>t.id)),o=yield M.Member.i.getData(e.callerId,...n);s.caller=new j(e.callerId,o.get(e.callerId),t),s.callees=e.users.map((e=>new j(e.id,o.get(e.id),t))),ut.rtcPlugin.requestPermission(e.type),yield ut.initClient(e.type,e.callId);const r=new lt(X.RANG,s.id);yield ht.sendRequest(r);const a=yield M.Member.i.getData(e.callerId),c={id:e.callerId,data:a.get(e.callerId)};F.fire(G.RING,{user:c}),i()}catch(t){console.warn("Ring failed",t),gt.destroy(),s(t)}}))))}}!function(t){t.RING="RING",t.USER_RANG="U_RANG",t.USER_QUIT="U_QUIT",t.USER_ACCEPTED="U_ACCEPTED",t.ENDED="ENDED"}(tt||(tt={}));class pt{onServerPacket(t,e){switch(t){case tt.RING:this.onRing(e);break;case tt.USER_RANG:this.onUserRang(e);break;case tt.USER_ACCEPTED:this.onUserAcceptPacket(e);break;case tt.USER_QUIT:this.onUserQuit(e)}}}class Rt extends pt{name(){return"Busy"}accept(){return H.status.accept()}end(){H.status.end(),vt.setStatus(new ft)}call(t){return Promise.reject("Another call is in progress.")}onRing(t){const e=new lt(X.BUSY,t.id);ht.sendRequest(e)}onUserAcceptPacket(t){H.status.onUserAcceptPacket(t)}onUserRang(t){H.status.onUserRang(t)}onUserQuit(t){H.status.onUserQuit(t)}onRTCTimeout(){H.status.onRTCTimeout()}onRTCRemoteFlow(t){H.status.onRTCRemoteFlow(t)}onGoEasyDisconnected(){H.status.onGoEasyDisconnected()}muteMic(t){H.status.muteMic(t)}toggleSpeaker(t){H.status.toggleSpeaker(t)}muteCamera(t){H.status.muteCamera(t)}switchCamera(){H.status.switchCamera()}play(t){H.status.play(t)}onRTCRemoteMicChanged(t){H.status.onRTCRemoteMicChanged(t)}onRTCRemoteCameraChanged(t){H.status.onRTCRemoteCameraChanged(t)}}class ft extends pt{name(){return"Idle"}call(e){if(W.check(),Y.validateNotification(e.notification),!M.Socket.user().id)throw new Error("Dialing failed: `id` is required when connecting to GoEasy.");return new Promise(((i,s)=>t(this,void 0,void 0,(function*(){try{vt.setStatus(new Rt),yield ut.rtcPlugin.requestPermission(e.mediaType),"calleeIds"in e?gt.initGroupCall(e):gt.initPrivateCall(e),H.setStatus(new Ct);let t=yield ut.initClient(e.mediaType);ut.vendorClient.join();const n=gt.callContext.call;n.id=t;const o=H.status.name();n.status=o;const r="calleeIds"in e?e.calleeIds:[e.calleeId],a=yield M.Member.i.getData(...r);n.callees=r.map((t=>new j(t,a.get(t),"Ringing")));const c=lt.createCallCommand(n,t,e);const l=(yield ht.sendRequest(c)).content.users;n.callees=n.callees.filter((t=>!l.find((e=>e.userId===t.id&&e.busy))));l.every((t=>t.busy))?(gt.destroy(),s({code:400,content:"all callees are busy"})):i()}catch(t){console.warn("Call failed",t),gt.destroy(),s(t)}}))))}onRing(e){return t(this,void 0,void 0,(function*(){vt.setStatus(new Rt),gt.ring(e);let t=new Et;H.setStatus(t),t.startRing(e)}))}accept(){return Promise.reject("No active call to accept.")}end(){}onUserRang(t){}onUserAcceptPacket(t){}onUserQuit(t){}onRTCTimeout(){}onRTCRemoteFlow(t){}onGoEasyDisconnected(){}muteMic(){}toggleSpeaker(){}muteCamera(){}switchCamera(){}play(t){}onRTCRemoteCameraChanged(t){}onRTCRemoteMicChanged(t){}}class vt{static setStatus(t){this.status=t}}vt.status=new ft;class gt{static ring(t){const e=new V;e.id=t.callId,e.time=t.time,e.mediaType=t.type,e.groupId=t.groupId,e.speakerOn=!0,this.callContext=new K(e)}static initPrivateCall(e){return t(this,void 0,void 0,(function*(){const t=new V;t.mediaType=e.mediaType,t.speakerOn=!0,t.caller=new j(M.Socket.user().id,M.Socket.user().data,"Dialing"),this.callContext=new K(t)}))}static initGroupCall(t){if(t.calleeIds.length>8)throw new Error("calleeIds can not more than 8");const e=new V;e.groupId=t.groupId,e.mediaType=t.mediaType,e.speakerOn=!0,e.caller=new j(M.Socket.user().id,M.Socket.user().data,"Dialing"),this.callContext=new K(e)}static updateMemberStatus(t,e){const i=this.callContext.call;[...i.callees,i.caller].find((e=>e.id===t)).status=e}static muteMemberMic(t,e){const i=this.callContext.call,s=[...i.callees,i.caller].find((e=>e.id===t));s.micMuted&&e||!s.micMuted&&!e||(s.micMuted=e)}static muteMemberCamera(t,e){const i=this.callContext.call,s=[...i.callees,i.caller].find((e=>e.id===t));s.cameraMuted&&e||!s.cameraMuted&&!e||(s.cameraMuted=e)}static toggleSpeaker(t){this.callContext.call.speakerOn=t}static isCaller(){return this.callContext.call.caller.id===M.Socket.user().id}static destroyWithEvent(t,e=M.Socket.user()){this.updateMemberStatus(e.id,"Quit"),F.fire(G.USER_QUIT,{user:e,reason:t}),F.fire(G.CALL_ENDED),this.destroy()}static destroy(){var t;null===(t=ut.vendorClient)||void 0===t||t.destroy(),this.callContext=null,H.clearStatus(),vt.setStatus(new ft)}}class yt{constructor(){x.i.on(e.RTC_LOST,(()=>this.onRTCLost())),x.i.on(e.RTC_RECONNECT,(()=>this.onRTCReconnect()))}onRTCLost(){gt.callContext&&(this.rtcLostTimeoutId=setTimeout((()=>{x.i.fire(e.RTC_TIMEOUT)}),1e4))}onRTCReconnect(){clearTimeout(this.rtcLostTimeoutId)}onGoEasyLost(){this.goeasyLostTimeoutId=setTimeout((()=>{x.i.fire(e.GOEASY_TIMEOUT)}),2e4)}onGoEasyReconnected(){clearTimeout(this.goeasyLostTimeoutId)}}class kt{static init(){this.instance=new kt}static i(){if(this.instance)return this.instance;throw new Error("Please connect GoEasy first.")}constructor(){this.rtcStabilizer=new yt,ut.init(),Tt.initNotificationAssembler(),M.Socket.onMessage(z.RTC_PKT,this.onServerPacket.bind(this)),x.i.on(e.RECEIVED_RTC_REMOTE_FLOW,this.onRTCRemoteFlow.bind(this)),x.i.on(e.RTC_TIMEOUT,this.onRTCTimeout.bind(this)),x.i.on(e.RTC_REMOTE_MIC_CHANGED,this.onRTCRemoteMicChanged.bind(this)),x.i.on(e.RTC_REMOTE_CAMERA_CHANGED,this.onRTCRemoteCameraChanged.bind(this)),M.Socket.on(M.Socket.EVENT.LOST,this.onGoEasyDisconnected.bind(this)),M.Socket.on(M.Socket.EVENT.DISCONNECT,this.onGoEasyDisconnected.bind(this))}on(t,e){F.on(t.toString(),e)}off(t,e){F.off(t.toString(),e)}call(e){return t(this,void 0,void 0,(function*(){return vt.status.call(e)}))}groupCall(e){return t(this,void 0,void 0,(function*(){return vt.status.call(e)}))}accept(){return vt.status.accept()}getCurrentCall(){var t;return(null===(t=gt.callContext)||void 0===t?void 0:t.call)||null}end(){vt.status.end()}muteMic(t){vt.status.muteMic(t)}toggleSpeaker(t){vt.status.toggleSpeaker(t)}muteCamera(t){vt.status.muteCamera(t)}switchCamera(){vt.status.switchCamera()}play(t){vt.status.play(t)}onServerPacket(t){vt.status.onServerPacket(t.name,t.data)}onRTCTimeout(){vt.status.onRTCTimeout()}onRTCRemoteFlow(t){vt.status.onRTCRemoteFlow(t)}onGoEasyDisconnected(){vt.status.onGoEasyDisconnected()}onRTCRemoteMicChanged(t){vt.status.onRTCRemoteMicChanged(t)}onRTCRemoteCameraChanged(t){vt.status.onRTCRemoteCameraChanged(t)}}class bt{static init(t){W.init(t)}static call(t){return kt.i().call(t)}static groupCall(t){return kt.i().groupCall(t)}static accept(){return kt.i().accept()}static currentCall(){return kt.i().getCurrentCall()}static end(){kt.i().end()}static muteMic(t){kt.i().muteMic(t)}static toggleSpeaker(t){kt.i().toggleSpeaker(t)}static muteCamera(t){kt.i().muteCamera(t)}static switchCamera(){kt.i().switchCamera()}static play(t){kt.i().play(t)}static on(t,e){kt.i().on(t,e)}static off(t,e){kt.i().off(t,e)}}bt.EVENT=G;export{bt as default};