@hysc/meeting 5.0.92 → 5.0.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/index.js +1 -1
- package/esm/index.js.map +2 -2
- package/package.json +5 -5
- package/umd/index.js +1 -1
package/umd/index.js
CHANGED
|
@@ -822,4 +822,4 @@
|
|
|
822
822
|
/*!**************************!*\
|
|
823
823
|
!*** ./src/util/util.ts ***!
|
|
824
824
|
\**************************/
|
|
825
|
-
/*! exports provided: generateUUID, callbackToPromise, getAudioContext, createAudioMeter, createVolumeMeter, parseVloudStreamOptions, timestamp, resumeContext, getEmptyVloudStats, timestampMillisecond */function(e,t,r){r.r(t),r.d(t,"generateUUID",(function(){return o})),r.d(t,"callbackToPromise",(function(){return a})),r.d(t,"getAudioContext",(function(){return u})),r.d(t,"createAudioMeter",(function(){return d})),r.d(t,"createVolumeMeter",(function(){return l})),r.d(t,"parseVloudStreamOptions",(function(){return h})),r.d(t,"timestamp",(function(){return m})),r.d(t,"resumeContext",(function(){return p})),r.d(t,"getEmptyVloudStats",(function(){return f})),r.d(t,"timestampMillisecond",(function(){return g}));var i=r(/*! bjy-common/src/function/execute */"./node_modules/bjy-common/src/function/execute.ts"),n=r(/*! bjy-common/src/function/nextTick */"./node_modules/bjy-common/src/function/nextTick.ts"),s=r(/*! bjy-common/src/function/getTimestamp */"./node_modules/bjy-common/src/function/getTimestamp.ts");function o(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))}function a(e,t,r,s=!0){return new Promise(((o,a)=>{s&&t.push((function(e){o(e)})),t.push((function(e){a(e)})),Object(i.default)(e,r,t),s||Object(n.default)((()=>{o()}))}))}let c;function u(){if(c)return c;let e=window.AudioContext||window.webkitAudioContext;return c=new e,c}function d(e,t=.98,r=.95,i=750){const n=e.createScriptProcessor(2048,1,1);return n.onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0),r=t.length;let i,s=0;for(let e=0;e<r;e++)i=t[e],Math.abs(i)>=n.clipLevel&&(n.clipping=!0,n.lastClip=window.performance.now()),s+=i*i;const o=Math.sqrt(s/r);n.volume=Math.max(o,n.volume*n.averaging)},n.clipping=!1,n.lastClip=0,n.volume=0,n.clipLevel=t,n.averaging=r,n.clipLag=i,n.connect(e.destination),n.checkClipping=()=>!!n.clipping&&(n.lastClip+n.clipLag<window.performance.now()&&(n.clipping=!1),n.clipping),n.shutdown=()=>{n.disconnect(),e.close(),n.onaudioprocess=null},n}function l(e,t){if(e._volumeMeter&&e._volumeMeter.disconnect(),t&&"audio"===t.kind){let r=new MediaStream;r.addTrack(t);let i=u(),n=i.createMediaStreamSource(r);e._volumeMeter=d(i),n.connect(e._volumeMeter)}e.getAudioLevel=()=>e._volumeMeter?e._volumeMeter.volume:0}function h(e,t){return e.audioSource||e.videoSource?{audio:!!e.audioSource,video:!!e.videoSource}:e.screen?{audio:!!e.audio,video:!0,screen:!0,fps:t.frameRate}:{audio:!!e.audio,video:!!e.video}}function m(){return Math.floor((new Date).getTime()/1e3)}function p(){return function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){c&&(yield c.resume())}))}function f(){return{bandwidth:{upload:0,download:0},bitrate:{audio:{upload:0,download:0},video:{upload:0,download:0}},packetLoss:{audio:{upload:0,download:0},video:{upload:0,download:0}},resolution:{width:0,height:0},framerate:0,audioLevel:0,transport:[{ip:"",type:"",localIp:"",localCandidateType:"",remoteCandidateType:"",networkType:"",rtt:0}],quality:{audio:{jitter:0,interruptionCount:0,interruptionDuration:0},video:{jitter:0,interruptionCount:0,interruptionDuration:0}},statistics:{audio:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0},video:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0,framesEncoded:0,framesDecoded:0,framesSent:0},bweforvideo:{googAvailableReceiveBandwidth:0,googAvailableSendBandwidth:0,googRetransmitBitrate:0,googTransmitBitrate:0,googTargetEncBitrate:0},ice:{packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0}},cpu:{appCpu:0,systemCpu:0}}}function g(e=0){return Object(s.default)()+e}}})},BRTC$2.exports=factory();var BRTC=getDefaultExportFromCjs(BRTC$2.exports),BRTC$1=_mergeNamespaces$1({__proto__:null,default:BRTC},[BRTC$2.exports]),BoomCoreErrorCode$1;class BoomError$2 extends Error{constructor(e,t,r){let i;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,i="string"==typeof t?t:JSON.stringify(t),this.message=i,r&&(this.name=r)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}}!function(e){e[e.BloudLock=28]="BloudLock",e[e.ShareScreenNoPermission=100]="ShareScreenNoPermission",e[e.ShareScreenCanceled=101]="ShareScreenCanceled",e[e.ShareScreenOtherError=102]="ShareScreenOtherError",e[e.ShareScreenContentHintError=103]="ShareScreenContentHintError",e[e.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",e[e.BrtcShareSigError=105]="BrtcShareSigError",e[e.ToggleShareScreenError=106]="ToggleShareScreenError",e[e.BrtcCreateStreamError=107]="BrtcCreateStreamError",e[e.BrtcSubscribeError=108]="BrtcSubscribeError",e[e.BrtcPublishError=109]="BrtcPublishError",e[e.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",e[e.BrtcUnPublishError=111]="BrtcUnPublishError",e[e.RepeatJoinError=112]="RepeatJoinError",e[e.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",e[e.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",e[e.JoinUserInfoError=115]="JoinUserInfoError",e[e.JoinTypeError=116]="JoinTypeError",e[e.JoinBrtcError=117]="JoinBrtcError",e[e.JoinBloudError=118]="JoinBloudError",e[e.UpdateCustomStatsError=119]="UpdateCustomStatsError",e[e.CreateBloudError=120]="CreateBloudError"}(BoomCoreErrorCode$1||(BoomCoreErrorCode$1={}));const ShareScreenNoPermission=new BoomError$2(BoomCoreErrorCode$1.ShareScreenNoPermission,"没有打开共享屏幕录制权限","no share permission"),ShareScreenCanceled=new BoomError$2(BoomCoreErrorCode$1.ShareScreenCanceled,"取消共享屏幕","cancel share"),ShareScreenOtherError=e=>new BoomError$2(BoomCoreErrorCode$1.ShareScreenOtherError,e);new BoomError$2(BoomCoreErrorCode$1.ShareScreenContentHintError,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed");const ShareScreenClientJoinedError=new BoomError$2(BoomCoreErrorCode$1.ShareScreenClientJoinedError,"共享屏幕brtc client入会失败","share client join failed"),BrtcShareSigError=new BoomError$2(BoomCoreErrorCode$1.BrtcShareSigError,"brtcShareSig为空","brtc share sig is empty"),ToggleShareScreenError=e=>new BoomError$2(BoomCoreErrorCode$1.ToggleShareScreenError,e,"toggle share has error"),RepeatJoinError$1=new BoomError$2(BoomCoreErrorCode$1.RepeatJoinError,"正在 join,请勿重复调用","repeat join error"),ProxiesUrlTypeError=new BoomError$2(BoomCoreErrorCode$1.ProxiesUrlTypeError,"proxies url 必须为字符串","get bloud proxies param error"),getBloudProxiesUrlError=e=>new BoomError$2(BoomCoreErrorCode$1.getBloudProxiesUrlError,e,"get bloud proxies error"),JoinUserInfoError=new BoomError$2(BoomCoreErrorCode$1.JoinUserInfoError,"userinfo传递错误,请检查"),JoinTypeError=new BoomError$2(BoomCoreErrorCode$1.JoinTypeError,"type传递错误,请检查"),JoinBrtcError=e=>new BoomError$2(BoomCoreErrorCode$1.JoinBrtcError,e,"join brtc error"),BrtcCreateStreamError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcCreateStreamError,"brtc 创建本地流失败"),BrtcPublishError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcPublishError,e,"brtc pub failed"),BrtcUnsubscribeError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcUnsubscribeError,e,"brtc sub failed"),BrtcUnPublishError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcUnsubscribeError,e,"brtc unpub failed");var BoomMeetingErrorCode$1,StreamErrorMap$1;!function(e){e[e.BmJoinError=200]="BmJoinError",e[e.BMLeaveError=201]="BMLeaveError",e[e.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",e[e.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",e[e.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",e[e.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",e[e.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",e[e.BmChangeMasterError=207]="BmChangeMasterError",e[e.BmUpdateManagerError=208]="BmUpdateManagerError",e[e.BmEvictUserError=209]="BmEvictUserError",e[e.BmUpdateUserError=210]="BmUpdateUserError",e[e.BmSetAudioOffError=211]="BmSetAudioOffError",e[e.BmSetVideoOffError=212]="BmSetVideoOffError",e[e.BmSetMsgOffError=213]="BmSetMsgOffError",e[e.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",e[e.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",e[e.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",e[e.BmCheckDeviceError=217]="BmCheckDeviceError"}(BoomMeetingErrorCode$1||(BoomMeetingErrorCode$1={})),function(e){e[e.createStream=1302]="createStream",e[e.noCameraDevice=1303]="noCameraDevice",e[e.noMicroDevice=1304]="noMicroDevice",e[e.noSpeakerDevice=1305]="noSpeakerDevice",e[e.openCamera=1301]="openCamera",e[e.cameraNotAuth=1314]="cameraNotAuth",e[e.cameraOccupy=1315]="cameraOccupy",e[e.openMicro=1302]="openMicro",e[e.micNotAuth=1317]="micNotAuth",e[e.micOccupy=1319]="micOccupy",e[e.streamDisconnected=1320]="streamDisconnected",e[e.syncFail=1321]="syncFail",e[e.getStreamFail=1322]="getStreamFail",e[e.streamConnectError=1323]="streamConnectError",e[e.streamReconnectSuccess=1324]="streamReconnectSuccess",e[e.streamReconnectFailed=1325]="streamReconnectFailed",e[e.shareStreamConnectError=1326]="shareStreamConnectError",e[e.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",e[e.shareStreamConnectFailed=1328]="shareStreamConnectFailed"}(StreamErrorMap$1||(StreamErrorMap$1={}));class BCClient{constructor(e){this.emitters=[],this.name="",this.type=SING_MODE,this.appId="",this.brtcAppId="",this.roomId="",this.tarCreate=!1,this.userinfo={},this.userId="",this.isJoining=!1,this.collection="",this.limit=0,this.token="",this.customToken="",this.create=!1,this.host="",this.getProxiesUrl="",this.secret="",this.enableRace=!1,this.disableMediaEngine=!1,this.roomType=1,this.audioCodec="opus",this.codec="h264",this.hasBloudJoined=!1,this.brtcSig="",this.shareContentHint="detail",this.identity="",this.isBig="0",this.brtcJoined=!1,this.joinReady=!1,this.joinBrtc=()=>new Promise(((e,t)=>{this.brtcClient.join(this.roomId,this.userId,this.sig).then((()=>(info$1("join brtc succeed"),this.brtcJoined=!0,e(!0)))).catch((e=>(console.log("brtc入会失败01",e),this.isJoining=!1,t(JoinBrtcError(e.message)))))})),this.joinBloud=()=>new Promise(((e,t)=>{SingleMode.singleModeJoin(this,(()=>this.addBloudEvent())).then((()=>(info$1("join bloud succeed"),this.hasBloudJoined=!0,e(!0)))).catch((e=>(error$2("bloud入会失败02","",[e]),this.isJoining=!1,t(e))))})),this.handleBloudSharePubFailed=()=>{error$2("bloud share stream unpublish failed, interval retry");let e=setInterval((()=>__awaiter$1(this,void 0,void 0,(function*(){clearInterval(e),yield this.bloudShareScreenStream.unpublish().then((()=>{this.bloudShareScreenStream=void 0})).catch((()=>{this.handleBloudSharePubFailed()}))}))),2e3)},this.emitter=new Emitter(!0),addEvent2Bloud(),window.BRTC=BRTC$1}setShareSig(e){this.brtcShareSig=e}clearObject(){this.client&&(this.client.close(),this.client.removeAllListeners()),this.client=null,this.collection&&(this.collection.close(),this.collection=null)}join(e){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise(((t,r)=>__awaiter$1(this,void 0,void 0,(function*(){if(this.isJoining)return Promise.reject(RepeatJoinError$1);if(this.client)return Promise.reject(RepeatJoinError$1);if("string"!=typeof e.getProxiesUrl)return Promise.reject(ProxiesUrlTypeError);if(!e.userinfo||e.userinfo&&"object"!=typeof e.userinfo)return Promise.reject(JoinUserInfoError);if("number"!=typeof e.type||1!==e.type&&2!==e.type)return Promise.reject(JoinTypeError);if(this.userId=e.userId,this.roomId=e.room,this.roomType=e.roomType,this.collection=e.collection,this.userinfo=e.userinfo,this.getProxiesUrl=e.getProxiesUrl,this.appId=e.appId,this.brtcAppId=e.brtcAppId,this.type=e.type,this.tarCreate=e.create,this.limit=e.limit,this.secret=e.secret,this.enableRace=e.enableRace,this.token=e.token,this.customToken=e.customToken,this.name=e.name,this.brtcSig=e.sig,this.identity=e.identity,this.isBig=e.is_big,this.sig=e.sig,Global.token=e.token,this.isJoining=!0,this.type===SING_MODE&&(yield SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))),this.type===MIX_MODE){this.disableMediaEngine=!0;try{this.brtcClient=BRTC$2.exports.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,audioLevelInterval:200,roomType:"big",silence:!0}),this.createShareBrtcClient(),this.addBrtcEvent(),this.fire("brtc-bound",!0),BRTC$2.exports.setVTRequestTimeout(5),yield this.joinRoom().then((()=>(this.isJoining=!1,this.fire(BCEvent$2.JOIN_READY),t(!0)))).catch((e=>(error$2("join room error","",this.userId,[JSON.stringify(e)]),r(e))))}catch(e){return this.isJoining=!1,error$2("join room error",LOGGER_TAG_CLIENT$1,this.userId,[e]),r(e)}}}))))}))}joinRoom(){return new Promise(((e,t)=>{let r=!1,i=!1;this.joinBloud().then((()=>{if(r=!0,i)return e(!0)})).catch((e=>t(e))),this.joinBrtc().then((()=>{if(i=!0,r)return e(!0)})).catch((e=>t(e)))}))}createShareBrtcClient(){return this.shareBrtcClient||(this.shareBrtcClient=BRTC$2.exports.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,roomType:"big",silence:!0}),this.shareBrtcClient.on("error",(e=>{this.fire("share-brtc-error",e)}))),this.shareBrtcClient}_getBloudProxiesUrl(e){return new Promise(((t,r)=>{request({url:`${this.getProxiesUrl}/proxies?token=${e}`}).then((r=>{t({proxies:r.proxies,token:e})})).catch((e=>{r(getBloudProxiesUrlError(e))}))}))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}changeMaster(e,t=!1){return this.client.changeMaster(e,t).catch((e=>e))}getMaster(){return this.client.getMaster()}syncUser(e){return this.client.syncUser(e)}getCreator(){return this.client.getCreator()}getName(){return this.client.getName()}close(){var e;return __awaiter$1(this,void 0,void 0,(function*(){this.leaveBrtcRoom(),null===(e=this.client)||void 0===e||e.close(),this.leaveShare()}))}getMsgSeq(){return this.client.getMsgSeq()}evictUser(e,t){return this.client.evictUser2(this.getMaster(),e,t)}updateUser(e,t){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.updateUser(e,t)}))}getLimits(){return this.client.getLimits()}getSwitch(){return this.client.getSwitch()}syncRoom(){return this.client.syncRoom()}update(e){return this.client.update(e)}getUsers(e,t,r){return __awaiter$1(this,void 0,void 0,(function*(){let{participants:i,total:n}=yield this.client.getUsers(e,t,r),s=new Map;return i.forEach((e=>{let t=BCUser.toUser(e,this.type);s.set(t.userId,t)})),{users:s,total:n}}))}updateStream(e,t,r){return this.client.updateStream(e,t,r)}getUsersList(e,t,r,i){return __awaiter$1(this,void 0,void 0,(function*(){let{participants:n,total:s,pageIndex:o}=yield this.client.getUsersList(e,r,t,i),a=new Map;return n.forEach((e=>{let t=BCUser.toUser(e,this.type);a.set(t.userId,t)})),{users:a,total:s,pageIndex:o}}))}getTotalUsers(){return this.client.getTotalUsers()}sendMessage(e,t){return this.client.sendMessage(e,t)}customMessage(e,t){return this.client.customMessage(e,t)}getMessages(e,t){return this.client.getMessages(e,t)}getLocalParticipant(){var e;return null===(e=this.client)||void 0===e?void 0:e.getLocalParticipant()}getAudioOff(){return this.client.getAudioOff()}getSelfOpenAudio(){return this.client.getSelfOpenAudio()}getVideoOff(){return this.client.getVideoOff()}getMsgOff(){return this.client.getMsgOff()}getLock(){return this.client.getLock()}getRoomInfo(){let e=Object.assign({},this.client.options);return delete e.token,e}setAudioOff(e,t){return this.client.setAudioOff(e,t)}setVideoOff(e){return this.client.setVideoOff(e)}setMsgOff(e){return this.client.setMsgOff(e)}setSwitch(e){return this.client.setSwitch(e)}setLock(e){return this.client.setLock(e)}publish(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.publish(e).catch((e=>Promise.reject(BrtcPublishError(JSON.stringify(e)))))}))}unpublish(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.unpublish(e).catch((e=>Promise.reject(BrtcUnPublishError(JSON.stringify(e)))))}))}subscribe(e,t={audio:!0,video:!0}){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.subscribe(e,t).catch((e=>Promise.reject(e)))}))}unsubscribe(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.unsubscribe(e).catch((e=>Promise.reject(BrtcUnsubscribeError(JSON.stringify(e)))))}))}addBloudEvent(){let e=this,t=BloudParameterHandlerMap;each$1(bloudEvents,(r=>{!function(r,i){e.client.on(r,(function(){let r=execute(t[i],e,toArray(arguments));e.fire(i,r)}))}(r,r)}))}addBrtcEvent(){const e=this;each$1(BrtcEvents,(t=>{var r;r=t,e.brtcClient.on(r,(t=>{e.fire(r,t)}))}))}clearBrtcEvent(){this.brtcClient.off()}leave(){return __awaiter$1(this,void 0,void 0,(function*(){return console.log("离开会议","userId =>",this.userId,"roomId =>",this.roomId,"userInfo =>",this.userinfo),yield SingleMode.singleModeLeave(this),this.leaveBrtcRoom()}))}leaveBrtcRoom(){return __awaiter$1(this,void 0,void 0,(function*(){if(console.log("离开brtc调用堆栈!!!!!"),this.brtcClient&&(this.brtcClient.off(),yield this.brtcClient.leave(),yield this.brtcClient.destroy(),this.brtcClient=null),this.shareBrtcClient){try{this.shareBrtcClient.off(),yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(),this.shareBrtcClient=null}}))}leaveShare(){return __awaiter$1(this,void 0,void 0,(function*(){if(this.shareBrtcClient){try{yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(),this.shareBrtcClient=null}}))}getEventList(){return BCEvent$2}createRecorder(e){return this.client.Recorder(e)}createSpeakerDetector(){return this.client.SpeakerDetector()}createLocalStream(e,t){return __awaiter$1(this,void 0,void 0,(function*(){BRTC$2.exports.isSmallStreamSupported()?yield this.brtcClient.enableSmallStream():error$2("simulcast is not supported"),this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return BRTC$2.exports.createStream(e)}catch(e){return Promise.reject(e)}}))}createPBLocalStream(e,t){return __awaiter$1(this,void 0,void 0,(function*(){this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return BRTC$2.exports.createStream(e)}catch(e){return Promise.reject(BrtcCreateStreamError(JSON.stringify(e)))}}))}creteBloudLocalStream(e,t){return this.client.Stream({audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t,screen:!1})}createBloudScreenStream(e,t){return this.client.Stream({screen:!0,audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t})}updateCustomStats(e,t=!1){return info$1("updateCustomStats","updateCustomStats","",[" customstats => ",JSON.stringify(e),"replace => ",t]),this.client.updateCustomStats({customStats:e},t)}getCustomStats(){var e;return null===(e=this.client)||void 0===e?void 0:e.getCustomStats()}getDuration(){var e;return null===(e=this.client)||void 0===e?void 0:e.duration}toggleShareScreen(e,t,r){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise(((t,i)=>__awaiter$1(this,void 0,void 0,(function*(){if(e)try{let e;e=r?yield BRTC$2.exports.createStream({video:!!r.videoSource,audio:!!r.audioSource,videoSource:r.videoSource,audioSource:r.audioSource,screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail",sourceType:"screen"}):yield BRTC$2.exports.createStream({screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail",sourceType:"screen"});const i="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:i.frameRate,bitrate:i.bitrate});try{yield e.init()}catch(e){throw error$2("brtc stream init failed","","",[e]),new Error(e)}yield this.publishShareStream(e),t(!0)}catch(e){String(e).includes("Permission denied by system")?(error$2("没有打开共享屏幕录制权限","","this.userId"),i(ShareScreenNoPermission)):String(e).includes("Permission denied")?(info$1("点击了取消共享屏幕","",this.userId,["nickname =>",this.name]),i(ShareScreenCanceled)):(error$2("开启共享屏幕失败","","",[JSON.stringify(e)]),i(ShareScreenOtherError("开启共享屏幕失败,请重试")))}else yield this.unpublishShareStream(),t(!0)}))))}))}shareHTMLMedia(e,t){return __awaiter$1(this,void 0,void 0,(function*(){if(e&&t)try{const e=BRTC$2.exports.createStream({audio:t.audio,video:t.video,videoSource:t.videoSource,audioSource:t.audioSource,videoHint:"motion",sourceType:"screen"}),r="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:r.frameRate,bitrate:r.bitrate}),yield e.init(),yield this.publishShareStream(e)}catch(e){return Promise.reject(ToggleShareScreenError(JSON.stringify(e)))}e||(yield this.unpublishShareStream())}))}publishShareStream(e){return __awaiter$1(this,void 0,void 0,(function*(){if(this.shareBrtcClient||this.createShareBrtcClient(),!this.brtcShareSig)return console.error("brtcShareSig为空"),Promise.reject(BrtcShareSigError);{yield this.shareBrtcClient.join(this.roomId,`${this.userId}_screen`,this.brtcShareSig).catch((e=>(error$2("共享屏幕入会失败","","",[JSON.stringify(e),this.brtcShareSig]),Promise.reject(ShareScreenClientJoinedError)))),e.on("video-track-ended",(()=>{this.handleShareStreamEnded()})),yield this.shareBrtcClient.publish(e).catch((t=>(error$2("共享屏幕流推流失败","","",["err =>",JSON.stringify(t)]),e.destroy(),Promise.reject(ShareScreenOtherError("共享屏幕流推流失败,请重试"))))),this.shareBrtcClient.on("sync-room-completed",(()=>{this.fire(BCEvent$2.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));let t=e.getAudioOn(),r=e.getVideoOn();this.shareScreenStream=e,this.createAndPubBloudShareStream(t,r),setTimeout((()=>{Promise.resolve(!0)}),200)}}))}createAndPubBloudShareStream(e,t){return this.bloudShareScreenStream=this.createBloudScreenStream({audio_enable:e,video_enable:t},`${this.userId}_screen`),this.bloudShareScreenStream.publish({video_enable:t,audio_enable:e})}replaceShareStreamVideoTrack(e){this.shareScreenStream?this.shareScreenStream.replaceTrack(e):error$2("当前没有开启共享屏幕,无法替换track")}unpublishShareStream(){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise((e=>__awaiter$1(this,void 0,void 0,(function*(){var t,r;try{yield this.shareBrtcClient.unpublish(this.shareScreenStream).catch((e=>{error$2("取消共享屏幕出错","","",[JSON.stringify(e)])})),yield null===(t=this.shareBrtcClient)||void 0===t?void 0:t.leave().catch((e=>{error$2("shareBrtcClient leave error","","",[JSON.stringify(e)])})),null===(r=this.shareScreenStream)||void 0===r||r.destroy(),this.shareScreenStream=void 0,yield this.bloudShareScreenStream.unpublish().then((()=>{this.bloudShareScreenStream=void 0})).catch((e=>{error$2("bloud share stream unpublish failed"),this.handleBloudSharePubFailed()}))}catch(e){console.log("取消共享兼容处理",e)}e(!0)}))))}))}setShareScreenContentHint(e){this.shareContentHint=e}releaseRoom(){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.release()}))}handleShareStreamEnded(){setTimeout((()=>{var e;this.shareScreenStream&&"live"===(null===(e=this.shareScreenStream.getVideoTrack())||void 0===e?void 0:e.readyState)||(error$2("share stream video track ended"),this.fire("toggle-screen-share",!1))}),2e3)}setCustomUrl(e){BRTC$2.exports.setCustomUrl(e)}bloudReconnect(){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.leave(),yield SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))}))}searchUsers(e,t,r){return __awaiter$1(this,void 0,void 0,(function*(){const{participants:i}=yield this.client.searchUsers(e,t,r);let n=new Map;return i.forEach((e=>{let t=BCUser.toUser(e,this.type);n.set(t.userId,t)})),{users:n}}))}queryUsers(e){return __awaiter$1(this,void 0,void 0,(function*(){const{participants:t}=yield this.client.queryUsers(e);let r=new Map;return t.forEach((e=>{let t=BCUser.toUser(e,this.type);r.set(t.userId,t)})),{users:r}}))}handleBloudRejoin(){return __awaiter$1(this,void 0,void 0,(function*(){return SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))}))}}const PLAYER_STATE_CHANGED="player-state-changed";class Player extends Emitter{constructor(e,t){super(),this.playEvent=()=>{this.videoStatus="PLAYING",info$1("stream big video playing",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.pauseEvent=()=>{this.videoStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.videoStatus,reason:"pause"}]),info$1("stream big video pause",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.stalledEvent=()=>{this.videoStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.videoStatus,reason:"stalled"}]),info$1("stream big video stalled",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.element=e,this.options=t,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor="#202020",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!this.video){if(!this.stream.getVideoTrack())return;this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.video.style.objectFit=this.options.fit,this.video.id=`video_${this.stream.getStreamId()}_big`,this.container.appendChild(this.video),this.video.addEventListener("playing",this.playEvent),this.video.addEventListener("pause",this.pauseEvent),this.video.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e,this.videoStatus="STOPPED"}play(e){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e,this.container.id=`player_${e.getStreamId()}_big_container`,this.stream.hasVideo()&&this.playVideo();try{this.video&&(yield this.video.play())}catch(e){error$2("player play video failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e;try{this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasVideo()&&t&&(yield this.video.play())}catch(e){error$2("player replay video failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}destroy(){this.video&&(this.video.removeEventListener("playing",this.playEvent),this.video.removeEventListener("pause",this.pauseEvent),this.video.removeEventListener("stalled",this.stalledEvent),this.video.style.display="none",this.video=null);try{this.container.style.display="none",this.element.removeChild(this.container)}catch(e){}this.container=null,debug$1("stream player destroy",LOGGER_TAG_PLAYER,this.stream.getUserId())}resume(){return __awaiter$1(this,void 0,void 0,(function*(){this.video&&(yield this.video.play()),debug$1("stream player resume",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){const e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}}function func$3(e){return typeof e===RAW_FUNCTION$2}class AudioPlayer extends Emitter{constructor(e,t){super(),this.audioLevel=1,this.playEvent=()=>{this.audioStatus="PLAYING",info$1("stream audio playing",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.pauseEvent=()=>{this.audioStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"pause"}]),info$1("stream audio pause",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.stalledEvent=()=>{this.audioStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"stalled"}]),info$1("stream audio stalled",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.element=e,this.options=t}get streamId(){return this.stream.getStreamId()}playAudio(){if(!this.audio){if(!this.stream.getAudioTrack())return;this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id=`audio_${this.stream.getStreamId()}_back`,this.element.appendChild(this.audio),this.stream.getAudioDeviceId()&&this.setSinkId(this.stream.getAudioDeviceId()),this.audio.volume=this.audioLevel,this.audio.addEventListener("playing",this.playEvent),this.audio.addEventListener("pause",this.pauseEvent),this.audio.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e,this.audioStatus="STOPPED"}setSinkId(e){return __awaiter$1(this,void 0,void 0,(function*(){this.audio&&func$3(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audioLevel=e,this.audio.volume=e)}play(e){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e,this.stream.hasAudio()&&this.playAudio();try{this.audio&&(yield this.audio.play())}catch(e){error$2("player play audio failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e;try{this.stream.hasAudio()&&r&&this.playAudio(),this.stream.hasAudio()&&r&&(yield this.audio.play())}catch(e){error$2("player replay audio failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}debug$1("stream replay",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){var e,t,r;null===(e=this.audio)||void 0===e||e.removeEventListener("playing",this.playEvent),null===(t=this.audio)||void 0===t||t.removeEventListener("pause",this.pauseEvent),null===(r=this.audio)||void 0===r||r.removeEventListener("stalled",this.stalledEvent);try{this.element.removeChild(this.audio)}catch(e){}this.audio=null,debug$1("stream player destroy",LOGGER_TAG_PLAYER,this.stream.getUserId())}resume(){return __awaiter$1(this,void 0,void 0,(function*(){this.audio?(yield this.audio.play(),info$1("stream player resume",LOGGER_TAG_PLAYER,this.stream.getUserId())):error$2("try resume audio play, but, audio not exits",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}}const enumAudioInputDevices=BRTC$2.exports.enumAudioInputDevices,enumAudioOutputDevices=BRTC$2.exports.enumAudioOutputDevices,enumVideoDevices=BRTC$2.exports.enumVideoDevices,getPermissions=BRTC$2.exports.getPermissions,checkSystemSupport=BRTC$2.exports.checkSystemSupport,createStream=BRTC$2.exports.createStream;class BoomError$1 extends Error{constructor(e,t,r,i){super(),this.code=e,this.error=r,this.BoomErrorFlag=!0,this.eName=i,this.message=t}static instanceOf(e){return!(!e||!e.BoomErrorFlag)}getCode(){return this.code}}const LOCAL_ERROR=1e3,INVALID_PARAMETER=1001,INVALID_OPERATION=1002,CLIENT_BANNED=4005,USER_NOT_EXIT=9001,DEBUG=1,WARN=3,EMPTY_FUNCTION=function(){};function formatLog$1(e,t,r,i){let n=[];return r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function info(e,t,r,i=[]){i.unshift(formatLog$1("INFO",e,t,r)),console.log(...i)}function warn(e,t,r,i=[]){i.unshift(formatLog$1("WARN",e,t,r)),console.log(...i)}function error$1(e,t,r,i=[]){i.unshift(formatLog$1("ERROR",e,t,r)),console.log(...i)}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}/BRTC/.test(EMPTY_FUNCTION.toString());var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,r,i,n;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=__values(s),a=o.next();!a.done;a=o.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(isFunction(c))try{c()}catch(e){n=e instanceof UnsubscriptionError?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var d=__values(u),l=d.next();!l.done;l=d.next()){var h=l.value;try{execFinalizer(h)}catch(e){n=null!=n?n:[],e instanceof UnsubscriptionError?n=__spreadArray(__spreadArray([],__read(n)),__read(e.errors)):n.push(e)}}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}}if(n)throw new UnsubscriptionError(n)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&arrRemove(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),EMPTY_SUBSCRIPTION=Subscription.EMPTY;function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}var config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},timeoutProvider={setTimeout:function(e,t){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var n=timeoutProvider.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,__spreadArray([e,t],__read(r))):setTimeout.apply(void 0,__spreadArray([e,t],__read(r)))},clearTimeout:function(e){var t=timeoutProvider.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}var context=null;function errorContext(e){if(config.useDeprecatedSynchronousErrorHandling){var t=!context;if(t&&(context={errorThrown:!1,error:null}),e(),t){var r=context,i=r.errorThrown,n=r.error;if(context=null,i)throw n}}else e()}var Subscriber=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,isSubscription(t)&&t.add(r)):r.destination=EMPTY_OBSERVER,r}return __extends(t,e),t.create=function(e,t,r){return new SafeSubscriber(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),_bind=Function.prototype.bind;function bind(e,t){return _bind.call(e,t)}var ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,r,i){var n,s,o=e.call(this)||this;isFunction(t)||!t?n={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=i?i:void 0}:o&&config.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},n={next:t.next&&bind(t.next,s),error:t.error&&bind(t.error,s),complete:t.complete&&bind(t.complete,s)}):n=t;return o.destination=new ConsumerObserver(n),o}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var i=this,n=isSubscriber(e)?e:new SafeSubscriber(e,t,r);return errorContext((function(){var e=i,t=e.operator,r=e.source;n.add(t?t.call(n,r):r?i._subscribe(n):i._trySubscribe(n))})),n},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=getPromiseCtor(t))((function(t,i){var n=new SafeSubscriber({next:function(t){try{e(t)}catch(e){i(e),n.unsubscribe()}},error:i,complete:t});r.subscribe(n)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,r){var i;t.subscribe((function(e){return i=e}),(function(e){return r(e)}),(function(){return e(i)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}var ObjectUnsubscribedError=createErrorClass((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),Subject=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return __extends(t,e),t.prototype.lift=function(e){var t=new AnonymousSubject(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new ObjectUnsubscribedError},t.prototype.next=function(e){var t=this;errorContext((function(){var r,i;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var n=__values(t.currentObservers),s=n.next();!s.done;s=n.next()){s.value.next(e)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}}))},t.prototype.error=function(e){var t=this;errorContext((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}}))},t.prototype.complete=function(){var e=this;errorContext((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,i=r.hasError,n=r.isStopped,s=r.observers;return i||n?EMPTY_SUBSCRIPTION:(this.currentObservers=null,s.push(e),new Subscription((function(){t.currentObservers=null,arrRemove(s,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,i=t.thrownError,n=t.isStopped;r?e.error(i):n&&e.complete()},t.prototype.asObservable=function(){var e=new Observable;return e.source=this,e},t.create=function(e,t){return new AnonymousSubject(e,t)},t}(Observable),AnonymousSubject=function(e){function t(t,r){var i=e.call(this)||this;return i.destination=t,i.source=r,i}return __extends(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:EMPTY_SUBSCRIPTION},t}(Subject),BehaviorSubject=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return __extends(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,i=e._value;if(t)throw r;return this._throwIfClosed(),i},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Subject);Object.freeze({}),Object.freeze([]);const LOGGER_TAG_CLIENT="c";var MODEL_SORT_ENUM_STAND,MODEL_SORT_ENUM_ZY,STREAM_TYPE;!function(e){e[e.SCREEN_MASTER=0]="SCREEN_MASTER",e[e.SCREEN_MANAGER_AUDIO_VIDEO=1]="SCREEN_MANAGER_AUDIO_VIDEO",e[e.SCREEN_MANAGER_AUDIO=2]="SCREEN_MANAGER_AUDIO",e[e.SCREEN_MANAGER_VIDEO=3]="SCREEN_MANAGER_VIDEO",e[e.SCREEN_MANAGER=4]="SCREEN_MANAGER",e[e.SCREEN_GUEST_AUDIO_VIDEO=5]="SCREEN_GUEST_AUDIO_VIDEO",e[e.SCREEN_GUEST_AUDIO=6]="SCREEN_GUEST_AUDIO",e[e.SCREEN_GUEST_VIDEO=7]="SCREEN_GUEST_VIDEO",e[e.SCREEN_GUEST=8]="SCREEN_GUEST",e[e.SCREEN_COMMONUSER_AUDIO_VIDEO=9]="SCREEN_COMMONUSER_AUDIO_VIDEO",e[e.SCREEN_COMMONUSER_AUDIO=10]="SCREEN_COMMONUSER_AUDIO",e[e.SCREEN_COMMONUSER_VIDEO=11]="SCREEN_COMMONUSER_VIDEO",e[e.SCREEN_OTHER=12]="SCREEN_OTHER",e[e.MASTER=13]="MASTER",e[e.LOCAL=14]="LOCAL",e[e.MANAGER_AUDIO_VIDEO=15]="MANAGER_AUDIO_VIDEO",e[e.MANAGER_AUDIO=16]="MANAGER_AUDIO",e[e.MANAGER_VIDEO=17]="MANAGER_VIDEO",e[e.MANAGER=18]="MANAGER",e[e.RAISE_HAND=19]="RAISE_HAND",e[e.RAISE_AUDIO=20]="RAISE_AUDIO",e[e.RAISE_VIDEO=21]="RAISE_VIDEO",e[e.GUEST_AUDIO_VIDEO=22]="GUEST_AUDIO_VIDEO",e[e.GUEST_AUDIO=23]="GUEST_AUDIO",e[e.GUEST_VIDEO=24]="GUEST_VIDEO",e[e.GUEST=25]="GUEST",e[e.SIGNAL=26]="SIGNAL",e[e.COMMONUSER_AUDIO_VIDEO=27]="COMMONUSER_AUDIO_VIDEO",e[e.COMMONUSER_AUDIO=28]="COMMONUSER_AUDIO",e[e.COMMONUSER_VIDEO=29]="COMMONUSER_VIDEO",e[e.OTHER=30]="OTHER"}(MODEL_SORT_ENUM_STAND||(MODEL_SORT_ENUM_STAND={})),function(e){e[e.SCREEN=0]="SCREEN",e[e.RAISE_AUDIO=1]="RAISE_AUDIO",e[e.RAISE_VIDEO=2]="RAISE_VIDEO",e[e.LOCAL=3]="LOCAL",e[e.MASTER_AUDIO_VIDEO=4]="MASTER_AUDIO_VIDEO",e[e.MANAGER_AUDIO_VIDEO=5]="MANAGER_AUDIO_VIDEO",e[e.AUDIO_VIDEO=6]="AUDIO_VIDEO",e[e.MASTER_AUDIO=7]="MASTER_AUDIO",e[e.MANAGER_AUDIO=8]="MANAGER_AUDIO",e[e.AUDIO=9]="AUDIO",e[e.MASTER_VIDEO=10]="MASTER_VIDEO",e[e.MANAGER_VIDEO=11]="MANAGER_VIDEO",e[e.VIDEO=12]="VIDEO",e[e.MASTER=13]="MASTER",e[e.MANAGER=14]="MANAGER",e[e.GUEST=15]="GUEST",e[e.COMMON_USER=16]="COMMON_USER",e[e.SIGNAL=17]="SIGNAL",e[e.OTHER=18]="OTHER"}(MODEL_SORT_ENUM_ZY||(MODEL_SORT_ENUM_ZY={})),function(e){e[e.SUB_MAIN=0]="SUB_MAIN",e[e.SINGLE=1]="SINGLE",e[e.SHARE=2]="SHARE",e[e.OTHER=3]="OTHER"}(STREAM_TYPE||(STREAM_TYPE={}));const STREAM_SUFFIX_SCREEN="_screen",MOBILE_STREAM_SUFFIX_SCREEN="screen-",SIGNAL_SUFFIX="xinhao_",RECEIVE_SUBSCRIBE_MESSAGE="sub-message",USER_SORT_NUM_CHANGE="user-sort-num-change",BIND_ELEMENT="bind-element",HANDLE_STREAM_CONNECT_ERROR="stream-connect-error",RAISE_HAND="raise-hand",MANUAL_SUBSCRIPTION="manual-subscription",UNSUBSCRIBE_STREAM="unsubscribe-stream",CHANG_IS_GUEST="change-is-guest",BIND_BIG_ELEMENT="bind-big-element",NO_CONTAINER="no-container",MODEL_SORT_NUM_CHANGE="model-sort-num-change",ADD_PULL_USER="add-pull-user",SET_VOLUME="set-volume",ADD_AUDIO_PLAY="add-audio-play";function mitt(e){return{all:e=e||new Map,on:function(t,r){var i=e.get(t);i?i.push(r):e.set(t,[r])},off:function(t,r){var i=e.get(t);i&&(r?i.splice(i.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var i=e.get(t);i&&i.slice().map((function(e){e(r)})),(i=e.get("*"))&&i.slice().map((function(e){e(t,r)}))}}}class BoomEmitter{static getInstance(){return BoomEmitter.emitter||(BoomEmitter.emitter=mitt()),BoomEmitter.emitter}}function getSortNum(e){return 2===_selfSortType?sortZY(e):sortStand(e)}function sortStand(e){let t=MODEL_SORT_ENUM_STAND.OTHER;return e.isSharing?(t=e.isMaster?MODEL_SORT_ENUM_STAND.SCREEN_MASTER:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO_VIDEO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_VIDEO:e.isManager?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER:e.isCommonUser?e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_OTHER:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_GUEST,t):(e.isMaster?t=MODEL_SORT_ENUM_STAND.MASTER:e.isLocal?t=MODEL_SORT_ENUM_STAND.LOCAL:e.isManager?t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_VIDEO:MODEL_SORT_ENUM_STAND.MANAGER:e.raiseHand?t=MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?t=MODEL_SORT_ENUM_STAND.RAISE_AUDIO:e.raiseVideoHands?t=MODEL_SORT_ENUM_STAND.RAISE_VIDEO:e.isCommonUser?e.isSignal?t=MODEL_SORT_ENUM_STAND.SIGNAL:e.isCommonUser&&(t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.OTHER):t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_VIDEO:MODEL_SORT_ENUM_STAND.GUEST,t)}function sortZY(e){let t;return t=e.isToupingma?MODEL_SORT_ENUM_ZY.SCREEN:e.raiseHand?MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?MODEL_SORT_ENUM_ZY.RAISE_AUDIO:e.raiseVideoHands?MODEL_SORT_ENUM_ZY.RAISE_VIDEO:e.isLocal?MODEL_SORT_ENUM_ZY.LOCAL:e.isMaster&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO_VIDEO:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO_VIDEO:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.AUDIO_VIDEO:e.isMaster&&e.audioEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO:e.audioEnable?MODEL_SORT_ENUM_ZY.AUDIO:e.isMaster&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_VIDEO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_VIDEO:e.videoEnable?MODEL_SORT_ENUM_ZY.VIDEO:e.isMaster?MODEL_SORT_ENUM_ZY.MASTER:e.isManager?MODEL_SORT_ENUM_ZY.MANAGER:e.isCommonUser?MODEL_SORT_ENUM_ZY.COMMON_USER:e.isSignal?MODEL_SORT_ENUM_ZY.SIGNAL:MODEL_SORT_ENUM_ZY.GUEST,t}BoomEmitter.emitter=void 0,BoomEmitter.removeEmitter=()=>{var e,t,r,i,n,s,o,a,c,u,d,l,h,m;null===(e=BoomEmitter.emitter)||void 0===e||e.off(RECEIVE_SUBSCRIBE_MESSAGE),null===(t=BoomEmitter.emitter)||void 0===t||t.off(USER_SORT_NUM_CHANGE),null===(r=BoomEmitter.emitter)||void 0===r||r.off(HANDLE_STREAM_CONNECT_ERROR),null===(i=BoomEmitter.emitter)||void 0===i||i.off(RAISE_HAND),null===(n=BoomEmitter.emitter)||void 0===n||n.off(UNSUBSCRIBE_STREAM),null===(s=BoomEmitter.emitter)||void 0===s||s.off(MANUAL_SUBSCRIPTION),null===(o=BoomEmitter.emitter)||void 0===o||o.off(CHANG_IS_GUEST),null===(a=BoomEmitter.emitter)||void 0===a||a.off(BIND_ELEMENT),null===(c=BoomEmitter.emitter)||void 0===c||c.off(BIND_BIG_ELEMENT),null===(u=BoomEmitter.emitter)||void 0===u||u.off(NO_CONTAINER),null===(d=BoomEmitter.emitter)||void 0===d||d.off(MODEL_SORT_NUM_CHANGE),null===(l=BoomEmitter.emitter)||void 0===l||l.off(ADD_PULL_USER),null===(h=BoomEmitter.emitter)||void 0===h||h.off(SET_VOLUME),null===(m=BoomEmitter.emitter)||void 0===m||m.off(ADD_AUDIO_PLAY),BoomEmitter.emitter=void 0};class BMUser{constructor(e,t=!1){var r;this.streamModels=new Map,this.sortNum=100,this.raiseVideoHands=!1,this.raiseAudioHands=!1,this.raiseHand=!1,this.isAudience=!1,this.isCommonUser=!1,this.inBackground=!1,this.raiseHandTime=0,this.userId=e.userId,this.userInfo=e.userInfo,this.nickName=e.nickname,this.isMaster=!!e.isMaster,this.isManager=!!e.isManager,this.isToupingma=!!e.isToupingma,this.isLocal=t,this.hasMultiple=!!e.hasMultiple,this.isCreate=!!e.isCreate,this.hasShare=!!e.hasShare,this.avatar=null===(r=e.userInfo)||void 0===r?void 0:r.avatar,this.permission=e.permission,this.raiseAudioHands=!!e.raiseAudioHands,this.raiseVideoHands=!!e.raiseVideoHands,this.raiseHand=!!e.raiseHand,this.isAudience=!!e.isAudience,this.isCommonUser=!!e.isCommonUser,this.inBackground=!!e.inBackground,this.audienceEnableSpeaking=!!e.audienceEnableSpeaking,this.raiseHandTime=e.raiseHandTime||0;const i={operation:"none",user:this};this.watcher=new BehaviorSubject(i),this.updateSortNum(!1)}get isWeb(){return!(!this.userInfo.pos||!this.userInfo.pos.includes("web")&&!this.userInfo.pos.includes("pc"))}setup(e,t,r){this.isLocal=!0,this.userId=e,this.userInfo=t,this.nickName=r||t.nickname,this.avatar=t.avatar}getMainStreamModel(){return this.streamModels.get(this.userId)}get nickname(){return this.nickName}getShareStreamModel(){return this.streamModels.get(`${this.userId}${STREAM_SUFFIX_SCREEN}`)}get audioEnable(){const e=this.getMainStreamModel();return!!e&&e._audio_enable}get isMixer(){return this.userId.includes("-mixer-")}get videoEnable(){const e=this.getMainStreamModel();return!!e&&e._video_enable}get isSharing(){let e=!1;for(let t of this.streamModels.values())if(t.isShare){e=!0;break}return e}get isSignal(){var e;return!!(null===(e=this.userId)||void 0===e?void 0:e.startsWith(SIGNAL_SUFFIX))}checkLocalHasMaster(){return this.isMaster||this.isManager}addStream(e,t){this.streamModels.set(e,t),this.watcher.next({operation:"changeShare",user:this})}removeStream(e){this.streamModels.delete(e),e.includes(STREAM_SUFFIX_SCREEN)&&info("删除的是共享屏幕的流:","","",["streamId =>",e]),setTimeout((()=>{this.watcher.next({operation:"changeShare",user:this})}),400)}getID(){return this.userId}getNickName(){return this.nickName}getUserInfo(){return this.userInfo}getStreams(){return this.streamModels}updateUserInfo(e,t={},r){var i,n,s,o,a,c;const u=null===(i=null==t?void 0:t.params)||void 0===i?void 0:i.customInfo,d=(null==u?void 0:u.updateKeys)||[];let l=!1,h="none";if(info("updateUserInfo =>","updateUser",e.userId,["updateKeys",d.toString(),"permission",null===(n=e.permission)||void 0===n?void 0:n.permission,"isMaster =>",this.isMaster,"isManager =>",this.isManager]),this.nickName!==e.nickname&&(h="changeNickName"),this.isMaster||!this.isManager||e.permission.getManage()||(h="removeManager",this.isManager=!1),this.isMaster||this.isManager||!e.permission.getManage()||-1!=d.indexOf("changeMaster")||(h="getManager",this.isManager=!0),e.userinfo.pos)this.userInfo=e.userinfo;else{const t=this.userInfo.pos;this.userInfo=e.userinfo,this.userInfo.pos=t}(d.includes("changeMaster")||d.includes("permission"))&&(e.permission=t.getPermission()),d.includes("raiseHandsAudio")&&(this.raiseAudioHands=u.raiseHandsAudio,h="raiseHandsAudio",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsAudio",user:this}),l=!0),d.includes("raiseHandsVideo")&&(this.raiseVideoHands=u.raiseHandsVideo,h="raiseHandsVideo",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsVideo",user:this}),l=!0),d.includes("raiseHand")&&(this.raiseHand=u.raiseHand,this.raiseHandTime=u.raiseHandTime,h="raiseHand",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHand",user:this}),l=!0),1!==r.conferenceMode&&this.isAudience&&d.includes("permission")&&(-1!==(null===(o=null===(s=t.params)||void 0===s?void 0:s.customInfo)||void 0===o?void 0:o.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!0),this.audienceEnableSpeaking=!0,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceEnable()),-1===(null===(c=null===(a=t.params)||void 0===a?void 0:a.customInfo)||void 0===c?void 0:c.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!1),this.audienceEnableSpeaking=!1,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceDisable())),d.includes("inBackground")&&(h="inBackground",this.inBackground=u.inBackground),this.nickName=e.nickname,this.permission=e.permission;let m=!this.isCommonUser;this.isCommonUser=!e.permission.getSubscribe(),m!==!this.isCommonUser&&(info(`身份有发生过变化,从${m?"嘉宾":"普通参会者"} => ${this.isCommonUser?"普通参会者":"嘉宾"}`),BoomEmitter.emitter.emit(CHANG_IS_GUEST,{user:this,isGuest:!this.isCommonUser,preIsGuest:m})),h&&this.watcher.next({operation:h,user:this}),(!l||l&&!this.isLocal)&&this.updateSortNum(!0)}hasManager(){return this.isManager||this.isMaster}getNicknameSuffix(){let e="";return this.isLocal&&this.isMaster?e="(我、主持人)":this.isLocal&&this.isManager?e="(我、联席主持人)":this.isLocal?e="(我)":this.isMaster?e="(主持人)":this.isManager?e="(联席主持人)":this.isSharing&&!this.isToupingma?e="的共享屏幕":this.isSharing&&this.isToupingma&&(e="(仅共享屏幕)"),e}updateSortNum(e=!0,t=!1){let r=getSortNum(this);this.setSortNum(r,e,t)}setSortNum(e,t,r){this.sortNum!==e&&(this.sortNum=e,t&&BoomEmitter.emitter.emit(USER_SORT_NUM_CHANGE,{isCommon:this.isCommonUser,shouldDelay:r}))}}const NULL=null,UNDEFINED=void 0,RAW_FUNCTION="function";Object.freeze({}),Object.freeze([]);const EMPTY_STRING="";function func(e){return typeof e===RAW_FUNCTION}function indexOf(e,t,r){return e.indexOf(t,r!==UNDEFINED?r:0)}function has(e,t){return indexOf(e,t)>=0}function toString(e,t){return e!=NULL&&e.toString?e.toString():t!==UNDEFINED?t:EMPTY_STRING}function isNative(e){return func(e)&&has(toString(e),"[native code]")}typeof setImmediate===RAW_FUNCTION&&isNative(setImmediate)&&setImmediate,typeof MessageChannel===RAW_FUNCTION&&isNative(MessageChannel);const notGetTalkInterval=3e5;function handleTime(e){let t=new Date(e),r=new Date,i=t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,n=t.getDate()<10?"0"+t.getDate():t.getDate(),s=t.getHours()<10?"0"+t.getHours():t.getHours(),o=t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes();return r.setHours(0,0,0,0)==t.setHours(0,0,0,0)?s+":"+o:i+"月"+n+"日 "+s+":"+o}function sortUsers(e){return e.sort(((e,t)=>e.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND&&t.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND?e.raiseHandTime-t.raiseHandTime:e.sortNum-t.sortNum))}function sortStreamModels(e){return e.sort(((e,t)=>e.sortNum!==t.sortNum?t.sortNum-e.sortNum:Number(e.getUser().isCommonUser)-Number(t.getUser().isCommonUser)))}function getIsCommonUser(e){return!getPermission(e,"s")}function getIsManager(e){return getPermission(e,"m")}function getIsMaster(e){return getPermission(e,"o")}function getPermission(e,t){return e.toLowerCase().includes(t)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}var freeGlobal="object"==typeof global$3&&global$3&&global$3.Object===Object&&global$3,freeGlobal$1=freeGlobal,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal$1||freeSelf||Function("return this")(),root$1=root,Symbol$1=root$1.Symbol,Symbol$2=Symbol$1,objectProto$1=Object.prototype,hasOwnProperty=objectProto$1.hasOwnProperty,nativeObjectToString$1=objectProto$1.toString,symToStringTag$1=Symbol$2?Symbol$2.toStringTag:void 0;function getRawTag(e){var t=hasOwnProperty.call(e,symToStringTag$1),r=e[symToStringTag$1];try{e[symToStringTag$1]=void 0;var i=!0}catch(e){}var n=nativeObjectToString$1.call(e);return i&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),n}var objectProto=Object.prototype,nativeObjectToString=objectProto.toString;function objectToString(e){return nativeObjectToString.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$2?Symbol$2.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag}var reWhitespace=/\s/;function trimmedEndIndex(e){for(var t=e.length;t--&&reWhitespace.test(e.charAt(t)););return t}var reTrimStart=/^\s+/;function baseTrim(e){return e?e.slice(0,trimmedEndIndex(e)+1).replace(reTrimStart,""):e}function isObject(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var NAN=NaN,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;function toNumber(e){if("number"==typeof e)return e;if(isSymbol(e))return NAN;if(isObject(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=isObject(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=baseTrim(e);var r=reIsBinary.test(e);return r||reIsOctal.test(e)?freeParseInt(e.slice(2),r?2:8):reIsBadHex.test(e)?NAN:+e}var now=function(){return root$1.Date.now()},now$1=now,FUNC_ERROR_TEXT="Expected a function",nativeMax=Math.max,nativeMin=Math.min;function debounce(e,t,r){var i,n,s,o,a,c,u=0,d=!1,l=!1,h=!0;if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT);function m(t){var r=i,s=n;return i=n=void 0,u=t,o=e.apply(s,r)}function p(e){return u=e,a=setTimeout(g,t),d?m(e):o}function f(e){var r=e-c;return void 0===c||r>=t||r<0||l&&e-u>=s}function g(){var e=now$1();if(f(e))return v(e);a=setTimeout(g,function(e){var r=t-(e-c);return l?nativeMin(r,s-(e-u)):r}(e))}function v(e){return a=void 0,h&&i?m(e):(i=n=void 0,o)}function _(){var e=now$1(),r=f(e);if(i=arguments,n=this,c=e,r){if(void 0===a)return p(c);if(l)return clearTimeout(a),a=setTimeout(g,t),m(c)}return void 0===a&&(a=setTimeout(g,t)),o}return t=toNumber(t)||0,isObject(r)&&(d=!!r.leading,s=(l="maxWait"in r)?nativeMax(toNumber(r.maxWait)||0,t):s,h="trailing"in r?!!r.trailing:h),_.cancel=function(){void 0!==a&&clearTimeout(a),u=0,i=c=n=a=void 0},_.flush=function(){return void 0===a?o:v(now$1())},_}var numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}const ignoreUserId=["-mixer-","-rtmpmixer-","record#","robot_","stt_"],BLOUD_PAGE_SIZE=500,PERMISSION_NOT_COMMON="RWPSAVMO,RWPSAVM,RWPSAV";class BMUserVM{constructor(e,t,r){this.userList=new Map,this.audiencesList=new Map,this.signalList=new Map,this.commonUserList=new Map,this.userListWatcher=new BehaviorSubject(Array.from(this.userList.values())),this.audiencesListWatcher=new BehaviorSubject(Array.from(this.audiencesList.values())),this.commonUserListWatcher=new BehaviorSubject(Array.from(this.commonUserList.values())),this.signalListWatcher=new BehaviorSubject(Array.from(this.signalList.values())),this.masterUserWatcher=new BehaviorSubject(null),this.getForceUserWatcher=new BehaviorSubject(!1),this.commTimer=200,this.addBCUser=(e,t=!1)=>{var r;const i=this.addUser(e);if(!this.room.bmStreamVm.streamModels.get(e.userId)){const t=this.getUser(e.userId);t?this.room.bmStreamVm.createStreamModel(t):error$1(`there is no user named ${e.userId}, and create streamModel failed!!!`)}{const i=this.room.bmStreamVm.streamModels.get(e.userId);i&&(e.stream.size?e.stream.forEach((r=>__awaiter$2(this,void 0,void 0,(function*(){var n,s;const{video_enable:o,audio_enable:a,customInfo:c}=r;if(r.screen){this.room.bmStreamVm.shareBloudStateMap.set(e.userId,{audio:a,video:o,customInfo:c,userId:e.userId,streamId:r.getID(),isScreen:!0});const u={id:i.userId,isScreen:!0,isWeb:i.isWeb};if(t){const t=new Map;t.set(e.userId,u),yield null===(n=this.room)||void 0===n?void 0:n.processUser(t)}else null===(s=this.room)||void 0===s||s.addUser2Queue(u)}else i&&i.updateBloudStream({video:o,audio:a,isScreen:r.screen,customInfo:c},this.room.bmStreamVm)})))):(i.bloudStream&&i.updateBloudStream(void 0,this.room.bmStreamVm),null===(r=this.room)||void 0===r||r.bmStreamVm.removeShareStreamModelByUId(e.userId)))}return i&&i.isMaster&&this.masterUserWatcher.next(i),null==i||i.updateSortNum(!1),i},this.updateAllSort=()=>{this.updateUserSort(),this.updateCommonUserSort()},this.updateSortByType=e=>{var t,r;(null===(t=this.room)||void 0===t?void 0:t.isSingleColumns)||e.isCommon?(null===(r=this.room)||void 0===r?void 0:r.isBig)&&e.shouldDelay?this.updateDelayCommonUserSort():this.updateCommonUserSort():this.updateUserSort()},this.updateUserSort=debounce((()=>{const e=this.sortUsers();this.userListWatcher.next(BMUserVM.filterUsers(e))}),200,{maxWait:1e3}),this.updateCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),this.commTimer,{maxWait:12e3}),this.updateDelayCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),12e4,{maxWait:12e4}),this.updateAudienceUserSort=()=>{const e=this.sortAudiences();this.audiencesListWatcher.next(BMUserVM.filterUsers(e))},this.updateSignalUserSort=()=>{const e=this.sortSignalUsers();this.signalListWatcher.next(e)},this.transBloudUsers=(e,t="",r=!1,i=0)=>__awaiter$2(this,void 0,void 0,(function*(){const n=new Map;yield this.getAllUsers(e,n,t,r).catch((()=>i<3?(error$1("get bloud user error, retry"),i+=1,void this.transBloudUsers(e,t,r,i)):void error$1("get current page of bloud users after 10 times final failed","","",[" page ",e," permission ",t]))),yield this.initUserList(n),n.clear();let s=[];for(let e of this.userList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands)&&s.push(e);this.room.roomInfo.setRaiseHandsList(s),this.updateAllSort(),this.room.bmStreamVm.updateModelSort()})),this.boomCore=e,this.localUser=t,this.room=r,BoomEmitter.emitter||error$1("init boom emitter error"),BoomEmitter.emitter.on(CHANG_IS_GUEST,this.handleUserRoleChange.bind(this)),BoomEmitter.emitter.on(USER_SORT_NUM_CHANGE,this.updateSortByType)}handleUserRoleChange(e){var t,r,i;return __awaiter$2(this,void 0,void 0,(function*(){const{user:n,isGuest:s,preIsGuest:o}=e,a=null===(t=this.room)||void 0===t?void 0:t.roomInfo.isBigRoom;info("handleUserRoleChange","",n.userId,["isGuest =>",s,"preIsGuest =>",o,"isBigRoom =>",a]);if(1===(null===(r=this.room)||void 0===r?void 0:r.userListColumns)||(o?this.userList.delete(n.userId):this.commonUserList.delete(n.userId),s?this.userList.set(n.userId,n):this.commonUserList.set(n.userId,n)),a)if(s)n.isLocal&&(yield this.initUsers());else{const e=null===(i=this.room)||void 0===i?void 0:i.getLocalParticipant().isCommonUser;if(n.isLocal&&(this.handleUnSubCommonUser(),this.handleCommonUserChange(),this.commonUserList.set(n.userId,n)),e){const e=n.getMainStreamModel();e&&e.unSubscribeStream(),n.isLocal||this.commonUserList.delete(n.userId)}}this.updateAllSort()}))}addUser(e){var t;const r=this.getUser(e.userId);if(r)return info("该用户已经加入房间",LOGGER_TAG_CLIENT,e.userId),this.updateUser(r,e),null;let i;return this.boomCore.userId==e.userId?(this.updateUser(this.localUser,e),i=this.localUser):i=this.toBMUser(e),1===(null===(t=this.room)||void 0===t?void 0:t.userListColumns)?this.commonUserList.set(i.userId,i):i.isAudience?this.audiencesList.set(i.userId,i):i.isSignal?this.signalList.set(i.userId,i):i.isCommonUser?this.commonUserList.set(i.userId,i):this.userList.set(i.userId,i),i}removeUser(e){let t=this.userList.delete(e);return t||(t=this.signalList.delete(e)),t||(t=this.audiencesList.delete(e)),t||(t=this.commonUserList.delete(e)),t||warn("userList中未找到该用户, 移除无效",LOGGER_TAG_CLIENT,e),t}videoEnable(e){const t=this.getUser(e);if(t)return t.videoEnable;throw new BoomError$1(USER_NOT_EXIT,"用户不存在")}audioEnable(e){const t=this.getUser(e);if(t)return t.audioEnable;throw new BoomError$1(USER_NOT_EXIT,"用户不存在")}checkIsMaster(e){if(!e)return!1;const t=this.boomCore.getMaster();return!!t&&t===e}checkLocalHasMaster(){return this.localUser.isMaster||this.localUser.isManager}checkUserHasMaster(e){const t=this.userList.get(e);return!!t&&t.permission.getManage()}getUser(e){let t;return t=(null==e?void 0:e.startsWith(SIGNAL_SUFFIX))?this.signalList.get(e):this.userList.get(e),t||(t=this.commonUserList.get(e)),t||(t=this.audiencesList.get(e)),t}getAllUsers(e,t,r="",i=!1){return __awaiter$2(this,void 0,void 0,(function*(){let n;if(i){let{users:t,total:i}=yield this.boomCore.getUsersList(e,r,BLOUD_PAGE_SIZE);n=t}else{let{users:t,total:i}=yield this.boomCore.getUsers(e,r,BLOUD_PAGE_SIZE);n=t}n.forEach((e=>{t.set(e.userId,e)}))}))}initUserList(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){const i=e.get(this.localUser.userId);if(i){const e=this.addUser(i);if(!(null===(t=this.room)||void 0===t?void 0:t.bmStreamVm.getStreamModelByUId(i.userId))){const e=this.getUser(i.userId);e?null===(r=this.room)||void 0===r||r.bmStreamVm.createStreamModel(e):error$1("there is no local streamModel exits, and create failed!!!")}(null==e?void 0:e.isMaster)&&this.masterUserWatcher.next(e)}e.delete(this.localUser.userId),e&&e.size>0&&this.addBcUsersMap(e)}))}addBcUsersMap(e,t=!1){e.forEach((e=>{this.addBCUser(e,t)}))}updateMaster(e,t,r){const i=this.getUser(e);i&&(i.isManager&&(i.isManager=!1),i.isMaster=!0,i.updateSortNum());const n=this.getUser(t);return n&&(n.isMaster=!1,r&&(n.isManager=!0),n.updateSortNum()),i||n||error$1("未找到该用户, updateMaster未生效",LOGGER_TAG_CLIENT,e,["masterId => ",e,"oldMasterId => ",t]),{master:i,oldMaster:n}}managerChangeToGuest(e){const t=this.getUser(e);return t?t.isManager?(t.permission.setManage(!1),t.permission.setSubscribe(!0),this.boomCore.updateUser(e,{customInfo:{permission:t.permission.get()}}),t.watcher.next({operation:"getGuest",user:t}),this.updateAllSort()):error$1("该用户不是管理员,无法设置为嘉宾",LOGGER_TAG_CLIENT,e):error$1("未找到该用户, managerChangeToGuest未生效",LOGGER_TAG_CLIENT,e),t}updateManager(e,t,r=!0){const i=this.getUser(e);return i?(i.permission.setManage(t),i.permission.setSubscribe(t),this.boomCore.updateUser(e,{customInfo:{permission:i.permission.get()}}),i.watcher.next({operation:t?"getManager":"removeManager",user:i}),this.updateAllSort()):error$1("userList中未找到该用户, updateManager未生效",LOGGER_TAG_CLIENT,e),i}getLocalUser(){return this.localUser}updateUser(e,t){var r,i,n,s,o;const a=this.checkIsMaster(t.userId),c=((null===(r=t.permission)||void 0===r?void 0:r.getManage())||getIsManager(null===(i=t.permission)||void 0===i?void 0:i.permission))&&!((null===(n=t.permission)||void 0===n?void 0:n.getOwn())||getIsMaster(null===(s=t.permission)||void 0===s?void 0:s.permission));let u="none";const d=e.isMaster;e.isManager!==c&&(u=c?"getManager":"removeManager"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),10),d!==a&&(u=a?"getMaster":"removeMaster"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),100);e.raiseHand!==t.customInfo.raiseHand&&setTimeout((()=>{e.watcher.next({operation:"raiseHand",user:e})}),300);e.nickname!==t.nickname&&setTimeout((()=>{e.watcher.next({operation:"changeNickName",user:e})}),300),e.userInfo=t.userinfo,e.nickName=t.nickname,e.userId=t.userId,e.permission=t.permission,e.avatar=t.userinfo.avatar,e.isToupingma=t.userinfo.pos.includes("_toupingma"),e.isMaster=a,e.isCreate=this.boomCore.getCreator()===t.userId,e.isAudience=!t.permission.getAudio(),e.isCommonUser=!t.permission.getSubscribe(),e.isManager=c,e.inBackground=!!(null===(o=null==t?void 0:t.customInfo)||void 0===o?void 0:o.inBackground),e.updateSortNum()}updateLocalUserPermission(e){const t=this.getLocalUser();t.isMaster=getIsMaster(e),t.isManager=!getIsMaster(e)&&getIsManager(e),t.isCommonUser=getIsCommonUser(e),t.watcher.next({operation:"none",user:t})}toBMUser(e){var t,r;let i={};i.userInfo=e.userinfo,i.nickname=e.nickname,i.userId=e.userId,i.streamModels=[],i.permission=e.permission,i.stream=e.stream,i.isToupingma=!(!e.userinfo.pos||!e.userinfo.pos.includes("_toupingma")),i.isMaster=this.checkIsMaster(i.userId),i.isAudience=!e.permission.getAudio(),i.isCommonUser=!e.permission.getSubscribe()||getIsCommonUser(e.permission.permission),i.raiseAudioHands=e.customInfo.raiseHandsAudio,i.raiseVideoHands=e.customInfo.raiseHandsVideo,i.raiseHand=e.customInfo.raiseHand,i.raiseHandTime=e.customInfo.raiseHandTime,i.inBackground=e.customInfo.inBackground,i.isCreate=this.boomCore.getCreator()===e.userId;let n=this.boomCore.getLocalParticipant();if(!n)throw new BoomError$1(INVALID_PARAMETER,"BCUserVM addUser时未找到本地用户");return n.getID()==i.userId&&(i.isLocal=!0),!(null===(t=i.permission)||void 0===t?void 0:t.getManage())&&!getIsManager(null===(r=i.permission)||void 0===r?void 0:r.permission)||i.isMaster||(i.isManager=!0),new BMUser(i,i.isLocal)}sortUsers(){return sortUsers(Array.from(this.userList.values()))}sortAudiences(){return sortUsers(Array.from(this.audiencesList.values()))}sortCommonUsers(){return sortUsers(Array.from(this.commonUserList.values()))}sortSignalUsers(){return sortUsers(Array.from(this.signalList.values()))}static filterUsers(e){return e.filter((e=>!ignoreUserId.some((t=>e.userId.includes(t)))))}initUsers(){var e;return __awaiter$2(this,void 0,void 0,(function*(){const t=yield this.getTotalUserNumber();info(`initUsers total users num: ${t}`);const r=Math.ceil(t/BLOUD_PAGE_SIZE);let i=0;const n=[],s=e=>__awaiter$2(this,void 0,void 0,(function*(){e<r&&(yield this.transBloudUsers(e-1))})),o=e=>__awaiter$2(this,void 0,void 0,(function*(){for(const t of e)yield t(),yield sleep(50)}));if(this.localUser.isCommonUser&&(null===(e=this.room)||void 0===e?void 0:e.isBig))this.commonUserList.set(this.localUser.userId,this.localUser),yield this.transBloudUsers(-1,PERMISSION_NOT_COMMON,!0);else{for(;i<r;)n.push(s.bind(null,i)),i+=1;o(n)}}))}handleUnSubCommonUser(){this.commonUserList.forEach((e=>{const t=e.getMainStreamModel();(null==t?void 0:t.hasPulled)&&t.unSubscribeStream()}))}handleCommonUserChange(){let e=new Map;this.room.bmStreamVm.streamModels.forEach((t=>{t.getUser().isCommonUser&&!t.isLocal||e.set(t.userId,t)})),this.room.bmStreamVm.streamModels=e,this.commonUserList.clear()}getUsers(e,t,r="RWPAV"){return __awaiter$2(this,void 0,void 0,(function*(){const{users:i,total:n}=yield this.boomCore.getUsers(e,r,t),s=[];return i.forEach((e=>{const t=this.toBMUser(e);s.push(t)})),{userList:s,total:n}}))}getUsersList(e,t,r="",i=!1){var n,s;return __awaiter$2(this,void 0,void 0,(function*(){const{users:o,total:a,pageIndex:c}=yield this.boomCore.getUsersList(e,r,t,i),u=[];return o.forEach((e=>{const t=this.toBMUser(e);u.push(t)})),i&&(null===(n=this.room)||void 0===n?void 0:n.roomInfo.totalWaitRoomUserWatcher.value)!==a&&(null===(s=this.room)||void 0===s||s.roomInfo.totalWaitRoomUserWatcher.next(a)),{userList:u,total:a,pageIndex:c}}))}getTotalUserNumber(){return __awaiter$2(this,void 0,void 0,(function*(){const e=()=>__awaiter$2(this,void 0,void 0,(function*(){const{total:e}=yield this.boomCore.getUsers(0,"",1);return e})),t=r=>{e().then((e=>{r(e)})).catch((e=>{error$1("getTotalUserNumber error","","",[JSON.stringify(e)]),t(r)}))};return new Promise(((e,r)=>__awaiter$2(this,void 0,void 0,(function*(){t(e)}))))}))}clearUsers(){this.userList.clear(),this.commonUserList.clear(),this.audiencesList.clear(),this.signalList.clear()}searchUsers(e,t){return __awaiter$2(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!1);let i=[],n=[];return r.forEach((e=>{const t=this.userList.get(e.userId);if(t)return void i.push(t);const r=this.commonUserList.get(e.userId);r&&n.push(r)})),{userList:i,commonUserList:n}}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"boomCore.searchUsers发生错误:"+(null==e?void 0:e.message)))}}))}searchWaitRoomUsers(e,t){return __awaiter$2(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!0),i=[];return r.forEach((e=>{const t=this.toBMUser(e);i.push(t)})),i}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"search wait room users error"))}}))}}class BMMessageInfo{constructor(e){this.isMeetingNotice=!1,this.userId=e.userId,this.message=e.message,this.role=e.role,this.isLocal=e.isLocal,this.avatar=e.avatar,this.nickName=e.nickName,this.to=e.to,this.isDanger=e.isDanger,this.seq=e.seq,this.failed=e.failed;let t=!1;e.isMeetingNotice&&(t=!0),this.isMeetingNotice=t,e.sendTime?(this.timeStamp=e.sendTime,this.time=handleTime(this.timeStamp)):(this.timeStamp=(new Date).getTime(),this.time=handleTime(this.timeStamp))}}var BCEvent;!function(e){e.ROOM_CONNECTED="room-connected",e.ROOM_RECONNECTING="room-reconnecting",e.ROOM_RECONNECTED="room-reconnected",e.ROOM_SYNC="room-synced",e.JOINUSER="participant-joined",e.LEAVEUSER="participant-left",e.ROOMERROR="room-error",e.UNPUBLISH="participant-unpublished",e.PUBLISHED="participant-published",e.SENDMESSAGE="new-message",e.CUSTOMMESSAGE="custom-message",e.STREAMERROR="error-media",e.STREAMDISCONNECTED="stream-disconnected",e.EVICTED="participant-evicted",e.UPDATESTATS="update-stats",e.CUSTOMSTATS="update-custom-stats",e.UPDATEUSER="participant-update",e.CHANGEMASTER="change-master",e.USERREJOINED="user-rejoined",e.TOKENWILLEXPIRE="token-will-expire",e.TOKENEXPIRE="token-expire",e.ICECANDIDATE="onIceCandidate",e.STREAMUPDATE="stream-update",e.UPDATE="update",e.ANALYSISDATA="analysis-data",e.ANALYSISERROR="analysis-error",e.STARTANALYSIS="start-analyze",e.STOPANALYSIS="stop-analyze",e.REPORTINFO="info-reported",e.STREAM_ADDED="stream-added",e.STREAM_REMOVED="stream-removed",e.STREAM_UPDATED="stream-updated",e.BLOUD_STREAM_UPDATED="bloud-stream-update",e.MOVE_USER_ROOM="move-user-room",e.STREAM_PUBLISHED="stream-published",e.STREAM_SUBSCRIBED="stream-subscribed",e.MUTE_VIDEO="mute-video",e.UNMUTE_VIDEO="unmute-video",e.MUTE_AUDIO="mute-audio",e.UNMUTE_AUDIO="unmute-audio",e.ERROR="error",e.PEER_JOINED="peer-joined",e.PEER_LEAVED="peer-leaved",e.CLIENT_BANNED="client-banned",e.USER_KICKED="user-kicked",e.TOKEN_WILL_EXPIRE="token-will-expire",e.TOKEN_EXPIRE="token-expire",e.ROOM_CLOSED="room-closed",e.NETWORK_ERROR="network-error",e.BRTC_SYNC_ROOM_COMPLETED="sync-room-completed",e.BRTC_ROOM_ROCONNECTING="brtc-room-reconnecting",e.BRTC_ROOM_RECONNECTED="brtc-room-reconnected",e.JOIN_READY="join-ready",e.BRTC_SHARE_SYNC_ROOM_COMPLETED="brtc-share-sync-room-completed",e.LEAVE_USERS="leaveUsers",e.ROOM_ERROR="error-room",e.UPDATE_STREAM="update-stream"}(BCEvent||(BCEvent={}));var BCEvent$1=BCEvent,BoomCoreErrorCode;function isShareStream(e){const t=e.getStreamId();return e.getUserId().endsWith(STREAM_SUFFIX_SCREEN)||t.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()}class BoomError extends Error{constructor(e,t,r){let i;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,i="string"==typeof t?t:JSON.stringify(t),this.message=i,r&&(this.name=r)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}}!function(e){e[e.BloudLock=28]="BloudLock",e[e.ShareScreenNoPermission=100]="ShareScreenNoPermission",e[e.ShareScreenCanceled=101]="ShareScreenCanceled",e[e.ShareScreenOtherError=102]="ShareScreenOtherError",e[e.ShareScreenContentHintError=103]="ShareScreenContentHintError",e[e.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",e[e.BrtcShareSigError=105]="BrtcShareSigError",e[e.ToggleShareScreenError=106]="ToggleShareScreenError",e[e.BrtcCreateStreamError=107]="BrtcCreateStreamError",e[e.BrtcSubscribeError=108]="BrtcSubscribeError",e[e.BrtcPublishError=109]="BrtcPublishError",e[e.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",e[e.BrtcUnPublishError=111]="BrtcUnPublishError",e[e.RepeatJoinError=112]="RepeatJoinError",e[e.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",e[e.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",e[e.JoinUserInfoError=115]="JoinUserInfoError",e[e.JoinTypeError=116]="JoinTypeError",e[e.JoinBrtcError=117]="JoinBrtcError",e[e.JoinBloudError=118]="JoinBloudError",e[e.UpdateCustomStatsError=119]="UpdateCustomStatsError",e[e.CreateBloudError=120]="CreateBloudError"}(BoomCoreErrorCode||(BoomCoreErrorCode={})),new BoomError(BoomCoreErrorCode.ShareScreenNoPermission,"没有打开共享屏幕录制权限","no share permission"),new BoomError(BoomCoreErrorCode.ShareScreenCanceled,"取消共享屏幕","cancel share"),new BoomError(BoomCoreErrorCode.ShareScreenContentHintError,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed"),new BoomError(BoomCoreErrorCode.ShareScreenClientJoinedError,"共享屏幕brtc client入会失败","share client join failed"),new BoomError(BoomCoreErrorCode.BrtcShareSigError,"brtcShareSig为空","brtc share sig is empty");const RepeatJoinError=new BoomError(BoomCoreErrorCode.RepeatJoinError,"正在 join,请勿重复调用","repeat join error");new BoomError(BoomCoreErrorCode.ProxiesUrlTypeError,"proxies url 必须为字符串","get bloud proxies param error"),new BoomError(BoomCoreErrorCode.JoinUserInfoError,"userinfo传递错误,请检查"),new BoomError(BoomCoreErrorCode.JoinTypeError,"type传递错误,请检查");const updateCustomStatsError=e=>new BoomError(BoomCoreErrorCode.UpdateCustomStatsError,e,"bloud updateCustomStats failed");var BoomMeetingErrorCode;!function(e){e[e.BmJoinError=200]="BmJoinError",e[e.BMLeaveError=201]="BMLeaveError",e[e.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",e[e.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",e[e.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",e[e.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",e[e.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",e[e.BmChangeMasterError=207]="BmChangeMasterError",e[e.BmUpdateManagerError=208]="BmUpdateManagerError",e[e.BmEvictUserError=209]="BmEvictUserError",e[e.BmUpdateUserError=210]="BmUpdateUserError",e[e.BmSetAudioOffError=211]="BmSetAudioOffError",e[e.BmSetVideoOffError=212]="BmSetVideoOffError",e[e.BmSetMsgOffError=213]="BmSetMsgOffError",e[e.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",e[e.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",e[e.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",e[e.BmCheckDeviceError=217]="BmCheckDeviceError"}(BoomMeetingErrorCode||(BoomMeetingErrorCode={}));const BmLeaveError=e=>new BoomError(BoomMeetingErrorCode.BMLeaveError,e,"boommeeting leave failed"),BmSetRemoteVideoEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetRemoteVideoEnable,e,"开关对端摄像头失败"),BmSetRemoteAudioEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetRemoteAudioEnable,e,"开关对端麦克风发生失败"),BmSetLocalVideoEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalVideoEnable,e,"开关本地摄像头失败"),BmSetLocalAudioEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalAudioEnable,e,"开关本地麦克风失败"),BmSetLocalSpeakerEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalSpeakerEnable,e,"开关扬声器失败"),BmChangeMasterError=e=>new BoomError(BoomMeetingErrorCode.BmChangeMasterError,e,"转移主持人发生错误"),BmUpdateManagerError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateManagerError,e,"改变联席主持人发生错误"),BmEvictUserError=e=>new BoomError(BoomMeetingErrorCode.BmEvictUserError,e,"踢出用户发生错误"),BmUpdateUserError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateUserError,e,"更新用户信息发生错误"),BmSetAudioOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetAudioOffError,e,"全员静音发生错误"),BmSetVideoOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetVideoOffError,e,"全员禁用摄像头发生错误"),BmSetMsgOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetMsgOffError,e,"全员禁用聊天发生错误"),BmUpdateCustomStatsError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateCustomStatsError,e,"更新房间自定义属性状态发生错误"),BmChangeVideoProfileError=e=>new BoomError(BoomMeetingErrorCode.BmChangeVideoProfileError,e,"远程调节对方视频发生错误"),BmChangeAudioProfileError=e=>new BoomError(BoomMeetingErrorCode.BmChangeAudioProfileError,e,"远程调节对方音频发生错误"),BmCheckDeviceError=e=>new BoomError(BoomMeetingErrorCode.BmCheckDeviceError,e,"远程检测对方设备发生错误");var StreamErrorMap;!function(e){e[e.createStream=1302]="createStream",e[e.noCameraDevice=1303]="noCameraDevice",e[e.noMicroDevice=1304]="noMicroDevice",e[e.noSpeakerDevice=1305]="noSpeakerDevice",e[e.openCamera=1301]="openCamera",e[e.cameraNotAuth=1314]="cameraNotAuth",e[e.cameraOccupy=1315]="cameraOccupy",e[e.openMicro=1302]="openMicro",e[e.micNotAuth=1317]="micNotAuth",e[e.micOccupy=1319]="micOccupy",e[e.streamDisconnected=1320]="streamDisconnected",e[e.syncFail=1321]="syncFail",e[e.getStreamFail=1322]="getStreamFail",e[e.streamConnectError=1323]="streamConnectError",e[e.streamReconnectSuccess=1324]="streamReconnectSuccess",e[e.streamReconnectFailed=1325]="streamReconnectFailed",e[e.shareStreamConnectError=1326]="shareStreamConnectError",e[e.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",e[e.shareStreamConnectFailed=1328]="shareStreamConnectFailed"}(StreamErrorMap||(StreamErrorMap={}));const BMCreateStreamError=e=>new BoomError(StreamErrorMap.createStream,`采集${e}流失败,请重试`),getStreamError=e=>new BoomError(StreamErrorMap.getStreamFail,`当前${e}不可用, 请确保您的${e}连接正确, 或更换其他${e}`),BMOpenCameraError=()=>new BoomError(StreamErrorMap.openCamera,"打开摄像头失败"),BMCameraNotAuthError=()=>new BoomError(StreamErrorMap.cameraNotAuth,"摄像头设备未授权, 无法开启视频, 启动摄像头失败, 请在系统或浏览器“设置-隐私”中允许使用摄像头"),BMCameraOccupyError=()=>new BoomError(StreamErrorMap.cameraOccupy,"当前摄像头被占用, 请检查或切换其他摄像头"),BMOpenMicroError=()=>new BoomError(StreamErrorMap.openMicro,"打开麦克风失败"),BMMicNotAuthError=()=>new BoomError(StreamErrorMap.micNotAuth,"麦克风设备未授权, 无法开启麦克风, 启动麦克风失败, 请在系统或浏览器“设置-隐私”中允许使用麦克风"),BMMicOccupyError=()=>new BoomError(StreamErrorMap.micOccupy,"当前麦克风被占用, 请检查或切换其他麦克风"),BMStreamDisconnectedError=e=>new BoomError(StreamErrorMap.streamDisconnected,`${e}连接已断开,正在重试,请稍后`),BmSyncStreamFailError=()=>new BoomError(StreamErrorMap.syncFail,"状态同步异常,请重试, 麦克风和摄像头已自动关闭"),BMStreamConnectError=()=>new BoomError(StreamErrorMap.streamConnectError,"网络连接异常,正在重试"),BMShareStreamConnectError=()=>new BoomError(StreamErrorMap.shareStreamConnectError,"共享屏幕网络连接异常,正在重试"),BMStreamReconnectSuccess=(e,t)=>{let r="";return e&&t?r="麦克风和摄像头":e?r="麦克风":t&&(r="摄像头"),new BoomError(StreamErrorMap.streamReconnectSuccess,`网络连接成功, ${r}已自动打开`)},BMShareStreamReconnectSuccess=()=>new BoomError(StreamErrorMap.shareStreamConnectSuccess,"共享屏幕网络连接成功, 已自动打开"),BMStreamReconnectFailed=()=>new BoomError(StreamErrorMap.streamReconnectFailed,"网络连接失败,请检查网络,麦克风和摄像头已自动关闭"),BMShareStreamReconnectFailed=()=>new BoomError(StreamErrorMap.streamReconnectFailed,"共享屏幕网络连接失败,请检查网络,共享屏幕已自动关闭");function checkStreamIsNormal(e){var t,r,i,n;if(e&&!e.isLocal){(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)))&&setTimeout((()=>{var t,r,i,n;(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)))&&(warn("用户流检测,但是流订阅出现了问题,需要重新订阅","用户流检测",e.userId,[" nickname => ",e.nickname,"isDisplay =>",e.isDisplay]),e.hasPulled=!1,e.pulledStreamType="small",e.sendMessage2Room())}),2e3)}}function handleBloudReconnectStreamEvent(e){var t,r;const i=e.getLocalStreamModel();if(i&&!(null==i?void 0:i.stream))e.bloudStream&&(info("brtc 已经没有流了,bloud 的流要取消掉"),e.bloudStream.unpublish(),i.updateBloudStream(void 0,e),e.bloudStream=null);else if(i&&i.stream){info("brtc 流已经重推上去了,bloud要重新发推流的逻辑");const t=i.stream.getAudioOn(),r=i.stream.getVideoOn();e.publishBloudStream(t,r).then((()=>{info("brtc stream repub success bloud repub success, notify reconnect success"),e.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess(t,r))}))}if(e.localIsShare){info("brtc has share stream, and bloud need to republish share stream");const i=null===(t=e.room)||void 0===t?void 0:t.boomCore.shareScreenStream;if(i){const t=i.getAudioOn(),n=i.getVideoOn();try{null===(r=e.room)||void 0===r||r.boomCore.createAndPubBloudShareStream(t,n)}catch(e){error$1("bloud 共享屏幕流,断网重连重推流失败")}}}}const handleReconnectedStream=debounce((e=>{if(e.networkState.bloud&&e.networkState.brtc)try{e.streamQueue.restart()}catch(t){e.streamQueue.setQueueProcessor(e.queueProcessor),e.streamQueue.restart()}}),300);function handleStreamPublished(e,t,r,i){const n=e.stream;if(info("本地推流","本地推流",n.getUserId()),n){const e=t.getLocalStreamModel();if(e&&t.updateStreamModel(e,n),i[BCEvent$1.STREAM_PUBLISHED].next({published:!0,model:e}),1===r.conferenceMode){r.getLocalParticipant().isAudience&&t.getStreamModels().forEach((e=>{e.sendMessage2Room()}))}}else i[BCEvent$1.STREAM_PUBLISHED].next({published:!1})}function handleBloudStreamPublished(e,t,r){info("bloud publish stream"),handleBloudStreamPubAUpdate(e,t,!0),r[BCEvent$1.PUBLISHED].next(e)}function handleBloudStreamPubAUpdate(e,t,r=!1){var i;info("bloud stream update","","",[JSON.stringify(e)]);const n=e.userId,s=e.isScreen,o=t.streamModels.get(n);if(o)if(s){t.shareBloudStateMap.set(n,e);const r={id:n,isWeb:o.isWeb,isScreen:s};null===(i=t.room)||void 0===i||i.addUser2Queue(r)}else o.updateBloudStream(e,t,r),o.getUser().updateSortNum();else error$1("bloud stream update, but can not get streamModel","",n)}function handleBloudStreamUnPublished(e,t,r){info("bloud unpublish stream","","",[JSON.stringify(e)]),handleBloudStreamUnpublish(e,t),r[BCEvent$1.UNPUBLISH].next(e)}function handleBloudStreamUpdated(e,t,r){info("bloud stream update","","",[JSON.stringify(e)]);const i=e.streamId,n=e.userId,s=e.params.customInfo;let o;o=i.includes("_screen")?t.shareStreamModels.get(n):t.streamModels.get(n),o?o.updateBloudCustomInfo(s):error$1("bloud stream update, but can not get streamModel","",n,["streamId =>",i]),r[BCEvent$1.UPDATE_STREAM].next(e)}function handleBloudStreamUnpublish(e,t){var r,i,n;const s=e.userId;if(e.isScreen){const e=t.shareStreamModels.get(s);if(e){const r=e.stream;r?(t.remoteStreamUnpublished(r),r.destroy()):t.removeShareStreamModelByUId(s);const i={id:s,isWeb:e.isWeb,isScreen:!0};null===(n=t.room)||void 0===n||n.streamQueue.removeUsers([i])}}else{const e=t.streamModels.get(s);if(e){e.updateBloudStream(void 0,t);const n=e.stream;n&&(null===(r=t.room.audioPlayer)||void 0===r||r.removeStream(n),t.remoteStreamUnpublished(n),n.destroy());const o={id:s,isWeb:e.isWeb,isScreen:!1};null===(i=t.room)||void 0===i||i.streamQueue.removeUsers([o])}}}function handleShareStreamFailed(e,t){setTimeout((()=>__awaiter$2(this,void 0,void 0,(function*(){info("handle republish share stream");try{const r=e.boomCore.shareScreenStream;if(r){const i=r.getAudioOn(),n=r.getVideoOn();yield e.boomCore.shareBrtcClient.publish(r),e.boomCore.createAndPubBloudShareStream(i,n),info("handle republish share stream success"),t.localShareError.next(BMShareStreamReconnectSuccess())}else warn("no share stream exist")}catch(e){error$1("handle republish share stream failed , now unpublish"),t.localShareError.next(BMShareStreamReconnectFailed()),yield t.toggleShareScreen(!1,void 0)}}))),1e3)}function setupRoomInfo(e,t,r){const i=e.permission,n=e.total;i&&r.updateLocalUserPermission(i),t.isInWaitRoom=e.joinwait;const s=e.waitroom;t.roomInfo.isOpenWaitRoom.next(s),t.roomInfo.totalUserWatcher.next(n)}function handleRoomConnected(e,t,r,i,n=!0){var s;return __awaiter$2(this,void 0,void 0,(function*(){info("room-connected",t.getLocalParticipant().userId,"room-connected",["roomId =>",t.roomInfo.roomID," local permission => ",e.permission]),t.forceId=null===(s=e.customStats.forceOn)||void 0===s?void 0:s.user,handleInitRoomInfo(e,t),setupRoomInfo(e,t,r),n&&i[BCEvent$1.ROOM_CONNECTED].next(e)}))}function handleInitJoinRoomUsers(e){return __awaiter$2(this,void 0,void 0,(function*(){info("join ready init users"),e.isInWaitRoom||(e.forceId&&(yield e.getForceUser(e.forceId)),yield e.userVM.initUsers())}))}function handleRoomUpdated(e,t){info("update-stats "," ","",["options => ",JSON.stringify(e.options)]),e.options&&"audiooff"==e.options[0]||"selfopenaudio"==e.options[1]?t.roomInfo.setAudioOff(e.room.audiooff,e.room.selfopenaudio):e.options&&"lock"==e.options[0]?t.roomInfo.setlock(e.room.lock):e.options&&"waitroom"==e.options[0]&&t.roomInfo.isOpenWaitRoom.next(e.stats.waitroom)}function handleInitRoomInfo(e,t){t.roomInfo.msgSeq=e.msgSeq,e.customStats&&t.roomInfo.initCustomStats(e.customStats)}function exitUserUpdateStream(e,t,r,i,n){var s;e.updateUser(t,r);const o=r.stream,a=i.streamModels.get(t.userId);if(a||error$1("bmUserVM中存在该用户,但是bmStreamModelVM中不存在该用户,佛了"),!o.size){(null==a?void 0:a.bloudStream)&&(a.updateBloudStream(void 0,i),n.streamQueue.removeUsers([{id:t.userId,isScreen:!1},{id:t.userId,isScreen:!0}]));const e=i.shareStreamModels.get(t.userId);e&&!e.isLocal&&(null===(s=e.stream)||void 0===s||s.destroy(),i.removeShareStreamModel(e))}o.get(`${t.userId}_screen`)&&n.addUser2Queue({id:t.userId,isScreen:!0,isWeb:t.isWeb});const c=o.get(t.userId);c&&(null==a||a.updateBloudStream({audio:c.audio_enable,video:c.video_enable,isScreen:!1},i))}function addUsers(e,t,r,i){e.isSingleColumns?t.commonUserList.forEach((n=>{const s=r.get(n.userId);if(s)return r.delete(n.userId),void exitUserUpdateStream(t,n,s,i,e);t.commonUserList.delete(n.userId),i.streamModels.delete(n.userId),i.shareStreamModels.delete(n.userId)})):t.userList.forEach((n=>{const s=r.get(n.userId);if(s)return exitUserUpdateStream(t,n,s,i,e),void(n.isCommonUser?t.userList.delete(n.userId):r.delete(n.userId));t.userList.delete(n.userId),i.streamModels.delete(n.userId),i.shareStreamModels.delete(n.userId)})),e.userVM.addBcUsersMap(r)}function handleRoomSync(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){const n=t.getLocalParticipant().userId,{users:s}=yield t.boomCore.queryUsers([n]),o=s.get(n);o&&r.updateUser(r.localUser,o);const a=t.getLocalParticipant().isCommonUser;if(t.isBig&&a){const{users:e}=yield t.boomCore.getUsersList(0,PERMISSION_NOT_COMMON,500);addUsers(t,r,e,i)}else{const e=(yield t.userVM.getTotalUserNumber())/BLOUD_PAGE_SIZE;let n=new Map;for(let r=0;r<e;r++){let{users:e}=yield t.boomCore.getUsers(r-1,"",BLOUD_PAGE_SIZE);e.forEach((e=>{n.set(e.userId,e)}))}addUsers(t,r,n,i)}handleInitRoomInfo(e,t),t.userVM.updateAllSort(),t.bmStreamVm.updateModelSort()}))}function handleBrtcRoomReconnecting(e,t,r){info("brtc room reconnecting"),t.networkState.brtc=!1,t.streamWSReconnectWatcher.next(!1),r[BCEvent$1.BRTC_ROOM_ROCONNECTING].next(e)}function handleBrtcRoomReconnected(e,t,r){info("brtc room reconnected"),t.networkState.brtc=!0,handleReconnectedStream(t),r[BCEvent$1.BRTC_ROOM_RECONNECTED].next(e)}function handleBloudRoomReconnecting(e,t,r){info("bloud room reconnecting"),t.networkState.bloud=!1,t.bloudWSReconnectWatcher.next(!1),r[BCEvent$1.ROOM_RECONNECTING].next(e)}function handleBloudRoomReconnected(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){t.hasSyncPermission?(info("bloud room reconnected"),t.bloudWSReconnectWatcher.next(!1),r[BCEvent$1.MOVE_USER_ROOM].next(null),yield t.syncRoom().then((()=>{t.hasSyncPermission=!0,r[BCEvent$1.ROOM_RECONNECTED].next(e)})).catch((e=>{error$1("sync room error",JSON.stringify(e));if(43===e.code)return t.hasSyncPermission=!1,void r[BCEvent$1.USERREJOINED].next(e);t.hasSyncPermission=!1,r[BCEvent$1.NETWORK_ERROR].next(e)}))):r[BCEvent$1.NETWORK_ERROR].next(e)}))}function handleBloudRoomSync(e,t,r,i,n){return __awaiter$2(this,void 0,void 0,(function*(){info("bloud sync room completed"),setupRoomInfo(e,r,t),yield handleRoomSync(e,r,t,i),handleBloudReconnectStreamEvent(i),r.networkState.bloud=!0,handleReconnectedStream(r),r.bloudWSReconnectWatcher.next(!0),n[BCEvent$1.ROOM_SYNC].next(e)}))}function handleParticipantJoin(e,t,r,i,n,s){var o,a,c,u,d,l,h,m,p,f,g,v,_;const y=null===(a=null===(o=null==e?void 0:e.participant)||void 0===o?void 0:o.params)||void 0===a?void 0:a.info.sync,S=e.mode;info("用户入会","用户入会",e.user.userId,["sync => ",y,"mode =>",S]);const E=t.room.isBig&&r.streamModels.size>1e3;let b=!1;if(y){let r=t.userList.get(e.user.userId);if(r||(r=t.commonUserList.get(e.user.userId)),r)return void(r.inBackground!=!!(null===(u=null===(c=e.user)||void 0===c?void 0:c.customInfo)||void 0===u?void 0:u.inBackground)&&(r.inBackground=!!(null===(l=null===(d=e.user)||void 0===d?void 0:d.customInfo)||void 0===l?void 0:l.inBackground),r.watcher.next({operation:"inBackground",user:r})))}1===S&&(null===(h=t.room)||void 0===h?void 0:h.isBig)&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId));if(getIsCommonUser(e.user.permission.permission)){t.userList.get(e.user.userId)&&(t.userList.delete(e.user.userId),r.streamModels.delete(e.user.userId),b=!0)}else{const i=t.commonUserList.get(e.user.userId);(null===(m=t.room)||void 0===m?void 0:m.isSingleColumns)||i&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId),b=!0)}let T=t.addBCUser(e.user);if(T){T.inBackground!=!!(null===(f=null===(p=e.user)||void 0===p?void 0:p.customInfo)||void 0===f?void 0:f.inBackground)&&(T.inBackground=!!(null===(v=null===(g=e.user)||void 0===g?void 0:g.customInfo)||void 0===v?void 0:v.inBackground),T.watcher.next({operation:"inBackground",user:T}));let o=!1;if(ignoreUserId.forEach((e=>{(null==T?void 0:T.userId.includes(e))&&(o=!0)})),b?t.updateAllSort():(null===(_=t.room)||void 0===_?void 0:_.isSingleColumns)?t.updateCommonUserSort():T?T.isCommonUser?E?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),!o){if(1!==e.mode){const e=new BMMessageInfo({isMeetingNotice:!0,userId:T.userId,message:T.nickName+"加入"+(2==i.roomType?"直播":"会议")});n.addMessage(e,!0)}s[BCEvent$1.JOINUSER].next({user:T,mode:S,data:e})}}}function handleLeaveUsers(e,t,r,i,n,s,o){var a;const c=e.userIds;info("bloud leave users","","",["userIds =>",c]),c.length&&(c.forEach((e=>{const a=leaveUser(e,t,r,n);a&&sendLeveNotification(a,s,o,i,!0,0)})),(null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():t.updateAllSort(),n.updateModelSort())}function handleParticipantLeft(e,t,r,i,n,s,o){var a;info(`bloud participant left ===>${e.userId}, ${e.mode}`);const c=1===e.mode,u=e.userId,d=r.isBig&&n.streamModels.size>1e3;if(u){const l=leaveUser(u,t,r,n);if((null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():l?l.isCommonUser?d?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),n.updateModelSort(),c)return void i[BCEvent$1.LEAVEUSER].next({user:l,mode:e.mode,data:e});l&&sendLeveNotification(l,s,o,i,1!==e.mode,e.mode)}else warn("participant-left触发=======>但是该用户信息不存在",LOGGER_TAG_CLIENT,null,[e.userId]),i[BCEvent$1.LEAVEUSER].next({user:e.userId,mode:e.mode,data:e})}function sendLeveNotification(e,t,r,i,n,s){let o=!1;if(ignoreUserId.forEach((t=>{(null==e?void 0:e.userId.includes(t))&&(o=!0)})),!o){if(n){const i=new BMMessageInfo({isMeetingNotice:!0,userId:e.userId,message:(null==e?void 0:e.nickName)+"离开"+(2==t.roomType?"直播":"会议")});r.addMessage(i,!0)}i[BCEvent$1.LEAVEUSER].next({user:e,mode:s})}}function leaveUser(e,t,r,i){const n=t.getUser(e);return t.removeUser(e),r.streamQueue.removeUsers([{id:e,isScreen:!1},{id:e,isScreen:!0}]),i.removeStreamModelByUId(e),i.removeShareStreamModelByUId(e),r.roomInfo.removeRaiseHandUser(e),r.roomInfo.removeVideoRaiseHandUser(e),r.roomInfo.removeSimpleRaiseHandUser(e),n}function handleChangeMaster(e,t,r,i,n){info("changeMaster =>","changeMaster","",["master: => ",e.master,"oldMaster =>",e.oldMaster]);const s=e.master,o=e.oldMaster,a=e.isKeep;if(s){let c=t.updateMaster(s,o,a);c.master&&(c.master.watcher.next({operation:"getMaster",user:c.master}),r.userVM.masterUserWatcher.next(c.master)),c.oldMaster&&(c.oldMaster.watcher.next({operation:"removeMaster",user:c.oldMaster}),a&&c.oldMaster.watcher.next({operation:"getManager",user:c.oldMaster}));const u=n.getStreamModelByUId(o),d=n.getStreamModelByUId(s);null==u||u.updateSortNum(),null==d||d.updateSortNum(),i[BCEvent$1.CHANGEMASTER].next({master:c.master,oldMaster:c.oldMaster,data:e})}else warn("change-master触发=======>但是房间内找不到master",LOGGER_TAG_CLIENT,null,s),i[BCEvent$1.CHANGEMASTER].next(null)}function handleEvict(e,t,r,i,n){var s;const o=e.userId,a=t.getUser(o);info("踢出用户 => ","evict ",null==a?void 0:a.userId,["nickname => ",null==a?void 0:a.nickName]);const c=leaveUser(o,t,i,r);(null===(s=t.room)||void 0===s?void 0:s.isSingleColumns)?t.updateCommonUserSort():c?c.isCommonUser?t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),n[BCEvent$1.EVICTED].next(e)}function handleUpdateUser(e,t,r,i,n){var s,o;if(info("用户信息被改变","",null===(s=e.user)||void 0===s?void 0:s.userId),null===(o=e.user)||void 0===o?void 0:o.userId){let s=t.getUser(e.user.userId),o=i.getStreamModelByUId(e.user.userId);s?s.updateUserInfo(e.user,e.participant,r):console.warn("participant-update: bmUser is null"),o&&o.updateSortNum(!0),n[BCEvent$1.UPDATEUSER].next({bmUser:s,params:e.participant.params})}}const handleUserRejoined=debounce(((e,t,r)=>{e[t.USERREJOINED].next(r)}),1e3);function handleMoveUserRoom(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){info("bloud move user room","","",[r]);const n=r.toWait;if(e.isInWaitRoom=n,n){e.handleResetOtherStreamStatus(),t.userList.clear(),t.userListWatcher.next([]),t.commonUserList.clear(),t.commonUserListWatcher.next([]),e.bmStreamVm.streamModels.clear(),i[BCEvent$1.CUSTOMMESSAGE].next(null),e.messageWatcher.next({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),e.audioPlayer.destroy();const r=e.bmStreamVm.localModel;r&&e.bmStreamVm.streamModels.set(r.userId,r),e.bmStreamVm.streamModelsWatcher.next([]),e.bmStreamVm.shareStreamModels.clear(),e.bmStreamVm.shareStreamModelsWatcher.next([]),e.roomInfo.raiseHandsWatcher.next([]),e.roomInfo.raiseVideoHandsWatcher.next([]),e.roomInfo.raiseSimpleHandsWatcher.next([])}else{yield handleRoomConnected(r.info,e,t,i,!1);const{audioOff:n,selfopenaudio:s,lock:o}=r.info;o!==e.roomInfo.lock&&e.roomInfo.setlock(o),n===e.roomInfo.audioOff&&s===e.roomInfo.selfopenaudio||e.roomInfo.setAudioOff(n,s),yield handleInitJoinRoomUsers(e)}i[BCEvent$1.MOVE_USER_ROOM].next(n)}))}function handleSendMessage(e,t,r,i){var n,s,o,a,c,u,d,l,h;let m=Object.assign({},e);if(m.message){if(m.message="string"==typeof m.message?JSON.parse(m.message):m.message,info("new-message","","",[" method => ",m.message.method]),"send-talk"===m.message.method){const i=m.user===(null===(n=t.getLocalUser())||void 0===n?void 0:n.userId),p=(null===(o=null===(s=m.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.status)||"",f=null===(u=null===(c=null===(a=m.message)||void 0===a?void 0:a.params)||void 0===c?void 0:c.stream)||void 0===u?void 0:u.avatar,g=e.seq,v=new BMMessageInfo({userId:m.user,message:p,isLocal:i,avatar:f,to:m.to,seq:g,nickName:null===(h=null===(l=null===(d=m.message)||void 0===d?void 0:d.params)||void 0===l?void 0:l.stream)||void 0===h?void 0:h.nickname,sendTime:(new Date).getTime()});r.addMessage(v,!1)}i[BCEvent$1.SENDMESSAGE].next(m)}}function handleCustomMessage(e,t,r){var i,n,s,o,a,c,u,d,l,h,m,p,f;let g=Object.assign({},e);if(g.message)if(g.message="string"==typeof g.message?JSON.parse(g.message):g.message,info("custom-message","","",[" method => ",g.message.method]),"video-force-change"==g.message.method){const e="enabled"==g.message.params.status;info(`远端控制本地摄像头: ${e}`),t.messageWatcher.next({type:MessageType.VIDEO_FORCE_CHANGE,status:e,fromUserId:g.user})}else if("audio-force-change"==g.message.method){let e;e="checkUserAudio"==g.message.params.status?g.message.params.status:"enabled"==g.message.params.status,info(`远端控制本地麦克风: ${e}`),t.messageWatcher.next({type:MessageType.AUDIO_FORCE_CHANGE,status:e,fromUserId:g.user,isNotCancelRootReport:null===(i=g.message.params)||void 0===i?void 0:i.isNotCancelRootReport})}else if("raise-hands"===g.message.method)t.raiseHandleRespWatcher.next(g.message.params);else if("give-like"===g.message.method)null===(n=t.roomVM)||void 0===n||n.giveLikeList.push({userId:g.user,nickName:null===(a=null===(o=null===(s=g.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.stream)||void 0===a?void 0:a.nickname,time:(new Date).getTime(),type:null===(d=null===(u=null===(c=g.message)||void 0===c?void 0:c.params)||void 0===u?void 0:u.stream)||void 0===d?void 0:d.type}),null===(l=t.roomVM)||void 0===l||l.giveLikeListWatcher.next(null===(h=t.roomVM)||void 0===h?void 0:h.giveLikeList);else if("resp-to-check-devices"===g.message.method)(null===(m=g.message)||void 0===m?void 0:m.params)&&(g.message.params.fromUserId=g.user),r[BCEvent$1.CUSTOMMESSAGE].next(g);else if("usercount"===g.message.method){if(g.message.params){let e=null===(f=null===(p=g.message)||void 0===p?void 0:p.params)||void 0===f?void 0:f.total;e?(e=Number(e),e<0&&(warn("服务返回的usercount为负数,"+e),e=0)):(warn("服务未返回usercount,"+e),e=0),t.roomInfo.totalUserWatcher.next(e)}}else if("waitusercount"===g.message.method){if(g.message.params){const e=g.message.params.total;t.roomInfo.totalWaitRoomUserWatcher.next(e)}}else r[BCEvent$1.CUSTOMMESSAGE].next(g)}let reconnectFailed=0,shareReconnectFailed=0;const NETWORK_ERROR_QUEUE=new Set;function handleBRTCRoomError(e,t,r,i,n){return __awaiter$2(this,void 0,void 0,(function*(){error$1("brtc error","brtc error","",[(new Date).toLocaleTimeString(),JSON.stringify(e),e.getCode()]);if(4002===e.getCode()){t.BRTCConnectFailed=!0,t.networkState.brtc=!1,warn("brtc 信令通道错误,需要重新走入会","brtc error",""),t.streamWSReconnectWatcher.next(!1);try{yield r.brtcClient.leave("room_close")}catch(e){error$1("brtc 离会失败")}setTimeout((()=>__awaiter$2(this,void 0,void 0,(function*(){t.handleResetOtherStreamStatus(),yield reconnectBrtcWS(r,t,n,e).catch((t=>{info("brtc断网重连失败, 处理一下退会逻辑","","",[JSON.stringify(t)]),n[BCEvent$1.ERROR].next(e)}))}))),1e3)}else n[BCEvent$1.ERROR].next(e)}))}function reconnectBrtcWS(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{setTimeout((()=>{info("brtc重连"),e.brtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>__awaiter$2(this,void 0,void 0,(function*(){info("brtc断网重连成功, 重新处理拉流和推流"),t.networkState.brtc=!0,setTimeout((()=>{t.brtcNetEnableWatcher.next(!0)}),2e3),handleReconnectedStream(t),t.BRTCConnectFailed=!1,reconnectFailed=0,yield t.handleRePushSelf(),t.streamWSReconnectWatcher.next(!0),n(!0)})))).catch((n=>{const o=n.getCode();info("断网重连入会失败","","",[n,o]),reconnectFailed<=10?(reconnectFailed+=1,e.brtcClient.isJoinning=!1,setTimeout((()=>{reconnectBrtcWS(e,t,r,i)}),2e3)):(error$1("brtc断网重连失败,处理一下退会"),reconnectFailed=0,r[BCEvent$1.ERROR].next(i),s(!1))}))}),7e3)}))}))}function reconnectBRTCShareWS(e){return __awaiter$2(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{setTimeout((()=>{info("共享屏幕重连"),e.shareBrtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>{shareReconnectFailed=0,t(!0)})).catch((t=>{const r=t.getCode();if(info("共享屏幕断网重连入会失败","","",[t,r]),!(shareReconnectFailed<=3))throw error$1("共享屏幕用户重连失败,处理一下取消共享屏幕"),shareReconnectFailed=0,new Error("共享屏幕重连失败");shareReconnectFailed+=1,reconnectBRTCShareWS(e)}))}),7e3)}))}))}function handleBloudError(e,t,r,i,n){return __awaiter$2(this,void 0,void 0,(function*(){error$1("network-error","network-error","local-client",["本地链接出现问题","netconnectiong => ",e.netConnecting]),e.netConnecting?yield handleBloudRoomReconnected(i,e,n):n[BCEvent$1.NETWORK_ERROR].next(i)}))}function handleCustomStats(e,t,r){let i=null==e?void 0:e.updateKeys;info("update-custom-stats"," "," ",["updateKeys => ",JSON.stringify(i)]),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich"))||(null==i?void 0:i.includes("fileUpdateLook"))||(null==i?void 0:i.includes("fileUpdateDown"))||(null==i?void 0:i.includes("fileUpdateEdit"))||(null==i?void 0:i.includes("fileUpdateModel"))||(null==i?void 0:i.includes("screenShareModel"))||(null==i?void 0:i.includes("onlyOnePersonShare"))||(null==i?void 0:i.includes("chatEnable"))||(null==i?void 0:i.includes("giveLikeEnable"))||(null==i?void 0:i.includes("cloudRecord"))||(null==i?void 0:i.includes("joinAudioEnable"))||(null==i?void 0:i.includes("joinVideoEnable"))||(null==i?void 0:i.includes("userListEnable"))||(null==i?void 0:i.includes("audioEnable"))||(null==i?void 0:i.includes("videoEnable"))||(null==i?void 0:i.includes("modifyNameEnable"))||(null==i?void 0:i.includes("backgroundAIEnable"))||(null==i?void 0:i.includes("recordEnable"))||(null==i?void 0:i.includes("joinMicrophoneDisable"))||(null==i?void 0:i.includes("joinCameraDisable"))||(null==i?void 0:i.includes("raiseHandEnable"))||(null==i?void 0:i.includes("forceOpenUserMic"))||(null==i?void 0:i.includes("forceOpenUserCamera"))||(null==i?void 0:i.includes("joinCueVoice")))&&t.roomInfo.updateOperationPermission(e.customStats),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich")))&&t.roomInfo.chatNoticeWatcher.next(e),r[BCEvent$1.CUSTOMSTATS].next(e)}var dist={},eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,i,s,o){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new n(i,s||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,o=new Array(s);n<s;n++)o[n]=i[n].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,n,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,u,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,s),!0;case 6:return d.fn.call(d.context,t,i,n,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var h,m=d.length;for(u=0;u<m;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,i);break;case 4:d[u].fn.call(d[u].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,n){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||n&&!a.once||i&&a.context!==i||o(this,s);else{for(var c=0,u=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||i&&a[c].context!==i)&&u.push(a[c]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(eventemitter3);var pTimeout$1={exports:{}},pFinally$1=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))));const pFinally=pFinally$1;class TimeoutError extends Error{constructor(e){super(e),this.name="TimeoutError"}}const pTimeout=(e,t,r)=>new Promise(((i,n)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const s=setTimeout((()=>{if("function"==typeof r){try{i(r())}catch(e){n(e)}return}const s=r instanceof Error?r:new TimeoutError("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),n(s)}),t);pFinally(e.then(i,n),(()=>{clearTimeout(s)}))}));pTimeout$1.exports=pTimeout,pTimeout$1.exports.default=pTimeout,pTimeout$1.exports.TimeoutError=TimeoutError;var priorityQueue={},lowerBound$1={};function lowerBound(e,t,r){let i=0,n=e.length;for(;n>0;){const s=n/2|0;let o=i+s;r(e[o],t)<=0?(i=++o,n-=s+1):n=s}return i}Object.defineProperty(lowerBound$1,"__esModule",{value:!0}),lowerBound$1.default=lowerBound,Object.defineProperty(priorityQueue,"__esModule",{value:!0});const lower_bound_1=lowerBound$1;class PriorityQueue{constructor(){Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]})}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const i=lower_bound_1.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}priorityQueue.default=PriorityQueue,Object.defineProperty(dist,"__esModule",{value:!0});const EventEmitter=eventemitter3.exports,p_timeout_1=pTimeout$1.exports,priority_queue_1=priorityQueue,empty=()=>{},timeoutError=new p_timeout_1.TimeoutError;class PQueue extends EventEmitter{constructor(e){var t,r,i,n;if(super(),Object.defineProperty(this,"_carryoverConcurrencyCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isIntervalIgnored",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalCap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalEnd",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queueClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_concurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isPaused",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveEmpty",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_resolveIdle",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_throwOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:priority_queue_1.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(n=null===(i=e.interval)||void 0===i?void 0:i.toString())&&void 0!==n?n:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother()}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=empty,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=empty)}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={},r=null){return new Promise(((i,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const s=void 0===this._timeout&&void 0===t.timeout?e():p_timeout_1.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(timeoutError),r&&r("resolve-timeout")}));r&&r("resolving"),i(await s),this._isPaused?r&&r("resolve-paused"):r&&r("resolve")}catch(e){this._isPaused?r&&r("resolve-paused"):r&&r("resolve"),n(e)}this._next()}),t),this._tryToStartAnother()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}var _default=dist.default=PQueue;class Pqueue{constructor(e,t=!0){this.queue=new _default({concurrency:e,autoStart:t,carryoverConcurrencyCount:!0,timeout:3e3,completeAction:e=>{console.log("task complete",e)}}),this.queueArray=[],this.isTaskPending=t}addQueue(e,t,r=0,i=""){this.queue.isPaused&&this.queue.start();let n={};n.taskID=t,n.status="pending",this.queue.add(e,{priority:r,timeout:3e3},(e=>{if(n.status=e,"resolve"===n.status||"resolve-paused"===n.status||"resolve-timeout"===n.status){const e=this.queueArray.findIndex((e=>n.taskID===e.taskID));-1!==e&&this.queueArray.splice(e,1)}})),this.queueArray.push(n)}clearQueue(){this.queue.clear(),this.queueArray=[],this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{console.log("clearQueue全部完事")}))}startQueue(){this.queue.start()}pauseQueue(){return this.queue.pause(),console.log(`size:${this.size()}`),this.isTaskPending=!1,this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{})),this.queueArray}size(){return this.queue.size}pending(){return this.queue.pending}checkTaskStatus(){return this.isTaskPending}setTaskStatus(e){this.isTaskPending=e}onIdle(){return this.queue.onIdle()}onEmpty(){return this.queue.onEmpty()}}const streamPullQueue=new Pqueue(4),eventQueue=new Pqueue(10);var MessageType;function attachEvents(e,t,r,i,n){info("attachEvents init");let s={};return e.on("toggle-screen-share",(()=>{error$1("share stream video track ended, now unpublish share stream"),r.localShareError.next(BMShareStreamReconnectFailed()),r.toggleShareScreen(!1,void 0).then((()=>{}))})),e.on("client-banned",(()=>__awaiter$2(this,void 0,void 0,(function*(){yield n.boomCore.leaveShare()})))),e.on("share-brtc-error",(t=>__awaiter$2(this,void 0,void 0,(function*(){if(4002===t.getCode())try{info("brtc share client disconnected, reconnecting"),yield e.shareBrtcClient.leave("room_close"),reconnectBRTCShareWS(e).then((()=>__awaiter$2(this,void 0,void 0,(function*(){info("brtc share client reconnected, retry repub share stream"),yield sleep(1e3);const t=e.shareScreenStream.getAudioOn(),r=e.shareScreenStream.getVideoOn();e.shareBrtcClient.publish(e.shareScreenStream),e.createAndPubBloudShareStream(t,r)})))).catch((e=>{throw new Error("共享屏幕重新入会失败")}))}catch(e){r.toggleShareScreen(!1,void 0).then((()=>{})).catch((e=>{error$1("共享发生错误退会失败","","",[JSON.stringify(e)])}))}})))),Object.values(BCEvent).forEach((e=>{s[e]=new BehaviorSubject(null)})),Object.values(BCEvent).forEach((o=>{switch(o){case BCEvent.STREAM_PUBLISHED:e.on(BCEvent.STREAM_PUBLISHED,(e=>{eventQueue.addQueue(handleStreamPublished.bind(null,e,r,n,s),BCEvent.STREAM_PUBLISHED)}));break;case BCEvent.BRTC_SYNC_ROOM_COMPLETED:e.on(BCEvent.BRTC_SYNC_ROOM_COMPLETED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(n.handleResetOtherStreamStatus.bind(n),BCEvent.BRTC_SYNC_ROOM_COMPLETED)}))));break;case BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED:e.on(BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED,(()=>{info("brtc share client sync completed, retry publish share stream"),eventQueue.addQueue(handleShareStreamFailed.bind(null,n,r),BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));break;case BCEvent.BRTC_ROOM_ROCONNECTING:e.on(BCEvent.BRTC_ROOM_ROCONNECTING,(e=>{eventQueue.addQueue(handleBrtcRoomReconnecting.bind(null,e,n,s),BCEvent.BRTC_ROOM_ROCONNECTING)}));break;case BCEvent.BRTC_ROOM_RECONNECTED:e.on(BCEvent.BRTC_ROOM_RECONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBrtcRoomReconnected.bind(null,e,n,s),BCEvent.BRTC_ROOM_RECONNECTED)}))));break;case BCEvent.CLIENT_BANNED:e.on(BCEvent.CLIENT_BANNED,(e=>{info("brtc client banned"),handleUserRejoined(s,BCEvent,e)}));break;case BCEvent.ERROR:e.on(BCEvent.ERROR,(t=>__awaiter$2(this,void 0,void 0,(function*(){n.netConnecting?eventQueue.addQueue(handleBRTCRoomError.bind(null,t,n,e,r,s),BCEvent.ERROR):NETWORK_ERROR_QUEUE.add(handleBRTCRoomError.bind(null,t,n,e,r,s))}))));break;case BCEvent.ROOM_ERROR:e.on(BCEvent.ROOM_ERROR,(e=>{error$1("bloud sync failed, leave room"),s[BCEvent.NETWORK_ERROR].next(e)}));break;case BCEvent.ROOM_CONNECTED:e.on(BCEvent.ROOM_CONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){return handleRoomConnected(e,n,t,s)}))));break;case BCEvent.JOIN_READY:e.on(BCEvent.JOIN_READY,(()=>handleInitJoinRoomUsers(n)));break;case BCEvent.JOINUSER:e.on(BCEvent.JOINUSER,(o=>__awaiter$2(this,void 0,void 0,(function*(){n.isInWaitRoom||eventQueue.addQueue(handleParticipantJoin.bind(null,o,t,r,e,i,s),BCEvent.JOINUSER)}))));break;case BCEvent.LEAVEUSER:e.on(BCEvent.LEAVEUSER,(o=>{n.isInWaitRoom||eventQueue.addQueue(handleParticipantLeft.bind(null,o,t,n,s,r,e,i),BCEvent.LEAVEUSER)}));break;case BCEvent.LEAVE_USERS:e.on(BCEvent.LEAVE_USERS,(o=>eventQueue.addQueue(handleLeaveUsers.bind(null,o,t,n,s,r,e,i),BCEvent.LEAVE_USERS)));break;case BCEvent.CHANGEMASTER:e.on(BCEvent.CHANGEMASTER,(e=>{eventQueue.addQueue(handleChangeMaster.bind(null,e,t,n,s,r),BCEvent.CHANGEMASTER)}));break;case BCEvent.SENDMESSAGE:e.on(BCEvent.SENDMESSAGE,(e=>{eventQueue.addQueue(handleSendMessage.bind(null,e,t,i,s),BCEvent.SENDMESSAGE)}));break;case BCEvent.CUSTOMMESSAGE:e.on(BCEvent.CUSTOMMESSAGE,(e=>{eventQueue.addQueue(handleCustomMessage.bind(null,e,n,s),BCEvent.CUSTOMMESSAGE)}));break;case BCEvent.EVICTED:e.on(BCEvent.EVICTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleEvict.bind(null,e,t,r,n,s),BCEvent.EVICTED)}))));break;case BCEvent.UPDATEUSER:e.on(BCEvent.UPDATEUSER,(e=>{eventQueue.addQueue(handleUpdateUser.bind(null,e,t,n,r,s),BCEvent.UPDATEUSER)}));break;case BCEvent.UPDATESTATS:e.on(BCEvent.UPDATESTATS,(e=>{eventQueue.addQueue(handleRoomUpdated.bind(null,e,n),BCEvent.UPDATESTATS)}));break;case BCEvent.CUSTOMSTATS:e.on(BCEvent.CUSTOMSTATS,(e=>{eventQueue.addQueue(handleCustomStats.bind(null,e,n,s),BCEvent.CUSTOMSTATS)}));break;case BCEvent.NETWORK_ERROR:e.on(BCEvent.NETWORK_ERROR,(t=>{eventQueue.addQueue(handleBloudError.bind(null,n,e,r,t,s),BCEvent.NETWORK_ERROR)}));break;case BCEvent.USERREJOINED:e.on(BCEvent.USERREJOINED,(e=>{info("bloud user rejoined"),handleUserRejoined(s,BCEvent,e)}));break;case BCEvent.ROOM_RECONNECTING:e.on(BCEvent.ROOM_RECONNECTING,(e=>{eventQueue.addQueue(handleBloudRoomReconnecting.bind(null,e,n,s),BCEvent.ROOM_RECONNECTING)}));break;case BCEvent.ROOM_RECONNECTED:e.on(BCEvent.ROOM_RECONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomReconnected.bind(null,e,n,s),BCEvent.ROOM_RECONNECTED)}))));break;case BCEvent.ROOM_SYNC:e.on(BCEvent.ROOM_SYNC,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomSync.bind(null,e,t,n,r,s),BCEvent.ROOM_SYNC)}))));break;case BCEvent.PUBLISHED:e.on(BCEvent.PUBLISHED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPublished.bind(null,e,r,s),BCEvent.PUBLISHED)}))));break;case BCEvent.UNPUBLISH:e.on(BCEvent.UNPUBLISH,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUnPublished.bind(null,e,r,s),BCEvent.UNPUBLISH)}))));break;case BCEvent.UPDATE_STREAM:e.on(BCEvent.UPDATE_STREAM,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUpdated.bind(null,e,r,s),BCEvent.UPDATE_STREAM)}))));case BCEvent.BLOUD_STREAM_UPDATED:e.on(BCEvent.BLOUD_STREAM_UPDATED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPubAUpdate.bind(null,e,r),BCEvent.BLOUD_STREAM_UPDATED)}))));break;case BCEvent.MOVE_USER_ROOM:e.on(BCEvent.MOVE_USER_ROOM,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleMoveUserRoom.bind(null,n,t,e,s),BCEvent.MOVE_USER_ROOM)}))));break;default:e.on(o,(e=>s[o].next(e)))}})),s}!function(e){e.INIT="init",e.VIDEO_FORCE_CHANGE="video-force-change",e.AUDIO_FORCE_CHANGE="audio-force-change"}(MessageType||(MessageType={}));class BMRoomVM{constructor(e,t,r){this.room=null,this.tipQueueObj={},this.roomInfo=r,this.userVM=t,this.boomCore=e,this.giveLikeList=[],this.giveLikeListWatcher=new Subject}initWithRoom(e){this.room=e}evictUser(e,t){return __awaiter$2(this,void 0,void 0,(function*(){if(!e)return Promise.reject(BmEvictUserError("未传递用户id"));if(!this.userVM.checkLocalHasMaster())return Promise.reject(BmEvictUserError("只有主持人权限才能踢出用户"));if(this.userVM.checkIsMaster(e))return Promise.reject(BmEvictUserError("主持人不能被踢出"));try{yield this.boomCore.evictUser(e,t)}catch(e){return Promise.reject(BmEvictUserError(`踢出用户失败${JSON.stringify(e)}`))}}))}updateUser(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return e?t?void(yield this.boomCore.updateUser(e,{customInfo:t}).catch((e=>Promise.reject(BmUpdateUserError(`boomCore updateUser出错 ${JSON.stringify(e)}`))))):Promise.reject(BmUpdateUserError("info为空,请写入要更新的信息")):Promise.reject(BmUpdateUserError("未传递目标用户id"))}))}changeMaster(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()||(null===(r=this.userVM.getUser(e))||void 0===r?void 0:r.isCreate)?yield this.boomCore.changeMaster(e,t).catch((e=>Promise.reject(BmChangeMasterError(`boomCore changeMaster error ${e}`)))):(console.error("该用户没有管理员权限, 无法改变主持人",LOGGER_TAG_CLIENT,e),Promise.reject(BmChangeMasterError("您没有管理员权限, 无法改变主持人"))):Promise.reject(BmChangeMasterError("未传递主持人id"))}))}updateManager(e,t,r=!0){return __awaiter$2(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()?this.userVM.updateManager(e,t,r):(console.error("该用户没有管理员权限, 无法改变联席主持人",LOGGER_TAG_CLIENT,e),Promise.reject(BmUpdateManagerError("该用户没有管理员权限, 无法改变主持人"))):Promise.reject(BmUpdateManagerError("未传递联席主持人id"))}))}changeNickName(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={nickname:t};yield this.updateUser(e,r)}))}sendMessageWithMaster(e,t){return __awaiter$2(this,void 0,void 0,(function*(){if(!this.userVM.checkLocalHasMaster())return Promise.reject(BmSetRemoteAudioEnable("您不是主持人,没有该权限"));if(t){if(!this.userVM.getUser(t))return Promise.reject(BmSetRemoteAudioEnable(`uid: ${t} 未找到用户`))}try{yield this.boomCore.customMessage(JSON.stringify(e),t)}catch(e){return Promise.reject(e)}}))}setRemoteAudioEnable(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){let i=e?"enabled":"disabled";"enabled"==i&&r&&(i="checkUserAudio");let n={domain:"room-control",method:"audio-force-change",params:{status:i,isNotCancelRootReport:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(n,t).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}setRemoteVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){let r={domain:"room-control",method:"video-force-change",params:{status:e?"enabled":"disabled",fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(BmSetRemoteVideoEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}closeRemoteShare(e){return __awaiter$2(this,void 0,void 0,(function*(){let t={domain:"room-control",method:"close-remote-share",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}tipUser(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){let n={domain:"room-control",method:"tip-user",params:{fromUserId:this.boomCore.getLocalParticipant().getID(),message:t,richMsg:r}};i?this.tipQueueObj[e]=setTimeout((()=>{this.sendMessageWithMaster(n,e)}),60*(i.minutes||0)*1e3+1e3*(i.seconds||0)):this.sendMessageWithMaster(n,e).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${JSON.stringify(e)}`))))}))}raiseHands(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){const i=null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().getID();let n={};"raiseHand"===e?(n.raiseHand=t,n.raiseHandTime=Math.floor((new Date).getTime()/1e3)):n["audio"===e?"raiseHandsAudio":"raiseHandsVideo"]=t,yield this.updateUser(i,n)}))}handleRaiseHands(e,t,r){var i,n,s;return __awaiter$2(this,void 0,void 0,(function*(){let o={domain:"user-control",method:"raise-hands",params:{raiseHandsType:e,raiseHands:t}};try{if(r)yield this.boomCore.customMessage(JSON.stringify(o),r);else{const t=null===(i=this.room)||void 0===i?void 0:i.roomInfo.raiseHandsWatcher.getValue(),r=null===(n=this.room)||void 0===n?void 0:n.roomInfo.raiseVideoHandsWatcher.getValue(),a=null===(s=this.room)||void 0===s?void 0:s.roomInfo.raiseSimpleHandsWatcher.getValue();0===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})),null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),1===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),2===e&&(null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),3===e&&(null==a||a.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})))}}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"boomCore.sendMessage发生错误"))}}))}updateCustomStats(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){yield this.boomCore.updateCustomStats(e,t).catch((t=>Promise.reject(updateCustomStatsError(`${JSON.stringify(e)} - ${JSON.stringify(t)}`))))}))}sendChatNotice(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatNotice:e,chatNoticeRich:t,showTipNotice:r}).catch((e=>e))}))}giveLikeEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({giveLikeEnable:e}).catch((e=>e))}))}changeAutoMute(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({autoMute:e})}))}allUserReceiveJoinLeaveMessages(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({allUserReceiveJoinLeaveMessages:e})}))}userJoinMasterVoice(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({userJoinMasterVoice:e})}))}userGiveLike(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){let i=(new Date).getTime(),n={domain:"room-control",method:"give-like",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:i,nickname:this.userVM.localUser.nickName,type:e||1}}},s=this.userVM.getLocalUser();try{yield this.boomCore.customMessage(JSON.stringify(n),void 0),this.giveLikeList.push({userId:null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant().userId,nickName:null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().nickName,time:(new Date).getTime(),type:e}),this.giveLikeListWatcher.next(this.giveLikeList)}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==s?void 0:s.userId),new BoomError$1(CLIENT_BANNED,"用户点赞==>sendMessage出错")}}))}chatEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatEnable:e}).catch((e=>e))}))}joinAudioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinAudioEnable:e}).catch((e=>e))}))}joinVideoEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinVideoEnable:e}).catch((e=>e))}))}userListEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({userListEnable:e}).catch((e=>e))}))}audioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({audioEnable:e}).catch((e=>e))}))}videoEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({videoEnable:e}).catch((e=>e))}))}modifyNameEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({modifyNameEnable:e}).catch((e=>e))}))}backgroundAIEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({backgroundAIEnable:e}).catch((e=>e))}))}forceOpenUserCamera(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserCamera:e}).catch((e=>e))}))}forceOpenUserMic(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserMic:e}).catch((e=>e))}))}joinCueVoice(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCueVoice:e}).catch((e=>e))}))}recordEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({recordEnable:e}).catch((e=>e))}))}raiseHandEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({raiseHandEnable:e}).catch((e=>e))}))}joinMicrophoneDisable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinMicrophoneDisable:e}).catch((e=>e))}))}joinCameraDisable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCameraDisable:e}).catch((e=>e))}))}changeFileUpdateModelPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateModel:e}).catch((e=>e))}))}changeFileUpdateLookPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateLook:e}).catch((e=>e))}))}changeFileUpdateDownPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateDown:e}).catch((e=>e))}))}changeFileUpdateEditPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateEdit:e}).catch((e=>e))}))}changeScreenShareModelPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({screenShareModel:e}).catch((e=>e))}))}changeOnlyOnePersonSharePermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({onlyOnePersonShare:e}).catch((e=>e))}))}setForceOnUser(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOn:{user:e}}).catch((e=>e))}))}updateHostLayout(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){if(this.userVM.checkLocalHasMaster())return this.updateCustomStats({from:{fromTag:"masterId"},hostLayout:e},t);info("您不是主持人,没有该上报权限",LOGGER_TAG_CLIENT)}))}checkDevices(e){return __awaiter$2(this,void 0,void 0,(function*(){const t={domain:"user-control",method:"check-devices",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(BmCheckDeviceError(`检测对方设备send-message发生错误: ${e}`))))}))}resp2CheckDevices(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-check-devices",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};if(!t)return Promise.reject(BmCheckDeviceError(`响应设备检测: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(BmCheckDeviceError(`响应响应设备检测send-message发生错误 ${e}`))}}))}changeRemoteVideoProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-video-profile",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(BmChangeVideoProfileError(`调节对方的视频分辨率send-message发生错误: ${e}`))))}))}resp2ChangeRemoteVideoProfile(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"resp-to-change-video-profile",params:{status:e,profile:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(BmChangeVideoProfileError(`响应调节视频分辨率: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(i),t)}catch(e){return Promise.reject(BmChangeVideoProfileError(`响应调节视频分辨率send-message发生错误 ${e}`))}}))}changeRemoteAudioProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-audio-profile",params:{microphoneDevice:e.microphoneDevice,speakerDevice:e.speakerDevice,echoCancellation:e.echoCancellation,noiseSuppression:e.noiseSuppression,autoGainControl:e.autoGainControl,speakerVolume:e.speakerVolume,microVolume:e.microVolume,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(BmChangeAudioProfileError(`调节音频send-message发生错误 ${JSON.stringify(e)}`))))}))}resp2ChangeRemoteAudioProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-change-audio-profile",params:{status:e,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(BmChangeAudioProfileError(`响应调节音频: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(BmChangeAudioProfileError(`响应调节音频send-message发生错误 ${e}`))}}))}}class BMChatVM{constructor(e,t,r){this.messageList=[],this.hasDangerMessageWatcher=new Subject,this.notificationMessageList=debounce((()=>{this.messageListWatcher.next(this.messageList)}),500),this.boomCore=e,this.userVM=t,this.bmRoom=r,this.messageListWatcher=new BehaviorSubject(this.messageList)}sendMessage(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){let i=e.replace(/(^\s*)|(\s*$)/g,""),n=(new Date).getTime(),s={domain:"room-control",method:"send-talk",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:n,nickname:this.userVM.localUser.nickName},status:i}},o=this.userVM.getLocalUser();try{let e,a=!1,c=r;c||(yield this.boomCore.sendMessage(JSON.stringify(s),t).then((t=>{e=t.seq})).catch((e=>{warn("sendmessage 出错","",null==o?void 0:o.userId,[e]),e&&39===e.code&&(a=!0,this.hasDangerMessageWatcher.next(!0))})));const u=new BMMessageInfo({userId:null==o?void 0:o.userId,message:i,isLocal:null==o?void 0:o.isLocal,avatar:null==o?void 0:o.avatar,nickName:null==o?void 0:o.nickName,sendTime:n,to:t,isDanger:a,seq:e,failed:c});return this.addMessage(u,!1),c?Promise.reject(u):Promise.resolve()}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==o?void 0:o.userId),new BoomError$1(CLIENT_BANNED,"发送聊天消息==>sendMessage出错")}}))}addMessage(e,t){if(!t||this.bmRoom.participantNotice){if(0==this.messageList.length||e.timeStamp-this.messageList[this.messageList.length-1].timeStamp>=notGetTalkInterval){const e=new BMMessageInfo({isMeetingNotice:!0,message:""});this.messageList.push(e)}this.messageList.push(e),this.notificationMessageList()}}updateMessageListWatcher(e){this.messageList=e,this.messageListWatcher.next(this.messageList)}getHistoryMessage(){return __awaiter$2(this,void 0,void 0,(function*(){const e=yield this.boomCore.getMessages(0,this.boomCore.getMsgSeq());let t=[];return e.items.forEach((e=>{if(e.private||e.to)return!1;if(0==e.msg.length||-1==e.msg.indexOf("{"))return!1;const r=JSON.parse(e.msg);if("send-talk"!=r.method)return!1;const i=e.seq;let n=r.params,s=n.stream.user?n.stream.user:e.userId;n.stream.nickname,n.status,(new Date).getTime();const o=new BMMessageInfo({userId:s,message:n.status,nickName:n.stream.nickname,isLocal:s==this.userVM.localUser.userId,avatar:n.stream.avatar,sendTime:n.stream.sendTime,seq:i});t.push(o)})),Promise.resolve(t)}))}}class BMSpeaker{constructor(e,t){this.user=e,this.stream=t}getID(){return this.stream.getStreamId()}getUser(){return this.user}}function getMasterSort(e,t){return 16|~~e<<1|~~t}function getLocalSort(e,t){return 12|~~e<<1|~~t}function getManagerSort(e,t){return 8|~~e<<1|~~t}function getGuestSort(e,t){return 4|~~e<<1|~~t}const namespace=`.streammodel${Math.random()}`;class BMStreamModel{constructor(e,t){this.streamType=STREAM_TYPE.OTHER,this.pullFailedNum=0,this._video_enable=!1,this._audio_enable=!1,this.videoEnableWatcher=new BehaviorSubject(this._video_enable),this.audioEnableWatcher=new BehaviorSubject(this._audio_enable),this.streamUpdateWatcher=new Subject,this.isSubScribedWatcher=new Subject,this.playStateChangeWatcher=new Subject,this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.audioLevelWatcher=new Subject,this.isCurrentDisplay=!1,this.isDisplay=!1,this.isDisplayObserve=new Subject,this.isInBig=!1,this.isInBigObserve=new Subject,this._hasPulled=!1,this.playerId="",this.shouldPull=!1,this._pulledStreamType="small",this.pulledStreamGoal="small",this.bigPlayerId="",this.isPlayingBig=!1,this.muted=!1,this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount=0,this.sortNum=-1,this.handleDisplayChange=e=>{var t;this.isDisplay!==e&&(this.isDisplay=e,null===(t=this.stream)||void 0===t||t.stop(),this.isDisplay||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.pulledStreamType="small"),this.sendMessage2Room())},this.onPlayerStateChange=e=>{var t,r;"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&(info("播放失败, 需要调用 resume 方法"),this.playStateChangeWatcher.next(this)),"PAUSED"!==e.state&&"pause"!==e.reason||(this.player&&(null===(t=this.player)||void 0===t||t.resume()),null===(r=this.stream)||void 0===r||r.resume())},this.handleStreamConnectError=()=>{info("流出现的connect-error userId","",this.userId,["streamId ==>",this.streamId,"nickname =>",this.nickname,"isLocal => ",this.isLocal]),this.isLocal?BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!0}):BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!1})},this.bindElement=e=>{this.playerId=e,this.emitBindElement()},this.bindBigElement=e=>{this.bigPlayerId=e,this.emitBindBigElement()},this.sendMessage2Room=debounce((()=>{BoomEmitter.emitter.emit(RECEIVE_SUBSCRIBE_MESSAGE,{stream:this})}),30),this.emitBindElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_ELEMENT,{stream:this})}),50),this.emitBindBigElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_BIG_ELEMENT,{stream:this})}),50),this.currentIsPlaying=()=>{const e=document.getElementById(this.playerId);let t=!1,r=0;if(e){const i=e.querySelectorAll('div[id^="player_"]');t=i.length>0,i.forEach((e=>{0===e.children.length&&(r+=1)}))}return t&&0>r},this.currentBigIsPlaying=()=>{if(!!!document.getElementById(this.bigPlayerId))return!1;if(this.stream){const e=document.getElementById(`player_${this.stream.getStreamId()}_big_container`);let t=0,r=0;if(e){e.querySelectorAll('div[id^="player_"]').forEach((e=>{0===e.children.length&&(r+=1)}))}return e&&t>r}},this.play=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){var e;const t=this.stream;if(t)if(this.isDisplay&&this.videoEnable){const e=document.getElementById(this.playerId),r=!!e;let i=!1;if(e){const t=e.querySelectorAll('div[id^="player_"]');i=t.length>0,t.forEach((t=>{0===t.children.length&&(t.style.display="none",null==e||e.removeChild(t))}))}if(r)try{t.isPlaying()&&i||(t.stop(),yield t.play(this.playerId,{backgroundColor:"#202020",fit:"contain",audio:!autoPlayAudio}),this.checkSmallVideo()),info("远端流播放结束",this.userId,this.streamId,[this.nickname])}catch(e){t.stop(),setTimeout((()=>{error$1("播放小流失败, 尝试重新播放","播放",this.userId,[this.streamId,this.stream,"error => ",JSON.stringify(e)]),this.play()}),2e3)}else warn("找不到播放器容器","stream play",this.userId,["流 id =>",this.streamId,"nickname =>",this.nickname,"playerId =>",this.playerId]),this.playerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"small"})}else null===(e=this.stream)||void 0===e||e.stop()}))),300),this.playInBig=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){var e,t,r;const i=this.stream;if(i){const n=document.getElementById(this.bigPlayerId);if(n){n.querySelectorAll('div[id^="player_"]').forEach((e=>{0===e.children.length&&(e.style.display="none",null==n||n.removeChild(e))}))}this.isInBig?this.videoEnable?n?(null===(e=this.player)||void 0===e||e.destroy(),this.player=null,this.initBigPlayer(),this.player&&(yield this.player.play(i),this.isPlayingBig=!0,this.checkBigVideo()),info("远端流大流播放结束",this.userId,this.streamId,[this.nickname])):(warn("找不到 bigPlayerId","大流播放",this.userId,["流 id =>",this.streamId]),this.bigPlayerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"big"})):(null===(t=this.player)||void 0===t||t.destroy(),this.player=null,this.isPlayingBig=!1):(null===(r=this.player)||void 0===r||r.destroy(),this.player=null,this.isPlayingBig=!1)}}))),300),this.collectAudioLevel=()=>{this.stream?(this.stream.off("audio-level"+namespace,this.handleAudioLevel),this.stream.on("audio-level"+namespace,this.handleAudioLevel)):warn("collection audio level but not have brtc stream")},this.handleAudioLevel=e=>{this.audioLevelWatcher.next(e)},this.user=e,this.updateUser(e),this._stream=t,this.isDisplayObserve.subscribe((e=>{this.handleDisplayChange(e)})),this.isInBigObserve.subscribe((e=>{this.handleIsInBig(e)})),this.updateSortNum(!1)}get hasPulled(){return this._hasPulled}set hasPulled(e){this._hasPulled=e}get pulledStreamType(){return this._pulledStreamType}set pulledStreamType(e){this._pulledStreamType=e}get uuid(){return this.isShare?`${this.userId}_share`:this.userId}get isAudience(){return this.user.isAudience}get canShow(){return!this.isAudience||(this.audioEnable||this.videoEnable)}changeMute(e){this.muted!==e&&(this.muted=e,this.handleSpeakerChange())}handleSpeakerChange(){var e,t;this.isLocal||(this.muted?null===(e=this.stream)||void 0===e||e.setAudioVolume(0):null===(t=this.stream)||void 0===t||t.setAudioVolume(1))}get isToupingma(){return this.user.isToupingma}get isMixer(){return this.user.isMixer}get isSignal(){return this.user.isSignal}genReceiveSubMsg(){let e=null;return e=this.isDisplay?{audio:!0,video:!0,streamType:"small"}:{audio:!0,video:!1,streamType:"small"},e}handleIsInBig(e){this.isInBig!==e&&(this.isInBig=e,info("isInBig change","",this.userId,["streamId =>",this.streamId,"isInBig => ",e]),this.isInBig?this.pulledStreamGoal="big":this.pulledStreamGoal="small",this.sendMessage2Room(),this.isShare&&(this.isInBig||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0)))}setVideoEnable(e){this._video_enable!==e&&(this._video_enable=e,this.videoEnableWatcher.next(e))}setAudioEnable(e){this._audio_enable!==e&&(this._audio_enable=e,this.audioEnableWatcher.next(e))}updateStream(e,t=!0,r){if(this._stream&&this._stream.off(namespace),this._stream=e,e){this.streamType=e.type;const i=e.getVideoOn(),n=e.getAudioOn();info("更新用户的流","updateStream",null==e?void 0:e.getUserId(),["nickname =>",this.nickname,"audioOn",n,"videoOn",i,"streamId",e.getStreamId()]),n&&(this.isShare||r.addToDetector(new BMSpeaker(this.user,e)),this.collectAudioLevel()),e.on("player-state-changed"+namespace,this.onPlayerStateChange),e.on("connect-error"+namespace,this.handleStreamConnectError),e.on("stream-connection-error"+namespace,this.handleStreamConnectError),t&&this.sendMessage2Room()}else this.hasPulled=!1,this.pulledStreamType="small",this.streamType=STREAM_TYPE.OTHER}updateBloudStream(e,t,r=!1){var i,n,s,o;let a=!1,c=!1;e?(this.bloudStream={audio:e.audio,video:e.video,isScreen:e.isScreen},e.customInfo&&(this.bloudStream.customInfo&&(null===(i=this.bloudStream.customInfo)||void 0===i?void 0:i.volume)===e.customInfo.volume||Number.isNaN(e.customInfo.volume)||this.setRemoteAudioLevel(e.customInfo.volume),this.bloudStream.customInfo=e.customInfo),this.stream&&(this.bloudStream.audio?this.isShare||(t.addToDetector(new BMSpeaker(this.user,this.stream)),this.collectAudioLevel()):t.removeFromDetector(this.stream.getStreamId())),this.bloudStream.video!==this._video_enable&&(a=!0),this.bloudStream.audio!=this._audio_enable&&(c=!0),this.setVideoEnable(this.bloudStream.video),this.setAudioEnable(this.bloudStream.audio),r&&(null===(n=this.stream)||void 0===n||n.destroy(),this.stream&&(null===(s=t.room.audioPlayer)||void 0===s||s.removeStream(this.stream)),this.updateStream(void 0,!1,t),this._stream=void 0),c&&!this.audioEnable&&this.stream&&(null===(o=t.room.audioPlayer)||void 0===o||o.removeStream(this.stream)),(this.bloudStream.audio||this.bloudStream&&this.isDisplay)&&(!this.stream||r?BoomEmitter.emitter.emit(ADD_PULL_USER,{id:this.userId,isWeb:this.isWeb,isScreen:this.isShare}):(this.isLocal||this.hasPulled&&this.stream.isSubscribed()||this.sendMessage2Room(),a&&this.sendMessage2Room(),!this.isLocal&&c&&this.audioEnable&&this.stream.isSubscribed()&&BoomEmitter.getInstance().emit(ADD_AUDIO_PLAY,{stream:this})))):(this.bloudStream=void 0,this.setVideoEnable(!1),this.setAudioEnable(!1),this.stream&&t.removeFromDetector(this.stream.getStreamId())),this.updateSortNum(!0),this.streamUpdateWatcher.next(!0)}updateBloudCustomInfo(e){var t;this.bloudStream?(this.bloudStream.customInfo&&(null===(t=this.bloudStream.customInfo)||void 0===t?void 0:t.volume)===e.volume||Number.isNaN(e.volume)||this.setRemoteAudioLevel(e.volume),this.bloudStream.customInfo=e):error$1("updateBloudCustomInfo, but bloudStream is undefined","","",["userId =>",this.userId])}get streamId(){return this._stream?this._stream.getStreamId():this.userId}get bStreamId(){return this.isShare?`${this.userId}_screen`:this.userId}get userId(){return this.user.userId}get stream(){return this._stream}get isLocal(){return this.user.isLocal}get isShare(){var e,t,r;return this.stream?this.user.isWeb?null===(t=null===(e=this.stream)||void 0===e?void 0:e.getUserId())||void 0===t?void 0:t.endsWith(STREAM_SUFFIX_SCREEN):!(!this.stream||!this.stream.getType||"assist"!==this.stream.getType()):!!(null===(r=this.bloudStream)||void 0===r?void 0:r.isScreen)}get isWeb(){return this.user.isWeb}get audioEnable(){return this._audio_enable}get videoEnable(){return this._video_enable}get nickname(){var e;return this.user.isToupingma?`${this.user.nickName}(的投屏)`:(null===(e=this.streamId)||void 0===e?void 0:e.includes(STREAM_SUFFIX_SCREEN))?`${this.user.nickName}(的屏幕共享)`:this.user.nickName}get audioLevel(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.getAudioLevel())||0}getUser(){return this.user}setRemoteAudioLevel(e){if(this.isLocal)throw new Error("不能设置本地流的音量");BoomEmitter.emitter.emit(SET_VOLUME,{streamId:this.streamId,volume:e})}getStats(){var e;return null===(e=this._stream)||void 0===e?void 0:e.getStats()}initBigPlayer(){try{if(this.bigPlayerId){const e=document.querySelector(`#${this.bigPlayerId}`);e||console.error("播放大流失败,找不到大流容器",this.userId,this.streamId,this.bigPlayerId),!this.player&&e&&(this.player=new Player(e,{fit:"contain"}),this.player.on("player-state-changed",(e=>{var t;this.stream&&(info("big player state change","","",[JSON.stringify(e)]),"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&this.playStateChangeWatcher.next(this),"PAUSED"===e.state&&(null===(t=this.player)||void 0===t||t.resume()))})))}}catch(e){error$1("初始化大窗口的播放器失败",this.userId,this.streamId,e.message)}}stop(){var e;null===(e=this._stream)||void 0===e||e.stop()}destroy(){var e;null===(e=this._stream)||void 0===e||e.destroy()}isPlaying(){var e;return null===(e=this._stream)||void 0===e?void 0:e.isPlaying()}replay(){var e;return null===(e=this._stream)||void 0===e?void 0:e.replay()}resume(){var e,t;null===(e=this._stream)||void 0===e||e.resume(),null===(t=this.player)||void 0===t||t.resume()}hasAudio(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasAudio())||!1}hasVideo(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasVideo())||!1}updateUser(e){this.user=e;const t=this.user.userInfo.pos;t?t.includes("web")||t.includes("pc")?this.streamType=STREAM_TYPE.SUB_MAIN:t.includes("_toupingma")?this.streamType=STREAM_TYPE.SHARE:this.streamType=STREAM_TYPE.SINGLE:this.streamType=STREAM_TYPE.SINGLE}updateSortNum(e=!0){const t=this.getSortNum();this.setSortNum(t,e)}setSortNum(e,t){this.sortNum!==e&&(this.sortNum=e,t&&(BoomEmitter.emitter.emit(MODEL_SORT_NUM_CHANGE,null),this.user.updateSortNum(!0)))}getSortNum(){return this.user.isMaster?getMasterSort(this.audioEnable,this.videoEnable):this.user.isLocal?getLocalSort(this.audioEnable,this.videoEnable):this.user.isManager?getManagerSort(this.audioEnable,this.videoEnable):getGuestSort(this.audioEnable,this.videoEnable)}checkSmallVideo(){if(this.videoEnable&&this.stream&&!this.isShare){const e=`video_${this.stream.getStreamId()}`;if(!!document.getElementById(e))return void this.checkVideoDecodeFrame(e);error$1("stream is play, but no video element, replay now")}}checkBigVideo(){if(this.videoEnable&&this.stream){const e=`video_${this.stream.getStreamId()}_big`;if(!this.isShare&&this.isDisplay&&this.playerId){const t=!!document.getElementById(e);if(this.isInBig){if(t)return void this.checkVideoDecodeFrame(e);error$1("stream is playing in big, but no video element, replay now"),this.playInBig()}}this.isShare&&this.isInBig&&this.bigPlayerId&&this.checkVideoDecodeFrame(e)}}checkVideoDecodeFrame(e){const t=document.getElementById(e);if(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),!t)return info("黑帧检测没有播放容器",this.userId,"",["streamId =>",this.streamId,"isShare =>",this.isShare]),void(this.isShare&&this.isInBig&&this.bigPlayerId&&(warn("share stream has no video player, retry play"),this.playInBig()));this.checkVideoTimer=setTimeout((()=>{var r,i,n;const s=(null==t?void 0:t.getVideoPlaybackQuality)&&(null===(r=null==t?void 0:t.getVideoPlaybackQuality())||void 0===r?void 0:r.totalVideoFrames)||0;if(!t||t.getVideoPlaybackQuality)return s>0?(clearTimeout(this.checkVideoTimer),void(this.checkFailedCount=0)):this.checkCount>10?(error$1("检测超过了十次,还没有视频流,需要重新拉取","黑帧检测",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname,"videoContainer => ",e]),this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount+=1,void(this.checkFailedCount<=3&&(this.hasPulled=!1,this.pulledStreamType="small",null===(i=this._stream)||void 0===i||i.off(namespace),null===(n=this._stream)||void 0===n||n.destroy(),this._stream=void 0,this.sendMessage2Room()))):(this.checkCount+=1,void this.checkVideoDecodeFrame(e));this.checkVideoTimer&&clearTimeout(this.checkVideoTimer)}),200)}subscribeStream(){this.shouldPull=!0,BoomEmitter.emitter.emit(MANUAL_SUBSCRIPTION,{stream:this})}unSubscribeStream(){this.shouldPull=!1,BoomEmitter.emitter.emit(UNSUBSCRIBE_STREAM,{stream:this})}}function getHTMLMediaStreamOptions(e){let t=null;const r=e.videoElement,i=r.offsetWidth,n=r.offsetHeight;if(r.captureStream?t=r.captureStream():r.mozCaptureStream&&(t=r.mozCaptureStream()),t){const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];return{video:!!e,audio:!!r,videoSource:e,audioSource:r,width:i,height:n}}return null}function getMediaStreamInfo(e,t){try{const r=e.getVideoTracks()[0],i=e.getAudioTracks()[0];return{video:!!r,audio:!!i,videoSource:r,audioSource:i,width:t.width,height:t.height}}catch(e){return console.log("获取共享音频参数有误",e),null}}function transShareScreen2User(e){return e.split("_")[0]}class BMStreamModelVM{constructor(){this.streamModels=new Map,this.streamModelsWatcher=new BehaviorSubject(BMStreamModelVM.filterStreamModels(this.sortStreamModels())),this.shareStreamModels=new Map,this.shareStreamModelsWatcher=new BehaviorSubject(Array.from(this.shareStreamModels.values())),this.localStreamErrorWatcher=new Subject,this.localModel=null,this.room=null,this.bloudStream=null,this.videoStream=null,this.audioStream=null,this.audioStats=!1,this.videoStats=!1,this.localIsShare=!1,this.isShareWatcher=new Subject,this._speaker_enable=!0,this.speakerEnableWatcher=new BehaviorSubject(this._speaker_enable),this.mixStreamModelWatcher=new BehaviorSubject(null),this.canvasTimer=null,this._isRecording=!1,this._slicingRecord=!1,this.isRecordingWatcher=new BehaviorSubject(this._isRecording),this._speaker=null,this._speakers=new Map,this.speakerWatcher=new BehaviorSubject(this._speaker),this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.localStreamConnectErrorWatcher=new Subject,this.localShareError=new Subject,this.shareBloudStateMap=new Map,this.updateModelSort=debounce((()=>{const e=this.sortStreamModels();this.streamModelsWatcher.next(BMStreamModelVM.filterStreamModels(e))}),200,{maxWait:500}),this.handleNoContainer=e=>{const{type:t,container:r,id:i}=e;let n;n="share"===t?this.shareStreamModels.get(i):this.streamModels.get(i),n&&("small"===r?this.noContainerWatcher.next(n):this.noBigContainerWatcher.next(n))},this.getHTMLMediaStream=getHTMLMediaStreamOptions,this.getMediaStream=getMediaStreamInfo,this.createCanvas(),setTimeout((()=>{this.canvasDisplay()}),100),BoomEmitter.emitter.on(MODEL_SORT_NUM_CHANGE,this.updateModelSort),BoomEmitter.emitter.on(NO_CONTAINER,this.handleNoContainer)}static filterStreamModels(e){return e.filter((e=>!e.isToupingma)).filter((e=>!ignoreUserId.some((t=>e.userId.includes(t))))).filter((e=>e.canShow))}initWithRoom(e){return this.room=e,this}setSpeakerEnable(e){var t;this._speaker_enable!==e&&(null===(t=this.room.audioPlayer)||void 0===t||t.mute(!e),this._speaker_enable=e,this.speakerEnableWatcher.next(e))}getStreamModels(){return Array.from(this.streamModels.values())}getStreamModelByUId(e){return this.streamModels.get(e)}getShareStreamModelByUId(e){return this.shareStreamModels.get(e)}getLocalStreamModel(){return this.localModel}createStreamModel(e,t){const r=new BMStreamModel(e,void 0);return t&&r.updateStream(t,!0,this),r.isShare?(e.addStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`,r),this.addShareStreamModel(r)):(e.addStream(e.userId,r),this.addStreamModel(r)),r}addStreamModel(e){e&&(e.isLocal?this.localModel||(this.localModel=e,this.streamModels.set(this.localModel.userId,this.localModel)):this.streamModels.set(e.userId,e))}addShareStreamModel(e){e&&(e.isLocal||(this.shareStreamModels.set(e.userId,e),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))))}removeStreamModel(e){if(!e)return;const t=e.getUser();this.streamModels.delete(e.userId),t.removeStream(e.userId)}removeShareStreamModelByUId(e){var t,r,i,n;const s=this.shareStreamModels.get(e);s&&(null===(t=s.stream)||void 0===t||t.stop(),null===(r=s.stream)||void 0===r||r.destroy(),s.audioEnable&&s.stream&&(null===(n=null===(i=this.room)||void 0===i?void 0:i.audioPlayer)||void 0===n||n.removeStream(s.stream)),this.removeShareStreamModel(s))}removeShareStreamModel(e){if(!e)return;const t=e.getUser();this.shareStreamModels.delete(e.userId),t.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`),t.updateSortNum(!0),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}removeStreamModelByUId(e){var t,r,i;const n=this.getStreamModelByUId(e);return n&&(n.stream&&(this.removeFromDetector(n.streamId),n.stream.stop(),n.stream.destroy()),n.audioEnable&&(n.stream?null===(r=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===r||r.removeStream(n.stream):null===(i=this.room)||void 0===i||i.audioPlayer.removeStreamByUid(e)),this.removeStreamModel(n)),n}remoteStreamPublished(e){const t=e.getStreamId(),r=e.getUserId();let i,n=this.getStreamModelByUId(r);if(n||(i=transShareScreen2User(String(r)),n=this.getStreamModelByUId(i)),n){if(isShareStream(e)){let t;if(i&&(t=this.shareStreamModels.get(i)),t){if(t.isLocal)return;t.hasPulled=!1,t.pulledStreamType="small",t.updateStream(e,!0,this),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}else{const t=this.createStreamModel(n.getUser(),e),r=e.getVideoOn(),i=e.getAudioOn(),s=this.shareBloudStateMap.get(n.userId);s?t.updateBloudStream({audio:s.audio,video:s.audio,isScreen:!0,customInfo:s.customInfo},this):t.updateBloudStream({audio:i,video:r,isScreen:!0},this),t.streamType=STREAM_TYPE.SHARE}}else n.hasPulled=!1,n.pulledStreamType="small",this.updateStreamModel(n,e);n.getUser().isMixer&&this.mixStreamModelWatcher.next(n),this.changeSingleStreamSpeaker(n).catch((e=>{error$1("设置单股流的扬声器的播放出现了问题","设置播放音量",null==n?void 0:n.userId)}))}else error$1("brtc有人推流了,但是找不到对应的streamModel, 找不到对应的用户","",r,["streamId => ",t,"type =>",e.getType&&e.getType()])}remoteStreamUnpublished(e){var t,r,i;let n;const s=e.getUserId(),o=e.getStreamId();let a=!1;if(s.includes(STREAM_SUFFIX_SCREEN)){const e=transShareScreen2User(String(s));if(e==(null===(r=null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant())||void 0===r?void 0:r.userId))return info("本地用户取消共享屏幕","取消共享屏幕",s),void this.localModel.getUser().removeStream(s);n=this.getShareStreamModelByUId(e),a=!0}else o.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()?(n=this.getShareStreamModelByUId(s),a=!0):n=this.getStreamModelByUId(s);if(this.removeFromDetector(o),this.removeFromRecorder(e),!n)return void error$1("brtc有人取消推流 但是找不到对应的streamModel","取消推流",s,[o]);const c=null===(i=n.stream)||void 0===i?void 0:i.getStreamId();if(c===o)return n.hasPulled=!1,n.pulledStreamType="small",a||n.streamType===STREAM_TYPE.SHARE?(this.removeShareStreamModel(n),void n.updateStream(void 0,!0,this)):(n.updateStream(void 0,!0,this),n);error$1("当前取消推流的和当前绑定的不是同一股流","",s,["streamId =>",o,"streamModel.streamId",c])}sortStreamModels(){return sortStreamModels(Array.from(this.streamModels.values()))}updateStreamModel(e,t){e.updateStream(t,!0,this)}updateShareStreamModel(e,t){e.updateStream(t,!0,this)}setLocalVideoEnable(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){if(!(null===(r=this.room)||void 0===r?void 0:r.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地摄像头,不与响应");if(!this.room.mediaPermission.camera)return Promise.reject(BMCameraNotAuthError());const i=this.getLocalStreamModel();if(info(`开关本地摄像头, 状态 => ${e}`,"本地用户",null==i?void 0:i.userId),i)if(e)if(null==i?void 0:i.stream){if(t)yield i.stream.replaceTrack(t).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}));else{if("CanvasCaptureMediaStreamTrack"===i.stream.getVideoTrack().constructor.name){const e=yield this.createVideoStream().catch((e=>Promise.reject(e)));yield i.stream.replaceTrack(e).then((()=>{info("replace video track success")})).catch((e=>(error$1("本地视频流更换视频流失败","","",JSON.stringify(e)),this.handleStreamUpdateFailed(),Promise.reject(BMOpenCameraError()))))}}if(!(yield i.stream.unmuteVideo()))return error$1("brtc unmuteVideo失败"),this.handleStreamUpdateFailed(),Promise.reject(BMOpenCameraError());info("brtc unmute video success"),yield this.bloudStream.setVideoEnabled(!0).then((()=>{i.updateStream(i.stream,!0,this),i.updateBloudStream({video:!0,audio:i.audioEnable,isScreen:!1},this),i.playInBig()})).catch((e=>{error$1("bloud unmuteVideo失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!1,!0,i,t).catch((e=>{var t,r,i,n,s;return error$1("开启本地摄像头失败","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));else{i.stream&&(yield this.muteOrUnpublishStream("video",!0,i).catch((e=>(error$1("关闭本地摄像头失败","","",[e]),Promise.reject(BmSetLocalVideoEnable(e))))))}}))}handleStreamUpdateFailed(){return __awaiter$2(this,void 0,void 0,(function*(){error$1("brtc unmute stream failed, now unpublish"),yield this.unpublishStream()}))}setLocalAudioEnable(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(!(null===(t=this.room)||void 0===t?void 0:t.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地麦克风,不与响应");if(!this.room.mediaPermission.microphone)return Promise.reject(BMMicNotAuthError());const r=this.getLocalStreamModel();if(info(`开关本地麦克风, 状态 => ${e}`,"本地用户",null==r?void 0:r.userId),r)if(e){if(null==r?void 0:r.stream){const e=yield r.stream.unmuteAudio();if(info(`unmute local stream audio res : ${e}`),!e)return error$1("brtc unmuteAudio失败","本地用户",""),yield this.handleStreamUpdateFailed(),Promise.reject(BMOpenMicroError());info("unmute audio success"),yield this.bloudStream.setAudioEnabled(!0).then((()=>{info("bloud stream set audio enable"),r.updateStream(r.stream,!1,this),r.updateBloudStream({audio:!0,video:r.videoEnable,isScreen:!1},this)})).catch((e=>{error$1("bloud unmuteAudio失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!0,!1,r).catch((e=>{var t,r,i,n,s;return error$1("开启本地麦克风失败","","",[e]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));(null==r?void 0:r.stream)&&this.addToRecorder(null==r?void 0:r.stream)}else{const e=r.stream;if(e){this.removeFromRecorder(e),this.removeFromDetector(e.getStreamId());try{yield this.muteOrUnpublishStream("audio",!0,r)}catch(e){return error$1("关闭本地麦克风失败","","",[JSON.stringify(e)]),Promise.reject(BmSetLocalAudioEnable(e))}}}}))}joinWithAudioAndAudio(e,t){return __awaiter$2(this,void 0,void 0,(function*(){info("join with audio and video","join publish","",[e,t]);const r=this.getLocalStreamModel();r&&(yield this.createStreamAndPublish(e,t,r).catch((e=>{var t,r,i,n,s;return error$1("join create and publish failed","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)})))}))}changeSpeaker(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){if(info("change speaker","","",[JSON.stringify(e)]),!e.deviceId)throw new BoomError(LOCAL_ERROR,"切换扬声器失败!,原因: 选择的设备没有deviceId"+(null==e?void 0:e.name));try{this.room.setSelectSpeakerDevice(e),null===(r=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===r||r.setDevice(e.deviceId)}catch(e){throw error$1("切换扬声器失败","","",["error",null==e?void 0:e.message,JSON.stringify(e)]),new BoomError(LOCAL_ERROR,"切换扬声器失败")}}))}changeSingleStreamSpeaker(e){return __awaiter$2(this,void 0,void 0,(function*(){const t=this.room.selectAudioOutputDevice;t&&(e.isLocal||e.stream&&(yield e.stream.setAudioOutput(t.deviceId)))}))}changeAudioInput(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){info("change audio input device","","",[JSON.stringify(e)]);const i=null===(t=this.localModel)||void 0===t?void 0:t.stream;null===(r=this.room)||void 0===r||r.setSelectAudioDevice(e),i&&(this.removeFromRecorder(i),yield i.switchDevice("audio",e.deviceId),this.addToRecorder(i))}))}changeVideoInput(e){var t,r,i;return __awaiter$2(this,void 0,void 0,(function*(){info("change video input device","","",[JSON.stringify(e)]);const n=null===(t=this.localModel)||void 0===t?void 0:t.stream;null===(r=this.room)||void 0===r||r.setSelectVideoDevice(e),n&&(yield n.switchDevice("video",e.deviceId),(null===(i=this.localModel)||void 0===i?void 0:i.isDisplay)&&this.localModel.isInBig&&this.localModel.playInBig())}))}muteSpeaker(e){return __awaiter$2(this,void 0,void 0,(function*(){info("静音扬声器 状态 =>","","",["status =>",e]);try{this.setSpeakerEnable(e)}catch(t){return Promise.reject(BmSetLocalSpeakerEnable(`开关扬声器失败 ${e} error: ${JSON.stringify(t)}`))}}))}createLocalAudioStream(){var e;return __awaiter$2(this,void 0,void 0,(function*(){this.room.mediaPermission.microphone?(yield this.room.initDevices(),this.room.audioDevices.length?(null===(e=this.audioStream)||void 0===e||e.destroy(),this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},this.localModel.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e))))):error$1("there is no audio device exists")):error$1("there is no microphone permission")}))}createStreamAndPublish(e,t,r,i){var n,s,o,a,c,u,d,l;return __awaiter$2(this,void 0,void 0,(function*(){let h=BMStreamModelVM.getCanvasStream();if(yield this.room.initDevices(),t)null===(a=this.brtcStream)||void 0===a||a.destroy(),(null===(c=this.room)||void 0===c?void 0:c.audioDevices.length)||(error$1("当前电脑中没有音频输入设备,重新获取"),yield null===(u=this.room)||void 0===u?void 0:u.initDevices()),(null===(d=this.room)||void 0===d?void 0:d.videoDevices.length)||(error$1("当前电脑中没有视频输入设备, 重新获取"),yield null===(l=this.room)||void 0===l?void 0:l.initDevices()),this.room.audioDevices.length>0?this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:this.room.mediaPermission.microphone},r.userId).catch((e=>(error$1("create brtc audio and video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))):(error$1("没有音频输入设备,只能创建视频流"),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!1},r.userId).catch((e=>(error$1("create brtc video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))));else{const e=h.getVideoTracks()[0];this.audioStream||(this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},r.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e)))));const t=null===(n=this.audioStream)||void 0===n?void 0:n.getAudioTrack();if(!t||t&&t.muted)throw null===(s=this.audioStream)||void 0===s||s.destroy(),this.audioStream=null,this.localStreamErrorWatcher.next("audio"),error$1("麦克风设备不可用","","",["muted => ?",null==t?void 0:t.muted]),getStreamError("麦克风");null===(o=this.brtcStream)||void 0===o||o.destroy(),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!0,videoSource:e,audioSource:t},r.userId).catch((e=>Promise.reject(e)))}this.brtcStream&&(t||(yield this.brtcStream.muteVideo()),e||(yield this.brtcStream.muteAudio()),i&&(yield this.brtcStream.replaceTrack(i).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}))),yield this.room.publish(this.brtcStream).catch((e=>{var t,r;return null===(t=this.brtcStream)||void 0===t||t.destroy(),null===(r=this.localModel)||void 0===r||r.updateBloudStream(void 0,this),Promise.reject(e)})),this.brtcStream.on("video-track-mute",this.muteHandler.bind(this,"video")),this.brtcStream.on("video-track-ended",this.muteHandler.bind(this,"video")),this.brtcStream.on("audio-track-mute",this.muteHandler.bind(this,"audio")),this.brtcStream.on("audio-track-ended",this.muteHandler.bind(this,"audio")),yield this.publishBloudStream(e,t))}))}publishBloudStream(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){const i=this.localModel.userId;this.bloudStream=this.room.boomCore.creteBloudLocalStream({audio_enable:e,video_enable:t},i),yield this.bloudStream.publish({video_enable:t,audio_enable:e}),null===(r=this.localModel)||void 0===r||r.updateBloudStream({video:t,audio:e,isScreen:!1},this)}))}muteHandler(e){var t,r,i,n,s,o;return __awaiter$2(this,void 0,void 0,(function*(){this.localStreamConnectErrorWatcher.next(BMStreamDisconnectedError("video"===e?"摄像头":"麦克风"));error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",null===(t=this.localModel)||void 0===t?void 0:t.videoEnable,"audioEnable",null===(r=this.localModel)||void 0===r?void 0:r.audioEnable,"type",e]);const a=()=>__awaiter$2(this,void 0,void 0,(function*(){var e,t,r,i,n,s,o,a;(null===(e=this.localModel)||void 0===e?void 0:e.stream)&&(yield null===(t=this.room)||void 0===t?void 0:t.boomCore.unpublish(this.localModel.stream)),null===(i=null===(r=this.localModel)||void 0===r?void 0:r.stream)||void 0===i||i.destroy(),null===(n=this.audioStream)||void 0===n||n.destroy(),null===(s=this.videoStream)||void 0===s||s.destroy(),this.audioStream=null,this.videoStream=null,null===(o=this.localModel)||void 0===o||o.updateStream(void 0,!0,this),yield this.bloudStream.unpublish(),this.bloudStream=null,null===(a=this.localModel)||void 0===a||a.updateBloudStream(void 0,this)}));if(null===(i=this.localModel)||void 0===i?void 0:i.stream)if("video"===e)info("video track has problem, now unpublish"),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),yield a();else{null===(n=this.audioStream)||void 0===n||n.destroy(),this.audioStream=null,this.audioStream=yield null===(s=this.room)||void 0===s?void 0:s.createPBSingleLocalStream({video:!1,audio:!0});const e=null===(o=this.audioStream)||void 0===o?void 0:o.getAudioTrack();e&&!e.muted?this.localModel.stream&&(yield this.localModel.stream.replaceTrack(e).catch((e=>{error$1("本地流出现异常, 重新创建audio stream replace 失败","本地流出现异常","",[JSON.stringify(e)]),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),a()}))):(error$1("recreate audio stream failed, now unpub"),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),a())}this.localStreamErrorWatcher.next(e)}))}unpublishStream(){var e,t,r,i;return __awaiter$2(this,void 0,void 0,(function*(){info("unpublish stream");const n=this.getLocalStreamModel();if(n){const s=n.stream;s&&(yield null===(e=this.room)||void 0===e?void 0:e.unpublish(s).catch((e=>{error$1("brtc 取消发布失败","取消推流",n.userId,[JSON.stringify(e)])})));try{this.removeFromRecorder(s),null==s||s.destroy(),null===(t=this.videoStream)||void 0===t||t.destroy(),null===(r=this.audioStream)||void 0===r||r.destroy(),null===(i=this.brtcStream)||void 0===i||i.destroy(),this.videoStream=null,this.audioStream=null,this.brtcStream=void 0,n.updateStream(void 0,!0,this),yield this.bloudStream.unpublish().catch((e=>{error$1("bloud unpublish stream failed","bloud unpublish stream",n.userId,[JSON.stringify(e),null==e?void 0:e.code,null==e?void 0:e.message])})),n.updateBloudStream(void 0,this),this.bloudStream=null}catch(e){error$1("stream destroy failed","取消推流",n.userId,[JSON.stringify(e)])}}}))}muteOrUnpublishStream(e,t,r){var i;return __awaiter$2(this,void 0,void 0,(function*(){const t=r.stream;let n=!0;if("audio"===e?n=t.getVideoOn():"video"===e&&(n=t.getAudioOn()),n){if("audio"===e){(yield t.muteAudio())||error$1("brtc muteAudio失败","关闭本地音频","本地"),yield this.bloudStream.setAudioEnabled(!1).catch((e=>{error$1("bloud setAudioEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({audio:!1,video:!0,isScreen:!1},this)}else if("video"===e){const e=BMStreamModelVM.getCanvasStream().getVideoTracks()[0];try{yield t.replaceTrack(e),yield t.muteVideo()}catch(e){error$1("关闭本地视频失败","关闭本地视频","本地",[JSON.stringify(e)])}try{null===(i=this.videoStream)||void 0===i||i.destroy(),this.videoStream=null}catch(e){error$1("this.videoStream destroy failed")}yield this.bloudStream.setVideoEnabled(!1).catch((e=>{error$1("bloud setVideoEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({video:!1,audio:!0,isScreen:!1},this)}}else yield this.unpublishStream()}))}toggleShareScreen(e,t,r){var i,n,s,o,a;return __awaiter$2(this,void 0,void 0,(function*(){return info("开关共享屏幕","","开关共享屏幕",["stats => ",e]),!e&&(null===(i=this.room)||void 0===i?void 0:i.boomCore.shareScreenStream)&&this.removeFromRecorder(null===(n=this.room)||void 0===n?void 0:n.boomCore.shareScreenStream),yield null===(s=this.room)||void 0===s?void 0:s.boomCore.toggleShareScreen(e,t,r).then((()=>{var r;if(info("bmStreamVm toggleShareScreen success","切换共享屏幕","",["enable =>",e,"options =>",JSON.stringify(t)]),e){const e=null===(r=this.room)||void 0===r?void 0:r.boomCore.shareScreenStream;e&&this.remoteStreamPublished(e)}else this.localModel.getUser().removeStream(`${this.localModel.userId}_screen`),this.localModel.getUser().updateSortNum(!0)})).catch((r=>(error$1("bmStreamVm toggleShareScreen error","切换共享屏幕","",["enable =>",e,"options =>",t]),Promise.reject(r)))),e&&(null===(o=this.room)||void 0===o?void 0:o.boomCore.shareScreenStream)&&this.addToRecorder(null===(a=this.room)||void 0===a?void 0:a.boomCore.shareScreenStream),this.localIsShare=e,this.isShareWatcher.next(e),Promise.resolve(!0)}))}setShareScreenContentHint(e){var t;null===(t=this.room)||void 0===t||t.boomCore.setShareScreenContentHint(e)}createCanvas(){const e=document.createElement("canvas");e.id="tarCanvas",e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.bottom="0",document.body.appendChild(e)}canvasDisplay(){let e=document.getElementById("tarCanvas");if(e){e.width=640,e.height=360;let t=e.getContext("2d");t.fill(),t.beginPath(),t.fillStyle="rgb(0,0,0)",t.fillRect(0,0,e.width,e.height),this.canvasTimer&&clearTimeout(this.canvasTimer),this.canvasTimer=setTimeout((()=>{this.canvasDisplay()}),1e3)}}static getCanvasStream(){return document.getElementById("tarCanvas").captureStream()}createVideoStream(){var e,t,r;return __awaiter$2(this,void 0,void 0,(function*(){return yield this.room.initDevices(),null===(e=this.videoStream)||void 0===e||e.destroy(),this.videoStream=yield this.room.createPBSingleLocalStream({video:!0,audio:!1},this.localModel.userId).catch((e=>Promise.reject(BMCreateStreamError("视频")))),null===(t=this.videoStream)||void 0===t||t.on("video-track-mute",this.muteHandler.bind(this,"video")),null===(r=this.videoStream)||void 0===r||r.on("video-track-ended",this.muteHandler.bind(this,"video")),this.videoStream.getVideoTrack()}))}startRecord(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(this._recorder)return;this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(e),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended")})),this._recorder.on("started",(()=>{info("record started.")}));let r=!0;try{yield this._recorder.start(),this._isRecording=!0,this.isRecordingWatcher.next(!0),this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),r=!1,yield t.stop()}return r}))}addToRecorder(e){this._isRecording&&!this._slicingRecord&&(e.on("audio-track-ended",(()=>{this.removeFromRecorder(e)})),this._recorder.addStream(e))}removeFromRecorder(e){this._isRecording&&!this._slicingRecord&&this._recorder.removeStream(e)}stopRecord(){return __awaiter$2(this,void 0,void 0,(function*(){this._recorder&&(this._isRecording=!1,this.isRecordingWatcher.next(!1),yield this._recorder.stop(),this._recorder=void 0)}))}sliceRecord(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(!this._isRecording)return;let r=this._recorder._opts;this._slicingRecord=!0;try{yield this._recorder.stop()}catch(e){error$1("stop record exception","","",[JSON.stringify(e)])}r.filename=e,this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(r),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended.")})),this._recorder.on("started",(()=>{info("record started.")}));let i=!0;try{yield this._recorder.start(),this._slicingRecord=!1,this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),this._slicingRecord=!1,i=!1,yield t.stop()}return i}))}startSpeakerDetector(){var e;this._speaker=null,this._speakerDetector=null===(e=this.room)||void 0===e?void 0:e.boomCore.createSpeakerDetector(),this._speakerDetector.on("speaker",(e=>{var t,r,i;let n=!0;e?((null===(t=this._speaker)||void 0===t?void 0:t.getUserInfo().userId)===e.getUser().userId&&(n=!1),this._speaker=e.getUser()):(this._speaker||(n=!1),this._speaker=null),n&&(info("当前讲话人","语音激励",null===(r=this._speaker)||void 0===r?void 0:r.userId,["nickname => ",null===(i=this._speaker)||void 0===i?void 0:i.nickname]),this.speakerWatcher.next(this._speaker))}))}addToDetector(e){this._speakers.set(e.getID(),e),this._speakerDetector&&this._speakerDetector.addStream(e)}removeFromDetector(e){let t=this._speakers.get(e);this._speakerDetector&&t&&(this._speakers.delete(e),this._speakerDetector.removeStream(t))}shareCustomMedia(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){return null===(r=this.room)||void 0===r?void 0:r.boomCore.shareHTMLMedia(e,t)}))}updateBloudStreamCustomStats(e,t,r){var i;return null===(i=this.room)||void 0===i?void 0:i.boomCore.updateStream(e,t,r)}clearCache(){var e,t,r,i,n;null===(t=null===(e=this.localModel)||void 0===e?void 0:e.stream)||void 0===t||t.destroy(),null===(r=this.videoStream)||void 0===r||r.destroy(),null===(i=this.audioStream)||void 0===i||i.destroy(),this.streamModels.clear(),this.shareStreamModels.clear(),null===(n=this.room)||void 0===n||n.userVM.clearUsers()}}class BMRoomInfo{constructor(){this.room=null,this._roomName="",this.msgSeq="",this.roomID="",this.audioOff=!1,this.selfopenaudio=!1,this.lock=!1,this.leaveNotice=!1,this.openSelf=!1,this.chatNotice="",this.chatNoticeRich="",this.raiseHandsList=new Map,this.raiseHandsWatcher=new BehaviorSubject(Array.from(this.raiseHandsList.values())),this.raiseVideoHandsList=new Map,this.raiseVideoHandsWatcher=new BehaviorSubject(Array.from(this.raiseVideoHandsList.values())),this.raiseSimpleHandsList=new Map,this.raiseSimpleHandsWatcher=new BehaviorSubject(Array.from(this.raiseSimpleHandsList.values())),this.operationPermissionWatcher=new Subject,this.chatNoticeWatcher=new Subject,this.totalUserWatcher=new BehaviorSubject(0),this.totalWaitRoomUserWatcher=new BehaviorSubject(0),this.isOpenWaitRoom=new Subject,this.audioOffWatcher=new Subject,this.lockWatcher=new BehaviorSubject(this.lock),this.leaveNoticeWatcher=new BehaviorSubject(this.leaveNotice),this.openSelfWatcher=new BehaviorSubject(this.openSelf),this.setRaiseHandsWatcherValue=debounce((()=>{this.raiseHandsWatcher.next(Array.from(this.raiseHandsList.values()))}),1e3),this.setVideoRaiseHandsWatcherValue=debounce((()=>{this.raiseVideoHandsWatcher.next(Array.from(this.raiseVideoHandsList.values()))}),1e3),this.setSimpleRaiseHandsWatcherValue=debounce((()=>{this.raiseSimpleHandsWatcher.next(Array.from(this.raiseSimpleHandsList.values()))}),1e3),BoomEmitter.emitter.on(RAISE_HAND,(e=>{"raiseHandsAudio"===e.status?e.user.raiseAudioHands?this.addRaiseHandUser(e.user):this.removeRaiseHandUser(e.user.userId):"raiseHandsVideo"===e.status?e.user.raiseVideoHands?this.addVideoRaiseHandUser(e.user):this.removeVideoRaiseHandUser(e.user.userId):"raiseHand"===e.status&&(e.user.raiseHand?this.addSimpleRaiseHandUser(e.user):this.removeSimpleRaiseHandUser(e.user.userId))}))}get roomName(){return this._roomName||(this._roomName=this.room.getName()),this._roomName}get isBigRoom(){return this.room.isBig}setup(e){this.roomID=e.room,this.handleInitParams()}bindRoom(e){this.room=e}initCustomStats(e){this.operationPermission=e,void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}updateOperationPermission(e){this.operationPermission=Object.assign(Object.assign({},this.operationPermission),e),void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}handleInitParams(){const e=this.room.boomCore.getAudioOff(),t=this.room.boomCore.getSelfOpenAudio();this.setAudioOff(e,t)}setAudioOff(e,t){this.audioOff=e,this.selfopenaudio=t,this.audioOffWatcher.next({audioOff:e,selfopenaudio:t})}setlock(e){this.lock=e,this.lockWatcher.next(e)}setLeaveNotice(e){this.leaveNotice=e,this.leaveNoticeWatcher.next(e)}setRaiseHandsList(e){e.forEach((e=>{e.raiseAudioHands&&this.raiseHandsList.set(e.getID(),e),e.raiseVideoHands&&this.raiseVideoHandsList.set(e.getID(),e),e.raiseHand&&this.raiseSimpleHandsList.set(e.getID(),e)})),this.setRaiseHandsWatcherValue(),this.setVideoRaiseHandsWatcherValue(),this.setSimpleRaiseHandsWatcherValue()}addRaiseHandUser(e){this.raiseHandsList.set(e.getID(),e),this.setRaiseHandsWatcherValue()}removeRaiseHandUser(e){this.raiseHandsList.delete(e),this.setRaiseHandsWatcherValue()}addVideoRaiseHandUser(e){this.raiseVideoHandsList.set(e.getID(),e),this.setVideoRaiseHandsWatcherValue()}removeVideoRaiseHandUser(e){this.raiseVideoHandsList.delete(e),this.setVideoRaiseHandsWatcherValue()}addSimpleRaiseHandUser(e){this.raiseSimpleHandsList.set(e.getID(),e),this.setSimpleRaiseHandsWatcherValue()}removeSimpleRaiseHandUser(e){this.raiseSimpleHandsList.delete(e),this.setSimpleRaiseHandsWatcherValue()}}var name="@hysc/meeting",version="5.0.92",description="boom meeting",main="umd/index.js",module$1="esm/index.js",types="esm/index.d.ts",scripts={dev:"tsc --watch",build:"tsc",docs:"rimraf docs && typedoc"},keywords=[],files=["esm","umd"],author="yangliye",license="MIT",dependencies={"@hysc/bloud":"workspace:*","@hysc/core":"workspace:*","@hysc/logger":"workspace:*","lodash-es":"^4.17.21",mitt:"^3.0.0","@hysc/p-queue":"6.3.0",rxjs:"^7.5.5",typescript:"^4.6.3","@hysc/utils":"workspace:*"},peerDependencies={"@hysc/core":"workspace:*"},devDependencies={"@types/lodash-es":"^4.17.6"},PackageJson={name:name,version:version,description:description,main:main,module:module$1,types:types,private:!1,scripts:scripts,keywords:keywords,files:files,author:author,license:license,dependencies:dependencies,peerDependencies:peerDependencies,devDependencies:devDependencies};function formatLog(e,t,r,i){let n=[];return r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}var LOGLEVEL=(e=>(e[e.INFO=0]="INFO",e[e.WARN=1]="WARN",e[e.ERROR=2]="ERROR",e[e.CLOSE=3]="CLOSE",e))(LOGLEVEL||{});const _Logger=class{static setEnableUpload(e){_Logger.enableUpload=e}static setLogLevel(e){_Logger.logLevel=e}static setNamespace(e){_Logger.namespace=e}static info(e,t,r,i=[]){_Logger.logLevel<=0&&(i.unshift(formatLog("INFO",e,t,r)),console.info(...i))}static warn(e,t,r,i=[]){_Logger.logLevel<=1&&(i.unshift(formatLog("WARN",e,t,r)),console.warn(...i))}static error(e,t,r,i=[]){_Logger.logLevel<=2&&(i.unshift(formatLog("ERROR",e,t,r)),console.error(...i))}};let Logger=_Logger;Logger.enableUpload=!1,Logger.logLevel=0,Logger.namespace="boom-core";class BMLiveVM{constructor(e){this.room=e}get localBMUser(){return this.room.getLocalParticipant()}get localIsAudience(){return this.room.getLocalParticipant().isAudience}handlePull(e){return __awaiter$2(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePull(e)):yield this.room.handlePull(e)}))}handleChangeStreamType(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.room.handleChangeStreamType(e)}))}handlePlay(e,t){return __awaiter$2(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePlay(e,t,!1)):yield this.room.handlePlay(e,t,!0)}))}handleAudienceDisable(){return __awaiter$2(this,void 0,void 0,(function*(){this.room.bmStreamVm.getStreamModels().forEach((e=>{var t;(null===(t=null==e?void 0:e.stream)||void 0===t?void 0:t.isSubscribed())&&e.hasPulled&&(e.hasPulled=!1,e.pulledStreamType="small",this.room.unsubscribe(e.stream).then((()=>{console.log("观众取消订阅这股流",e.userId,e.nickname,e.isDisplay,e.isCurrentDisplay)})))}));const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1))}))}handleAudienceEnable(){return __awaiter$2(this,void 0,void 0,(function*(){const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1)),this.room.bmStreamVm.getStreamModels().forEach((e=>{streamPullQueue.addQueue(this.room.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}))}))}}function addBrtcNetEvent(e){var t,r;null===(t=e.brtcClient.client)||void 0===t||t.signal.channel.on("reconnecting",(()=>e.fire(BCEvent$1.BRTC_ROOM_ROCONNECTING))),null===(r=e.brtcClient.client)||void 0===r||r.signal.channel.on("reconnected",(()=>e.fire(BCEvent$1.BRTC_ROOM_RECONNECTED)))}class SingletonQueue{constructor(){return this.pullMap=new Map,SingletonQueue.instance?SingletonQueue.instance:(SingletonQueue.instance=this,this)}addUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.set(`${e.id}_screen`,e):this.pullMap.set(e.id,e)})),this._callback&&this._callback(this.pullMap)}removeUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.delete(`${e.id}_screen`):this.pullMap.delete(e.id)}))}restart(){if(!this._callback)throw error$1("no callback exists in streamQueue please setQueueProcessor first!"),new Error("no callback");this._callback(this.pullMap)}setQueueProcessor(e){this._callback=e}removeQueueProcessor(){this._callback=void 0}}class AudioPlay{constructor(e,t){this.playMap=new WeakSet,this.playerMap=new Map,this.muted=!1,this.playStateChangeWatcher=new Subject;const r=document.getElementById(e);if(!r)throw new Error("no container found, play failed");this.container=r,this.room=t}addStream(e){if(this.room.shouldPlayAudio&&this.room.autoPlayAudio)if(this.playMap.has(e)){warn("stream is playing, replay",e.getUserId());const t=this.playerMap.get(e.getStreamId());t&&t.replay(e)}else info("add stream to player","",e.getUserId(),["streamId ",e.getStreamId()]),this.playMap.add(e),this.play(e)}removeStream(e){const t=e.getStreamId();let r=this.playerMap.get(t);r&&(r.off(),r.destroy()),info("remove audio player","","",["streamId =>",t]),this.playerMap.delete(t),this.playMap.delete(e)}removeStreamByUid(e){let t=new Map;this.playerMap.forEach((r=>{isShareStream(r.stream)||r.stream.getUserId()===e&&t.set(r.stream.getStreamId(),r)})),t.forEach(((e,t)=>{e.off(),e.destroy(),this.playerMap.delete(t),this.playMap.delete(e.stream)})),t.clear()}play(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(e.hasAudio()&&this.container){const r=new AudioPlayer(this.container,{});if(this.addPlayerEvent(r),yield r.play(e),this.deviceId&&(yield r.setSinkId(this.deviceId)),this.muted)r.setVolume(0);else{let i;const n=transShareScreen2User(e.getUserId());if(i=isShareStream(e)?this.room.bmStreamVm.shareStreamModels.get(n):this.room.bmStreamVm.streamModels.get(n),i){const e=null===(t=i.bloudStream)||void 0===t?void 0:t.customInfo;e&&e.volume&&(r.audioLevel=e.volume,r.setVolume(e.volume))}}this.playerMap.set(e.getStreamId(),r)}}))}mute(e){this.muted=e,e?this.playerMap.forEach((e=>e.setVolume(0))):this.playerMap.forEach((e=>{e.audioLevel>0?e.setVolume(e.audioLevel):e.setVolume(1)}))}setVolume(e,t){const r=this.playerMap.get(e);if(r){if(r.audioLevel=t,this.muted)return;r.setVolume(t)}else error$1("设置了流的音量,但是没有找到对应的播放器",e)}setDevice(e){this.deviceId=e,this.playerMap.forEach((t=>t.setSinkId(e)))}addPlayerEvent(e){e.on("player-state-changed",(t=>{e.stream&&(info("player state change","","",[JSON.stringify(t)]),"error"===t.type&&t.reason&&"NotAllowedError"===t.reason.name&&this.playStateChangeWatcher.next(e),"PAUSED"===t.state&&e.resume())}))}destroy(){this.playerMap.forEach((e=>e.destroy())),this.playerMap.clear(),this.playMap=new WeakSet}}let _selfSortType=1;const subscribeOptions={audio:!0,video:!0,streamType:"small",videoEnable:!0,audioEnable:!0};let autoPlayAudio=!0;class BMRoom{constructor({initDevices:e}={initDevices:!0}){this.roomVM=null,this.videoDevices=[],this.audioDevices=[],this.audioOutputDevices=[],this.selectVideoDevice=null,this.selectAudioDevice=null,this.selectAudioOutputDevice=null,this.streamQueue=new SingletonQueue,this.userListColumns=1,this.sortType=1,this.BRTCConnectFailed=!1,this.pubFailedNum=0,this.streamConnectedErrorQueue=[],this.conferenceMode=1,this.isBig=!1,this.selectVideoDeviceWatcher=new BehaviorSubject(this.selectVideoDevice),this.selectAudioDeviceWatcher=new BehaviorSubject(this.selectAudioDevice),this.selectAudioOutputDeviceWatcher=new BehaviorSubject(this.selectAudioOutputDevice),this.audioDevicesWatcher=new Subject,this.videoDevicesWatcher=new Subject,this.audioOutputDevicesWatcher=new Subject,this.raiseHandleRespWatcher=new Subject,this.enableAudienceSpeakingWatcher=new Subject,this.mediaPermission={microphone:!0,camera:!0,screen:!0},this.videoProfile="360p",this.audioProfile=null,this.streamWSReconnectWatcher=new Subject,this.bloudWSReconnectWatcher=new Subject,this.netConnecting=!0,this.netConnectingWatcher=new Subject,this.hasSyncPermission=!0,this.meetingControlOptions={cancelAutoPull:!1},this.forceId="",this.networkState={bloud:!0,brtc:!0},this.brtcNetEnableWatcher=new Subject,this.autoPlayAudio=!0,this.pubFailedTimer=null,this.messageWatcher=new BehaviorSubject({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),this.isInWaitRoom=!1,this.shouldPlayAudio=!0,this.handleReprocessStreamError=()=>{this.netConnecting&&this.networkState.brtc&&this.networkState.bloud&&this.streamConnectedErrorQueue.length&&(info("brtc 网络恢复正常,处理重推逻辑","","",this.streamConnectedErrorQueue),this.streamConnectedErrorQueue.forEach((e=>{this.handleStreamConnectError(e)})),this.streamConnectedErrorQueue=[])},this.handleMediaDevicesChange=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){const e=this.filterDevice(this.audioDevices);yield this.bmStreamVm.changeAudioInput(e);const t=this.filterDevice(this.audioOutputDevices);yield this.bmStreamVm.changeSpeaker(t)}))),1e3),this.enumVideoDevices=enumVideoDevices,this.enumAudioInputDevices=enumAudioInputDevices,this.enumAudioOutputDevices=enumAudioOutputDevices,this.getPermissions=getPermissions,this.checkSystemSupport=checkSystemSupport,this.createStream=createStream,this.participantNotice=!1,this.handleQueueTask=(e,t=!1)=>__awaiter$2(this,void 0,void 0,(function*(){this.BRTCConnectFailed||(e.isLocal||!this.meetingControlOptions.cancelAutoPull||e.shouldPull)&&(yield this.handleStreamTask(e,t))})),this.republishLocalStream=debounce((e=>__awaiter$2(this,void 0,void 0,(function*(){const t=e.getAudioOn()||!1,r=e.getVideoOn()||!1;info("republish local stream ","","",[t,r]),(t||r)&&(yield this.publish(e).then((()=>__awaiter$2(this,void 0,void 0,(function*(){this.bmStreamVm.bloudStream=null,yield this.bmStreamVm.publishBloudStream(t,r),info("local stream connect error, and republish success, bloud stream republish success","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess(t,r))})))).catch((()=>{info("local stream connect error, and republish failed","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectFailed())})))}))),1e3),this.processUser=e=>__awaiter$2(this,void 0,void 0,(function*(){const t=new Set;if(e.forEach((e=>{if(e.isScreen){const r=this.bmStreamVm.getShareStreamModelByUId(e.id);r&&r.stream||(e.isWeb?t.add(`${e.id}_screen`):t.add(e.id))}else{let r=this.bmStreamVm.streamModels.get(e.id);r&&!r.stream&&t.add(e.id)}})),info("brtc query streams","","",["queryIds => ",JSON.stringify(Array.from(t))]),t.size){const e=yield this.queryBrtcStreams(Array.from(t)).catch((e=>{error$1("query stream error","","",[JSON.stringify(e)])}));if(e&&e.length){const t=e.map((e=>[e.getUserId(),e.getStreamId()]));info("brtc query streams result","","",["streamInfo =>",JSON.stringify(t)]),e&&this.handleAddStreams(e)}}})),this.queueProcessor=debounce(this.processUser,500,{maxWait:1e3}),Logger.setLogLevel(LOGLEVEL.INFO),info(`\n******************************************************************************\n* 欢迎使用 BoomMeeting(${PackageJson.version}) Web SDK\n******************************************************************************\n `),Logger.info("this is formatted by hysc/logger module");const t=BoomEmitter.getInstance();this.localUser=new BMUser({},!0),this.roomInfo=new BMRoomInfo,this.roomInfo.bindRoom(this),this.bmLiveVM=new BMLiveVM(this),this.bmStreamVm=(new BMStreamModelVM).initWithRoom(this),this.boomCore=new BCClient({}),t.on(RECEIVE_SUBSCRIBE_MESSAGE,(e=>{this.handleSubMessage(e)})),t.on(HANDLE_STREAM_CONNECT_ERROR,(e=>{this.handleStreamConnectError(e)})),t.on(ADD_PULL_USER,(e=>{this.addUser2Queue(e)})),t.on(MANUAL_SUBSCRIPTION,(e=>{this.manualSubscribeStreamModel(e.stream)})),t.on(UNSUBSCRIBE_STREAM,(e=>{this.handleUnsubscribe(e.stream)})),t.on(BIND_ELEMENT,(e=>{this.handleStreamBindElement(e.stream)})),t.on(BIND_BIG_ELEMENT,(e=>{this.handleStreamBindBigElement(e.stream)})),t.on(SET_VOLUME,(e=>{var t;null===(t=this.audioPlayer)||void 0===t||t.setVolume(e.streamId,e.volume)})),t.on(ADD_AUDIO_PLAY,(e=>{const t=e.stream.stream;t&&!t.isLocalStream()&&(this.audioPlayer.playMap.has(t)||this.audioPlayer.addStream(t))})),window.addEventListener("offline",(()=>{this.netConnecting=!1,this.netConnectingWatcher.next(!1)})),window.addEventListener("online",(()=>{this.netConnecting=!0,this.netConnectingWatcher.next(!0),NETWORK_ERROR_QUEUE.forEach((e=>{e()})),NETWORK_ERROR_QUEUE.clear(),this.handleReprocessStreamError()})),window.navigator.mediaDevices&&e&&(window.navigator.mediaDevices.ondevicechange=()=>__awaiter$2(this,void 0,void 0,(function*(){yield this.initDevices(),yield this.handleMediaDevicesChange()})),this.initDevices()),this.streamQueue.setQueueProcessor(this.queueProcessor),this.brtcNetEnableWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()})),this.bloudWSReconnectWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()}))}get isSingleColumns(){return 1===this.userListColumns}setAutoPlayAudio(e){this.autoPlayAudio=e,autoPlayAudio=e}setMediaPermission(e){this.mediaPermission=Object.assign(Object.assign({},this.mediaPermission),e),info("current media permission is ","","",[JSON.stringify(this.mediaPermission)])}setShouldPlayAudio(e){this.shouldPlayAudio=e}initAudioPlayer(e){info("init audio player"),this.audioPlayer=new AudioPlay(e,this)}setupMeetingControlOptions(e){e&&(this.meetingControlOptions=Object.assign(Object.assign({},this.meetingControlOptions),e))}handleSubMessage(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e.stream),`${e.stream.streamId} - 订阅流 - display ${e.stream.isDisplay} - currentDisplay - ${e.stream.isCurrentDisplay}`,0,e.stream.nickname)}setVideoProfile(e){e&&(this.videoProfile=e)}setUserListColumns(e){const t=toNumber(e);if(!isNumber(t))throw new Error("参数必须是数字");this.userListColumns=t}setSortType(e){const t=toNumber(e);if(t>2||t<1)throw new Error("排序映射只能为 2 或者 1");this.sortType=t,_selfSortType=this.sortType}setAudioProfile(e){this.audioProfile=e}setSig(e){this.boomCore.setShareSig(e)}initDevices(){return __awaiter$2(this,void 0,void 0,(function*(){return Promise.all([this.enumVideoDevices().then((e=>{this.videoDevices=e,this.videoDevicesWatcher.next(e)})),this.enumAudioInputDevices().then((e=>{this.audioDevices=e,this.audioDevicesWatcher.next(e)})),this.enumAudioOutputDevices().then((e=>{this.audioOutputDevices=e,this.audioOutputDevicesWatcher.next(e)}))]).then((()=>{let e=this.videoDevices.filter((e=>{var t;return e.name==(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.name)}));const t=e[0]?e[0]:this.filterDevice(this.videoDevices);t&&this.setSelectVideoDevice(t);let r=this.audioDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.name)}));const i=r[0]?r[0]:this.filterDevice(this.audioDevices);i&&this.setSelectAudioDevice(i);let n=this.audioOutputDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.name)}));const s=n[0]?n[0]:this.filterDevice(this.audioOutputDevices);return s&&this.setSelectSpeakerDevice(s),{videoDevices:this.videoDevices,audioDevices:this.audioDevices,audioOutputDevices:this.audioOutputDevices,selectVideoDevice:this.selectVideoDevice,selectAudioDevice:this.selectAudioDevice,selectAudioOutputDevice:this.selectAudioOutputDevice}}))}))}filterDevice(e){const t=e.filter((e=>e.default))[0];return t||e[0]}setSelectAudioDevice(e){var t;(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectAudioDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioDevice=e,this.selectAudioDeviceWatcher.next(e))}setSelectVideoDevice(e){var t;(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectVideoDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectVideoDevice=e,this.selectVideoDeviceWatcher.next(e))}setSelectSpeakerDevice(e){var t;(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectSpeakerDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioOutputDevice=e,this.selectAudioOutputDeviceWatcher.next(e))}observe(e,t){return this.observes[e].subscribe(t)}join(e){return __awaiter$2(this,void 0,void 0,(function*(){const t=e.brtc_host;t&&this.setCustomUrl(t);try{if(this.boomCore.client)return error$1("重复 join,请先调用 destroy"),Promise.reject(RepeatJoinError);this.conferenceMode=e.roomType,this.isBig=e.is_big,info("========================","join info",e.userId,["roomId: ",e.room," roomType: ",e.roomType," roomName: ",e.name]),this.localUser.setup(e.userId,e.userinfo,e.nickname),this.bmStreamVm.createStreamModel(this.localUser),this.userVM=new BMUserVM(this.boomCore,this.localUser,this),this.isBig&&(this.userVM.commTimer=1e3),this.roomVM=new BMRoomVM(this.boomCore,this.userVM,this.roomInfo),this.roomVM.initWithRoom(this),this.chatVM=new BMChatVM(this.boomCore,this.userVM,this),this._attachEvents(),yield this.boomCore.join(e).catch((e=>Promise.reject(e))),this.roomInfo.setup(this.boomCore.getRoomInfo());for(let e in this.observes)this.observe(e,(()=>{}));this.bmStreamVm.startSpeakerDetector(),this.roomInfo.setlock(this.boomCore.client.lock),addBrtcNetEvent(this.boomCore)}catch(e){return error$1("join room error","","",[JSON.stringify(e)]),Promise.reject(e)}}))}leave(){var e,t;return __awaiter$2(this,void 0,void 0,(function*(){try{this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedNum=0,BoomEmitter.removeEmitter(),autoPlayAudio=!0,null===(e=this.audioPlayer)||void 0===e||e.destroy(),this.bmStreamVm.clearCache(),this.bmStreamVm.canvasTimer&&clearTimeout(this.bmStreamVm.canvasTimer);const r=yield this.boomCore.leave().catch((()=>{error$1("bloud离会失败")}));for(let e in this.observes)null===(t=this.observes[e])||void 0===t||t.unsubscribe();return this.observes={},r}catch(e){return error$1("leave room error","","",[JSON.stringify(e)]),Promise.reject(BmLeaveError(JSON.stringify(e)))}}))}releaseRoom(){return __awaiter$2(this,void 0,void 0,(function*(){yield this.boomCore.releaseRoom()}))}startRecord(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.startRecord(e)}))}stopRecord(){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.stopRecord()}))}sliceRecord(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.sliceRecord(e)}))}close(){this.bmStreamVm.clearCache(),this.boomCore.close()}setRemoteVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setRemoteAudioEnable(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteAudioEnable(e,t,r).catch((e=>Promise.reject(e)))}))}setLocalVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setLocalAudioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalAudioEnable(e).catch((e=>Promise.reject(e)))}))}setLocalSpeakerEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.muteSpeaker(e).catch((e=>Promise.reject(e)))}))}_attachEvents(){this.observes=attachEvents(this.boomCore,this.userVM,this.bmStreamVm,this.chatVM,this)}createSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter$2(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId};e.videoSource&&(n.videoSource=e.videoSource),e.audioSource&&(n.audioSource=e.audioSource),n.echoCancellation=!0,n.noiseSuppression=!0,n.autoGainControl=!0;const s=yield this.boomCore.createLocalStream(n,t).catch((t=>(error$1("create brtc stream error","","",[JSON.stringify(t),null==t?void 0:t.message]),Promise.reject(getStreamError(e.video?"摄像头":"麦克风")))));e.video&&("720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile));try{yield s.init()}catch(t){if(error$1("brtc init stream failed","","",[null==t?void 0:t.message]),String(t).includes("Permission denied by system")){if(e.video)return Promise.reject(BMCameraNotAuthError());if(e.audio)return Promise.reject(BMMicNotAuthError())}else{if(String(t).includes("Could not start video source"))return Promise.reject(BMCameraOccupyError());if(String(t).includes("Could not start audio source"))return Promise.reject(BMMicOccupyError())}return Promise.reject(BMCreateStreamError(e.video?"摄像头":"麦克风"))}return s}))}createPBSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter$2(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},s=yield this.boomCore.createPBLocalStream(n,t).catch((e=>Promise.reject(e)));return"720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile),yield s.init(),s}))}subscribe(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return this.boomCore.subscribe(e,t)}))}unsubscribe(e){return this.boomCore.unsubscribe(e).catch((e=>Promise.reject(e)))}publish(e){return new Promise(((t,r)=>{this.boomCore.publish(e).then((()=>{info("brtc stream publish success"),t(!0)})).catch((()=>__awaiter$2(this,void 0,void 0,(function*(){this.pubFailedNum<=3?(this.pubFailedNum+=1,this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedTimer=setTimeout((()=>(error$1(`local publish stream failed, retry failed num: ${this.pubFailedNum}`),this.publish(e).then(t).catch(r))),3e3)):(error$1("retry publish local stream failed, ubpublish now"),yield this.bmStreamVm.unpublishStream(),r(!1))}))))}))}unpublish(e){return this.boomCore.unpublish(e).catch((e=>Promise.reject(e)))}getUser(e){return this.userVM.getUser(e)}changeMaster(e,t=!1){var r;return __awaiter$2(this,void 0,void 0,(function*(){return null===(r=this.roomVM)||void 0===r?void 0:r.changeMaster(e,t).catch((e=>e))}))}updateManager(e,t,r=!0){return __awaiter$2(this,void 0,void 0,(function*(){return this.roomVM.updateManager(e,t,r).catch((e=>e))}))}getMaster(){return this.boomCore.getMaster()}getCreator(){return this.boomCore.getCreator()}getName(){return this.boomCore.getName()}evictUser(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.evictUser(e,t).catch((e=>e))}))}updateUser(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){null===(r=this.roomVM)||void 0===r||r.updateUser(e,t).catch((e=>e))}))}getMsgSeq(){return this.boomCore.getMsgSeq()}getLimits(){return this.boomCore.getLimits()}getSwitch(){return this.boomCore.getSwitch()}syncRoom(){return this.boomCore.syncRoom()}update(e){return this.boomCore.update(e)}getUsers(){return this.userVM.userList}getTotalUsers(){return this.userVM.userList.size}sendMessage(e,t){return this.boomCore.sendMessage(e,t)}customMessage(e,t){return this.boomCore.customMessage(e,t)}getMessages(e,t){return this.boomCore.getMessages(e,t)}getLocalParticipant(){var e;let t=null===(e=this.userVM)||void 0===e?void 0:e.getLocalUser();return t||(t=this.localUser),t}getAudioOff(){return this.boomCore.getAudioOff()}getSelfOpenAudio(){return this.boomCore.getSelfOpenAudio()}getVideoOff(){return this.boomCore.getVideoOff()}getMsgOff(){return this.boomCore.getMsgOff()}getLock(){return this.boomCore.getLock()}getRoomInfo(){return this.roomInfo}setAudioOff(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.setAudioOff(e,t).catch((e=>Promise.reject(BmSetAudioOffError(`boomCore.setAudioOff error ${JSON.stringify(e)}`))))}))}updateRoom(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.boomCore.client.update(e)}))}setVideoOff(e){return this.boomCore.setVideoOff(e).catch((e=>Promise.reject(BmSetVideoOffError(`boomCore.setVideoOff error ${JSON.stringify(e)}`))))}setMsgOff(e){return this.boomCore.setMsgOff(e).catch((e=>Promise.reject(BmSetMsgOffError(`boomCore.setMsgOff error ${JSON.stringify(e)}`))))}setSwitch(e){return this.boomCore.setSwitch(e)}setLock(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.setLock(e),this.boomCore.getLock()}))}sendChatMessage(e,t,r){if(!this.chatVM)throw new BoomError$1(INVALID_OPERATION,"未初始化chatVM, 无法发送聊天信息");return this.chatVM.sendMessage(e,t,r)}getChatMessage(){if(!this.chatVM)throw new BoomError$1(INVALID_OPERATION,"未初始化chatVM, 无法获取聊天室消息");return this.chatVM.messageList}getHistoryMessage(){return __awaiter$2(this,void 0,void 0,(function*(){return this.chatVM.getHistoryMessage()}))}updateCustomStats(e){return info("updateCustomStats","","",[JSON.stringify(e)]),this.boomCore.updateCustomStats(Object.assign(Object.assign({},e),{pos:"web"})).catch((e=>Promise.reject(BmUpdateCustomStatsError(`.boomCore.updateCustomStats ${JSON.stringify(e)}`))))}getCustomStats(){return this.boomCore.getCustomStats()}getDuration(){return this.boomCore.getDuration()}checkUserHasMaster(e){return this.userVM.checkUserHasMaster(e)}changeNickName(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.changeNickName(e,t)}))}handleStreamTask(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){e.stream?1===this.conferenceMode?(yield this.handlePull(e),yield this.handleChangeStreamType(e),yield this.handlePlay(e,t)):(yield this.bmLiveVM.handlePull(e),yield this.bmLiveVM.handleChangeStreamType(e),yield this.bmLiveVM.handlePlay(e,t)):((e.isDisplay||e.isInBig)&&e.bloudStream||e.audioEnable)&&(yield this.addUser2Queue({id:e.userId,isScreen:e.isShare,isWeb:e.isWeb}))}))}handlePull(e){var t,r,i,n;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal||(e.isMixer&&(yield this.handleSubscribeSteam(e)),e.isDisplay!==e.isCurrentDisplay||e.isInBig&&e.pulledStreamType!==e.pulledStreamGoal||!e.hasPulled?(info(" 订阅流 => ","订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t)]),e.isCurrentDisplay=e.isDisplay,e.checkCount=0,e.isDisplay||e.isInBig||!e.isDisplay&&(e.audioEnable||(null===(i=e.stream)||void 0===i?void 0:i.getAudioOn()))?yield this.handleSubscribeSteam(e):yield this.handleUnsubscribeStream(e)):e.stream&&e.audioEnable&&(null===(n=this.audioPlayer)||void 0===n||n.addStream(e.stream)))}))}manualSubscribeStreamModel(e){streamPullQueue.addQueue(this.handleStreamTask.bind(this,e),e.streamId,0,e.nickname)}handleUnsubscribe(e){streamPullQueue.addQueue(this.handleUnsubscribeStream.bind(this,e),e.streamId,0,e.nickname)}handleStreamBindElement(e){streamPullQueue.addQueue(this.handlePlay.bind(this,e,!1,!1),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleStreamBindBigElement(e){streamPullQueue.addQueue(this.handlePlayInBIg.bind(this,e),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleUnsubscribeStream(e){var t,r,i,n,s;return __awaiter$2(this,void 0,void 0,(function*(){e.stream&&((null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t))||e.hasPulled)&&(info("取消订阅流 => ","取消订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)]),e.hasPulled=!1,e.pulledStreamType="small",e.isInBig=!1,yield null===(s=e.stream)||void 0===s?void 0:s.stop(),yield this.unsubscribe(e.stream).then((()=>{var t;e.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(e.stream)),e.isSubScribedWatcher.next(!1),info("取消订阅这股流","",e.userId,[e.nickname,e.isDisplay,e.isCurrentDisplay])})).catch((()=>{error$1("unsubscribe error")})))}))}handleSubscribeSteam(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){try{e.hasPulled&&e.stream.isSubscribed()?e.isDisplay?null===(t=e.stream)||void 0===t||t.unmuteVideo().then((()=>{info("stream unmute video success","unmute-video",e.userId,["streamId => ",e.streamId])})):null===(r=e.stream)||void 0===r||r.muteVideo().then((()=>{info("stream mute video success","mute-video",e.userId,["streamId => ",e.streamId])})):(e.hasPulled=!0,yield this.subscribe(e.stream,subscribeOptions).then((()=>{var t,r;e.isDisplay||null===(t=e.stream)||void 0===t||t.muteVideo(),e.stream&&e.audioEnable&&(null===(r=this.audioPlayer)||void 0===r||r.addStream(e.stream)),e.pullFailedNum=0,info("订阅流结束","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId,"display =>",e.isDisplay]),e.isSubScribedWatcher.next(!0),this.bmStreamVm.addToRecorder(e.stream),e.isDisplay&&e.videoEnable&&checkStreamIsNormal(e)})).catch((t=>{var r,i;if(error$1("订阅流失败","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId," error => ",JSON.stringify(t)]),e.hasPulled=!1,e.pulledStreamType="small",e.pullFailedNum+=1,null===(r=e.player)||void 0===r||r.destroy(),e.pullFailedNum<=3)this.handlePulledFailed(e);else{e.pullFailedNum=0;const r=e.isShare;try{null===(i=e.stream)||void 0===i||i.destroy()}catch(t){}e.updateStream(void 0,!1,this.bmStreamVm),info("subscribe stream failed, need to reQuery stream","",e.userId,["streamId =>",e.streamId,"hasStream => ",!!e.stream,"isWeb => ",e.isWeb,"isScreen => ",r]),this.addUser2Queue({id:e.userId,isWeb:e.isWeb,isScreen:r})}})))}catch(t){e.hasPulled=!1,e.pulledStreamType="small",console.error("订阅流失败","",e.userId,e.nickname,"错误 =>",t)}}))}handleChangeStreamType(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal||e.pulledStreamType!==e.pulledStreamGoal&&(null===(t=e.stream)||void 0===t?void 0:t.isSubscribed())&&((null===(r=e.stream)||void 0===r?void 0:r.isSubscribed())||e.hasPulled)&&(info("大小流切换 => ","切换大小流",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," pulledStreamType =>",e.pulledStreamType," pulledStreamGoal =>",e.pulledStreamGoal]),e.pulledStreamType=e.pulledStreamGoal,yield this.boomCore.brtcClient.setRemoteVideoStreamType(e.stream,e.pulledStreamGoal).catch((t=>{error$1("大小流切换失败","",e.userId,["error => ",JSON.stringify(t)])})),info("大小流切换结束","",e.userId,["nickname =>",e.nickname," isInBig => ",e.isInBig," pulledStreamGoal => ",e.pulledStreamGoal,"pulledStreamType => ",e.pulledStreamType]))}))}handlePlay(e,t,r=!0){var i,n,s;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal?e.isShare||t||(e.play(),e.playInBig()):(e.hasPulled||(null===(i=null==e?void 0:e.stream)||void 0===i?void 0:i.isSubscribed()))&&(t&&!e.isShare||e.play(),e.stream&&e.audioEnable&&((null===(n=this.audioPlayer)||void 0===n?void 0:n.playMap.has(e.stream))||null===(s=this.audioPlayer)||void 0===s||s.addStream(e.stream)),r&&(yield this.handlePlayInBIg(e)))}))}handlePlayInBIg(e){return __awaiter$2(this,void 0,void 0,(function*(){yield e.playInBig()}))}handlePulledFailed(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}handleStreamConnectError(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){const{stream:r,isLocal:i}=e;info("handleStreamConnectError","","",["nickname =>",r.nickname,"streamId => ",r.streamId,"isShare =>",r.isShare,"isLocal => ",i]),r.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(r.stream)),i?r.stream&&(r.isShare?this.bmStreamVm.localShareError.next(BMShareStreamConnectError()):this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamConnectError()),this.netConnecting&&this.networkState.brtc&&this.networkState.bloud?r.isShare?(info("Local share stream has problem, now ,republish"),handleShareStreamFailed(this,this.bmStreamVm)):(info("brtc 网络正常,重新推流"),r.stream&&(yield this.republishLocalStream(r.stream))):(error$1("brtc 网络还没恢复,等恢复了在重新推流 ","",r.userId,["nickname =>",r.nickname,"streamId => ",r.streamId,"isShare =>",r.isShare]),this.streamConnectedErrorQueue.push(e))):this.netConnecting&&this.networkState.brtc?(r.hasPulled=!1,r.pulledStreamType="small",streamPullQueue.addQueue(this.handleQueueTask.bind(this,r),r.streamId,0,r.nickname)):(error$1("brtc 网络还没恢复,等恢复了在重新拉流 ","",r.userId,["nickname =>",r.nickname]),this.streamConnectedErrorQueue.push(e))}))}toggleAudienceSpeaking(e,t){e.permission.setAudio(t),this.updateUser(e.userId,{permission:e.permission.get()})}updateUserIsGuest(e,t){return __awaiter$2(this,void 0,void 0,(function*(){e.permission.setSubscribe(t),yield this.updateUser(e.userId,{permission:e.permission.get()})}))}managerChangeToGuest(e){this.userVM.managerChangeToGuest(e)}moveUserRoom(e,t=!1,r=!1){return this.boomCore.client.moveUserRoom(e,t,r)}getParticipantNotice(e){this.participantNotice=e}setCustomUrl(e){this.boomCore.setCustomUrl(e)}handleRePushSelf(){var e,t;return __awaiter$2(this,void 0,void 0,(function*(){const r=null===(t=null===(e=this.getLocalParticipant())||void 0===e?void 0:e.getMainStreamModel())||void 0===t?void 0:t.stream;r&&(yield this.republishLocalStream(r))}))}handleResetOtherStreamStatus(){info("brtc sync-room-completed"),this.bmStreamVm.streamModels.forEach((e=>{var t;e.isLocal||(e.hasPulled=!1,e.pulledStreamType="small",e.stream&&e.stream.stop(),null===(t=e.stream)||void 0===t||t.destroy(),e.updateStream(void 0,!1,this.bmStreamVm))})),this.bmStreamVm.shareStreamModels.forEach((e=>{var t,r;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";const i=e.getUser();null===(t=e.stream)||void 0===t||t.stop(),null===(r=e.stream)||void 0===r||r.destroy(),i.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`)}})),this.bmStreamVm.shareStreamModels.clear(),this.bmStreamVm.shareStreamModelsWatcher.next(Array.from(this.bmStreamVm.shareStreamModels.values())),this.networkState.brtc=!0,setTimeout((()=>{this.brtcNetEnableWatcher.next(!0),this.streamWSReconnectWatcher.next(!0)}),2e3),handleReconnectedStream(this)}addUser2Queue(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(e.isScreen)this.streamQueue.addUsers([e]);else{const r=this.bmStreamVm.streamModels.get(e.id);r&&!r.isLocal&&(r.stream||r&&((null===(t=r.bloudStream)||void 0===t?void 0:t.audio)||r.bloudStream&&r.isDisplay)&&this.streamQueue.addUsers([e]))}}))}queryBrtcStreams(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.brtcClient.queryUsers(e)}))}handleAddStreams(e){e.forEach((e=>{if(isShareStream(e)){const t=this.bmStreamVm.shareStreamModels.get(transShareScreen2User(e.getUserId()));(!t||t&&!t.stream)&&this.bmStreamVm.remoteStreamPublished(e)}else{const t=this.bmStreamVm.streamModels.get(e.getUserId());t&&!t.stream&&this.bmStreamVm.remoteStreamPublished(e)}}))}getForceUser(e){return __awaiter$2(this,void 0,void 0,(function*(){const{users:t}=yield this.boomCore.queryUsers([e]);this.userVM.addBcUsersMap(t,!0),this.userVM.getForceUserWatcher.next(!0)}))}getVersion(){return PackageJson.version}}return window.BoomMeeting=BMRoom,window.BoomError=BoomError,BMRoom}));
|
|
825
|
+
/*! exports provided: generateUUID, callbackToPromise, getAudioContext, createAudioMeter, createVolumeMeter, parseVloudStreamOptions, timestamp, resumeContext, getEmptyVloudStats, timestampMillisecond */function(e,t,r){r.r(t),r.d(t,"generateUUID",(function(){return o})),r.d(t,"callbackToPromise",(function(){return a})),r.d(t,"getAudioContext",(function(){return u})),r.d(t,"createAudioMeter",(function(){return d})),r.d(t,"createVolumeMeter",(function(){return l})),r.d(t,"parseVloudStreamOptions",(function(){return h})),r.d(t,"timestamp",(function(){return m})),r.d(t,"resumeContext",(function(){return p})),r.d(t,"getEmptyVloudStats",(function(){return f})),r.d(t,"timestampMillisecond",(function(){return g}));var i=r(/*! bjy-common/src/function/execute */"./node_modules/bjy-common/src/function/execute.ts"),n=r(/*! bjy-common/src/function/nextTick */"./node_modules/bjy-common/src/function/nextTick.ts"),s=r(/*! bjy-common/src/function/getTimestamp */"./node_modules/bjy-common/src/function/getTimestamp.ts");function o(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))}function a(e,t,r,s=!0){return new Promise(((o,a)=>{s&&t.push((function(e){o(e)})),t.push((function(e){a(e)})),Object(i.default)(e,r,t),s||Object(n.default)((()=>{o()}))}))}let c;function u(){if(c)return c;let e=window.AudioContext||window.webkitAudioContext;return c=new e,c}function d(e,t=.98,r=.95,i=750){const n=e.createScriptProcessor(2048,1,1);return n.onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0),r=t.length;let i,s=0;for(let e=0;e<r;e++)i=t[e],Math.abs(i)>=n.clipLevel&&(n.clipping=!0,n.lastClip=window.performance.now()),s+=i*i;const o=Math.sqrt(s/r);n.volume=Math.max(o,n.volume*n.averaging)},n.clipping=!1,n.lastClip=0,n.volume=0,n.clipLevel=t,n.averaging=r,n.clipLag=i,n.connect(e.destination),n.checkClipping=()=>!!n.clipping&&(n.lastClip+n.clipLag<window.performance.now()&&(n.clipping=!1),n.clipping),n.shutdown=()=>{n.disconnect(),e.close(),n.onaudioprocess=null},n}function l(e,t){if(e._volumeMeter&&e._volumeMeter.disconnect(),t&&"audio"===t.kind){let r=new MediaStream;r.addTrack(t);let i=u(),n=i.createMediaStreamSource(r);e._volumeMeter=d(i),n.connect(e._volumeMeter)}e.getAudioLevel=()=>e._volumeMeter?e._volumeMeter.volume:0}function h(e,t){return e.audioSource||e.videoSource?{audio:!!e.audioSource,video:!!e.videoSource}:e.screen?{audio:!!e.audio,video:!0,screen:!0,fps:t.frameRate}:{audio:!!e.audio,video:!!e.video}}function m(){return Math.floor((new Date).getTime()/1e3)}function p(){return function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){c&&(yield c.resume())}))}function f(){return{bandwidth:{upload:0,download:0},bitrate:{audio:{upload:0,download:0},video:{upload:0,download:0}},packetLoss:{audio:{upload:0,download:0},video:{upload:0,download:0}},resolution:{width:0,height:0},framerate:0,audioLevel:0,transport:[{ip:"",type:"",localIp:"",localCandidateType:"",remoteCandidateType:"",networkType:"",rtt:0}],quality:{audio:{jitter:0,interruptionCount:0,interruptionDuration:0},video:{jitter:0,interruptionCount:0,interruptionDuration:0}},statistics:{audio:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0},video:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0,framesEncoded:0,framesDecoded:0,framesSent:0},bweforvideo:{googAvailableReceiveBandwidth:0,googAvailableSendBandwidth:0,googRetransmitBitrate:0,googTransmitBitrate:0,googTargetEncBitrate:0},ice:{packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0}},cpu:{appCpu:0,systemCpu:0}}}function g(e=0){return Object(s.default)()+e}}})},BRTC$2.exports=factory();var BRTC=getDefaultExportFromCjs(BRTC$2.exports),BRTC$1=_mergeNamespaces$1({__proto__:null,default:BRTC},[BRTC$2.exports]),BoomCoreErrorCode$1;class BoomError$2 extends Error{constructor(e,t,r){let i;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,i="string"==typeof t?t:JSON.stringify(t),this.message=i,r&&(this.name=r)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}}!function(e){e[e.BloudLock=28]="BloudLock",e[e.ShareScreenNoPermission=100]="ShareScreenNoPermission",e[e.ShareScreenCanceled=101]="ShareScreenCanceled",e[e.ShareScreenOtherError=102]="ShareScreenOtherError",e[e.ShareScreenContentHintError=103]="ShareScreenContentHintError",e[e.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",e[e.BrtcShareSigError=105]="BrtcShareSigError",e[e.ToggleShareScreenError=106]="ToggleShareScreenError",e[e.BrtcCreateStreamError=107]="BrtcCreateStreamError",e[e.BrtcSubscribeError=108]="BrtcSubscribeError",e[e.BrtcPublishError=109]="BrtcPublishError",e[e.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",e[e.BrtcUnPublishError=111]="BrtcUnPublishError",e[e.RepeatJoinError=112]="RepeatJoinError",e[e.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",e[e.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",e[e.JoinUserInfoError=115]="JoinUserInfoError",e[e.JoinTypeError=116]="JoinTypeError",e[e.JoinBrtcError=117]="JoinBrtcError",e[e.JoinBloudError=118]="JoinBloudError",e[e.UpdateCustomStatsError=119]="UpdateCustomStatsError",e[e.CreateBloudError=120]="CreateBloudError"}(BoomCoreErrorCode$1||(BoomCoreErrorCode$1={}));const ShareScreenNoPermission=new BoomError$2(BoomCoreErrorCode$1.ShareScreenNoPermission,"没有打开共享屏幕录制权限","no share permission"),ShareScreenCanceled=new BoomError$2(BoomCoreErrorCode$1.ShareScreenCanceled,"取消共享屏幕","cancel share"),ShareScreenOtherError=e=>new BoomError$2(BoomCoreErrorCode$1.ShareScreenOtherError,e);new BoomError$2(BoomCoreErrorCode$1.ShareScreenContentHintError,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed");const ShareScreenClientJoinedError=new BoomError$2(BoomCoreErrorCode$1.ShareScreenClientJoinedError,"共享屏幕brtc client入会失败","share client join failed"),BrtcShareSigError=new BoomError$2(BoomCoreErrorCode$1.BrtcShareSigError,"brtcShareSig为空","brtc share sig is empty"),ToggleShareScreenError=e=>new BoomError$2(BoomCoreErrorCode$1.ToggleShareScreenError,e,"toggle share has error"),RepeatJoinError$1=new BoomError$2(BoomCoreErrorCode$1.RepeatJoinError,"正在 join,请勿重复调用","repeat join error"),ProxiesUrlTypeError=new BoomError$2(BoomCoreErrorCode$1.ProxiesUrlTypeError,"proxies url 必须为字符串","get bloud proxies param error"),getBloudProxiesUrlError=e=>new BoomError$2(BoomCoreErrorCode$1.getBloudProxiesUrlError,e,"get bloud proxies error"),JoinUserInfoError=new BoomError$2(BoomCoreErrorCode$1.JoinUserInfoError,"userinfo传递错误,请检查"),JoinTypeError=new BoomError$2(BoomCoreErrorCode$1.JoinTypeError,"type传递错误,请检查"),JoinBrtcError=e=>new BoomError$2(BoomCoreErrorCode$1.JoinBrtcError,e,"join brtc error"),BrtcCreateStreamError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcCreateStreamError,"brtc 创建本地流失败"),BrtcPublishError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcPublishError,e,"brtc pub failed"),BrtcUnsubscribeError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcUnsubscribeError,e,"brtc sub failed"),BrtcUnPublishError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcUnsubscribeError,e,"brtc unpub failed");var BoomMeetingErrorCode$1,StreamErrorMap$1;!function(e){e[e.BmJoinError=200]="BmJoinError",e[e.BMLeaveError=201]="BMLeaveError",e[e.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",e[e.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",e[e.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",e[e.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",e[e.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",e[e.BmChangeMasterError=207]="BmChangeMasterError",e[e.BmUpdateManagerError=208]="BmUpdateManagerError",e[e.BmEvictUserError=209]="BmEvictUserError",e[e.BmUpdateUserError=210]="BmUpdateUserError",e[e.BmSetAudioOffError=211]="BmSetAudioOffError",e[e.BmSetVideoOffError=212]="BmSetVideoOffError",e[e.BmSetMsgOffError=213]="BmSetMsgOffError",e[e.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",e[e.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",e[e.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",e[e.BmCheckDeviceError=217]="BmCheckDeviceError"}(BoomMeetingErrorCode$1||(BoomMeetingErrorCode$1={})),function(e){e[e.createStream=1302]="createStream",e[e.noCameraDevice=1303]="noCameraDevice",e[e.noMicroDevice=1304]="noMicroDevice",e[e.noSpeakerDevice=1305]="noSpeakerDevice",e[e.openCamera=1301]="openCamera",e[e.cameraNotAuth=1314]="cameraNotAuth",e[e.cameraOccupy=1315]="cameraOccupy",e[e.openMicro=1302]="openMicro",e[e.micNotAuth=1317]="micNotAuth",e[e.micOccupy=1319]="micOccupy",e[e.streamDisconnected=1320]="streamDisconnected",e[e.syncFail=1321]="syncFail",e[e.getStreamFail=1322]="getStreamFail",e[e.streamConnectError=1323]="streamConnectError",e[e.streamReconnectSuccess=1324]="streamReconnectSuccess",e[e.streamReconnectFailed=1325]="streamReconnectFailed",e[e.shareStreamConnectError=1326]="shareStreamConnectError",e[e.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",e[e.shareStreamConnectFailed=1328]="shareStreamConnectFailed"}(StreamErrorMap$1||(StreamErrorMap$1={}));class BCClient{constructor(e){this.emitters=[],this.name="",this.type=SING_MODE,this.appId="",this.brtcAppId="",this.roomId="",this.tarCreate=!1,this.userinfo={},this.userId="",this.isJoining=!1,this.collection="",this.limit=0,this.token="",this.customToken="",this.create=!1,this.host="",this.getProxiesUrl="",this.secret="",this.enableRace=!1,this.disableMediaEngine=!1,this.roomType=1,this.audioCodec="opus",this.codec="h264",this.hasBloudJoined=!1,this.brtcSig="",this.shareContentHint="detail",this.identity="",this.isBig="0",this.brtcJoined=!1,this.joinReady=!1,this.joinBrtc=()=>new Promise(((e,t)=>{this.brtcClient.join(this.roomId,this.userId,this.sig).then((()=>(info$1("join brtc succeed"),this.brtcJoined=!0,e(!0)))).catch((e=>(console.log("brtc入会失败01",e),this.isJoining=!1,t(JoinBrtcError(e.message)))))})),this.joinBloud=()=>new Promise(((e,t)=>{SingleMode.singleModeJoin(this,(()=>this.addBloudEvent())).then((()=>(info$1("join bloud succeed"),this.hasBloudJoined=!0,e(!0)))).catch((e=>(error$2("bloud入会失败02","",[e]),this.isJoining=!1,t(e))))})),this.handleBloudSharePubFailed=()=>{error$2("bloud share stream unpublish failed, interval retry");let e=setInterval((()=>__awaiter$1(this,void 0,void 0,(function*(){clearInterval(e),yield this.bloudShareScreenStream.unpublish().then((()=>{this.bloudShareScreenStream=void 0})).catch((()=>{this.handleBloudSharePubFailed()}))}))),2e3)},this.emitter=new Emitter(!0),addEvent2Bloud(),window.BRTC=BRTC$1}setShareSig(e){this.brtcShareSig=e}clearObject(){this.client&&(this.client.close(),this.client.removeAllListeners()),this.client=null,this.collection&&(this.collection.close(),this.collection=null)}join(e){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise(((t,r)=>__awaiter$1(this,void 0,void 0,(function*(){if(this.isJoining)return Promise.reject(RepeatJoinError$1);if(this.client)return Promise.reject(RepeatJoinError$1);if("string"!=typeof e.getProxiesUrl)return Promise.reject(ProxiesUrlTypeError);if(!e.userinfo||e.userinfo&&"object"!=typeof e.userinfo)return Promise.reject(JoinUserInfoError);if("number"!=typeof e.type||1!==e.type&&2!==e.type)return Promise.reject(JoinTypeError);if(this.userId=e.userId,this.roomId=e.room,this.roomType=e.roomType,this.collection=e.collection,this.userinfo=e.userinfo,this.getProxiesUrl=e.getProxiesUrl,this.appId=e.appId,this.brtcAppId=e.brtcAppId,this.type=e.type,this.tarCreate=e.create,this.limit=e.limit,this.secret=e.secret,this.enableRace=e.enableRace,this.token=e.token,this.customToken=e.customToken,this.name=e.name,this.brtcSig=e.sig,this.identity=e.identity,this.isBig=e.is_big,this.sig=e.sig,Global.token=e.token,this.isJoining=!0,this.type===SING_MODE&&(yield SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))),this.type===MIX_MODE){this.disableMediaEngine=!0;try{this.brtcClient=BRTC$2.exports.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,audioLevelInterval:200,roomType:"big",silence:!0}),this.createShareBrtcClient(),this.addBrtcEvent(),this.fire("brtc-bound",!0),BRTC$2.exports.setVTRequestTimeout(5),yield this.joinRoom().then((()=>(this.isJoining=!1,this.fire(BCEvent$2.JOIN_READY),t(!0)))).catch((e=>(error$2("join room error","",this.userId,[JSON.stringify(e)]),r(e))))}catch(e){return this.isJoining=!1,error$2("join room error",LOGGER_TAG_CLIENT$1,this.userId,[e]),r(e)}}}))))}))}joinRoom(){return new Promise(((e,t)=>{let r=!1,i=!1;this.joinBloud().then((()=>{if(r=!0,i)return e(!0)})).catch((e=>t(e))),this.joinBrtc().then((()=>{if(i=!0,r)return e(!0)})).catch((e=>t(e)))}))}createShareBrtcClient(){return this.shareBrtcClient||(this.shareBrtcClient=BRTC$2.exports.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,roomType:"big",silence:!0}),this.shareBrtcClient.on("error",(e=>{this.fire("share-brtc-error",e)}))),this.shareBrtcClient}_getBloudProxiesUrl(e){return new Promise(((t,r)=>{request({url:`${this.getProxiesUrl}/proxies?token=${e}`}).then((r=>{t({proxies:r.proxies,token:e})})).catch((e=>{r(getBloudProxiesUrlError(e))}))}))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}changeMaster(e,t=!1){return this.client.changeMaster(e,t).catch((e=>e))}getMaster(){return this.client.getMaster()}syncUser(e){return this.client.syncUser(e)}getCreator(){return this.client.getCreator()}getName(){return this.client.getName()}close(){var e;return __awaiter$1(this,void 0,void 0,(function*(){this.leaveBrtcRoom(),null===(e=this.client)||void 0===e||e.close(),this.leaveShare()}))}getMsgSeq(){return this.client.getMsgSeq()}evictUser(e,t){return this.client.evictUser2(this.getMaster(),e,t)}updateUser(e,t){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.updateUser(e,t)}))}getLimits(){return this.client.getLimits()}getSwitch(){return this.client.getSwitch()}syncRoom(){return this.client.syncRoom()}update(e){return this.client.update(e)}getUsers(e,t,r){return __awaiter$1(this,void 0,void 0,(function*(){let{participants:i,total:n}=yield this.client.getUsers(e,t,r),s=new Map;return i.forEach((e=>{let t=BCUser.toUser(e,this.type);s.set(t.userId,t)})),{users:s,total:n}}))}updateStream(e,t,r){return this.client.updateStream(e,t,r)}getUsersList(e,t,r,i){return __awaiter$1(this,void 0,void 0,(function*(){let{participants:n,total:s,pageIndex:o}=yield this.client.getUsersList(e,r,t,i),a=new Map;return n.forEach((e=>{let t=BCUser.toUser(e,this.type);a.set(t.userId,t)})),{users:a,total:s,pageIndex:o}}))}getTotalUsers(){return this.client.getTotalUsers()}sendMessage(e,t){return this.client.sendMessage(e,t)}customMessage(e,t){return this.client.customMessage(e,t)}getMessages(e,t){return this.client.getMessages(e,t)}getLocalParticipant(){var e;return null===(e=this.client)||void 0===e?void 0:e.getLocalParticipant()}getAudioOff(){return this.client.getAudioOff()}getSelfOpenAudio(){return this.client.getSelfOpenAudio()}getVideoOff(){return this.client.getVideoOff()}getMsgOff(){return this.client.getMsgOff()}getLock(){return this.client.getLock()}getRoomInfo(){let e=Object.assign({},this.client.options);return delete e.token,e}setAudioOff(e,t){return this.client.setAudioOff(e,t)}setVideoOff(e){return this.client.setVideoOff(e)}setMsgOff(e){return this.client.setMsgOff(e)}setSwitch(e){return this.client.setSwitch(e)}setLock(e){return this.client.setLock(e)}publish(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.publish(e).catch((e=>Promise.reject(BrtcPublishError(JSON.stringify(e)))))}))}unpublish(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.unpublish(e).catch((e=>Promise.reject(BrtcUnPublishError(JSON.stringify(e)))))}))}subscribe(e,t={audio:!0,video:!0}){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.subscribe(e,t).catch((e=>Promise.reject(e)))}))}unsubscribe(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.unsubscribe(e).catch((e=>Promise.reject(BrtcUnsubscribeError(JSON.stringify(e)))))}))}addBloudEvent(){let e=this,t=BloudParameterHandlerMap;each$1(bloudEvents,(r=>{!function(r,i){e.client.on(r,(function(){let r=execute(t[i],e,toArray(arguments));e.fire(i,r)}))}(r,r)}))}addBrtcEvent(){const e=this;each$1(BrtcEvents,(t=>{var r;r=t,e.brtcClient.on(r,(t=>{e.fire(r,t)}))}))}clearBrtcEvent(){this.brtcClient.off()}leave(){return __awaiter$1(this,void 0,void 0,(function*(){return console.log("离开会议","userId =>",this.userId,"roomId =>",this.roomId,"userInfo =>",this.userinfo),yield SingleMode.singleModeLeave(this),this.leaveBrtcRoom()}))}leaveBrtcRoom(){return __awaiter$1(this,void 0,void 0,(function*(){if(console.log("离开brtc调用堆栈!!!!!"),this.brtcClient&&(this.brtcClient.off(),yield this.brtcClient.leave(),yield this.brtcClient.destroy(),this.brtcClient=null),this.shareBrtcClient){try{this.shareBrtcClient.off(),yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(),this.shareBrtcClient=null}}))}leaveShare(){return __awaiter$1(this,void 0,void 0,(function*(){if(this.shareBrtcClient){try{yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(),this.shareBrtcClient=null}}))}getEventList(){return BCEvent$2}createRecorder(e){return this.client.Recorder(e)}createSpeakerDetector(){return this.client.SpeakerDetector()}createLocalStream(e,t){return __awaiter$1(this,void 0,void 0,(function*(){BRTC$2.exports.isSmallStreamSupported()?yield this.brtcClient.enableSmallStream():error$2("simulcast is not supported"),this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return BRTC$2.exports.createStream(e)}catch(e){return Promise.reject(e)}}))}createPBLocalStream(e,t){return __awaiter$1(this,void 0,void 0,(function*(){this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return BRTC$2.exports.createStream(e)}catch(e){return Promise.reject(BrtcCreateStreamError(JSON.stringify(e)))}}))}creteBloudLocalStream(e,t){return this.client.Stream({audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t,screen:!1})}createBloudScreenStream(e,t){return this.client.Stream({screen:!0,audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t})}updateCustomStats(e,t=!1){return info$1("updateCustomStats","updateCustomStats","",[" customstats => ",JSON.stringify(e),"replace => ",t]),this.client.updateCustomStats({customStats:e},t)}getCustomStats(){var e;return null===(e=this.client)||void 0===e?void 0:e.getCustomStats()}getDuration(){var e;return null===(e=this.client)||void 0===e?void 0:e.duration}toggleShareScreen(e,t,r){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise(((t,i)=>__awaiter$1(this,void 0,void 0,(function*(){if(e)try{let e;e=r?yield BRTC$2.exports.createStream({video:!!r.videoSource,audio:!!r.audioSource,videoSource:r.videoSource,audioSource:r.audioSource,screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail",sourceType:"screen"}):yield BRTC$2.exports.createStream({screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail",sourceType:"screen"});const i="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:i.frameRate,bitrate:i.bitrate});try{yield e.init()}catch(e){throw error$2("brtc stream init failed","","",[e]),new Error(e)}yield this.publishShareStream(e),t(!0)}catch(e){String(e).includes("Permission denied by system")?(error$2("没有打开共享屏幕录制权限","","this.userId"),i(ShareScreenNoPermission)):String(e).includes("Permission denied")?(info$1("点击了取消共享屏幕","",this.userId,["nickname =>",this.name]),i(ShareScreenCanceled)):(error$2("开启共享屏幕失败","","",[JSON.stringify(e)]),i(ShareScreenOtherError("开启共享屏幕失败,请重试")))}else yield this.unpublishShareStream(),t(!0)}))))}))}shareHTMLMedia(e,t){return __awaiter$1(this,void 0,void 0,(function*(){if(e&&t)try{const e=BRTC$2.exports.createStream({audio:t.audio,video:t.video,videoSource:t.videoSource,audioSource:t.audioSource,videoHint:"motion",sourceType:"screen"}),r="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:r.frameRate,bitrate:r.bitrate}),yield e.init(),yield this.publishShareStream(e)}catch(e){return Promise.reject(ToggleShareScreenError(JSON.stringify(e)))}e||(yield this.unpublishShareStream())}))}publishShareStream(e){return __awaiter$1(this,void 0,void 0,(function*(){if(this.shareBrtcClient||this.createShareBrtcClient(),!this.brtcShareSig)return console.error("brtcShareSig为空"),Promise.reject(BrtcShareSigError);{yield this.shareBrtcClient.join(this.roomId,`${this.userId}_screen`,this.brtcShareSig).catch((e=>(error$2("共享屏幕入会失败","","",[JSON.stringify(e),this.brtcShareSig]),Promise.reject(ShareScreenClientJoinedError)))),e.on("video-track-ended",(()=>{this.handleShareStreamEnded()})),yield this.shareBrtcClient.publish(e).catch((t=>(error$2("共享屏幕流推流失败","","",["err =>",JSON.stringify(t)]),e.destroy(),Promise.reject(ShareScreenOtherError("共享屏幕流推流失败,请重试"))))),this.shareBrtcClient.on("sync-room-completed",(()=>{this.fire(BCEvent$2.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));let t=e.getAudioOn(),r=e.getVideoOn();this.shareScreenStream=e,this.createAndPubBloudShareStream(t,r),setTimeout((()=>{Promise.resolve(!0)}),200)}}))}createAndPubBloudShareStream(e,t){return this.bloudShareScreenStream=this.createBloudScreenStream({audio_enable:e,video_enable:t},`${this.userId}_screen`),this.bloudShareScreenStream.publish({video_enable:t,audio_enable:e})}replaceShareStreamVideoTrack(e){this.shareScreenStream?this.shareScreenStream.replaceTrack(e):error$2("当前没有开启共享屏幕,无法替换track")}unpublishShareStream(){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise((e=>__awaiter$1(this,void 0,void 0,(function*(){var t,r;try{yield this.shareBrtcClient.unpublish(this.shareScreenStream).catch((e=>{error$2("取消共享屏幕出错","","",[JSON.stringify(e)])})),yield null===(t=this.shareBrtcClient)||void 0===t?void 0:t.leave().catch((e=>{error$2("shareBrtcClient leave error","","",[JSON.stringify(e)])})),null===(r=this.shareScreenStream)||void 0===r||r.destroy(),this.shareScreenStream=void 0,yield this.bloudShareScreenStream.unpublish().then((()=>{this.bloudShareScreenStream=void 0})).catch((e=>{error$2("bloud share stream unpublish failed"),this.handleBloudSharePubFailed()}))}catch(e){console.log("取消共享兼容处理",e)}e(!0)}))))}))}setShareScreenContentHint(e){this.shareContentHint=e}releaseRoom(){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.release()}))}handleShareStreamEnded(){setTimeout((()=>{var e;this.shareScreenStream&&"live"===(null===(e=this.shareScreenStream.getVideoTrack())||void 0===e?void 0:e.readyState)||(error$2("share stream video track ended"),this.fire("toggle-screen-share",!1))}),2e3)}setCustomUrl(e){BRTC$2.exports.setCustomUrl(e)}bloudReconnect(){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.leave(),yield SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))}))}searchUsers(e,t,r){return __awaiter$1(this,void 0,void 0,(function*(){const{participants:i}=yield this.client.searchUsers(e,t,r);let n=new Map;return i.forEach((e=>{let t=BCUser.toUser(e,this.type);n.set(t.userId,t)})),{users:n}}))}queryUsers(e){return __awaiter$1(this,void 0,void 0,(function*(){const{participants:t}=yield this.client.queryUsers(e);let r=new Map;return t.forEach((e=>{let t=BCUser.toUser(e,this.type);r.set(t.userId,t)})),{users:r}}))}handleBloudRejoin(){return __awaiter$1(this,void 0,void 0,(function*(){return SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))}))}}const PLAYER_STATE_CHANGED="player-state-changed";class Player extends Emitter{constructor(e,t){super(),this.playEvent=()=>{this.videoStatus="PLAYING",info$1("stream big video playing",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.pauseEvent=()=>{this.videoStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"video",state:this.videoStatus,reason:"pause"}]),info$1("stream big video pause",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.stalledEvent=()=>{this.videoStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"video",state:this.videoStatus,reason:"stalled"}]),info$1("stream big video stalled",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.element=e,this.options=t,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor="#202020",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!this.video){if(!this.stream.getVideoTrack())return;this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.video.style.objectFit=this.options.fit,this.video.id=`video_${this.stream.getStreamId()}_big`,this.container.appendChild(this.video),this.video.addEventListener("playing",this.playEvent),this.video.addEventListener("pause",this.pauseEvent),this.video.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e,this.videoStatus="STOPPED"}play(e){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e,this.container.id=`player_${e.getStreamId()}_big_container`,this.stream.hasVideo()&&this.playVideo();try{this.video&&(yield this.video.play())}catch(e){error$2("big player play video failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e;try{this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasVideo()&&t&&(yield this.video.play())}catch(e){error$2("big player replay video failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}destroy(){this.video&&(this.video.removeEventListener("playing",this.playEvent),this.video.removeEventListener("pause",this.pauseEvent),this.video.removeEventListener("stalled",this.stalledEvent),this.video.style.display="none",this.video=null);try{this.container.style.display="none",this.element.removeChild(this.container)}catch(e){}this.container=null,debug$1("stream player destroy",LOGGER_TAG_PLAYER,this.stream.getUserId())}resume(){return __awaiter$1(this,void 0,void 0,(function*(){this.video&&(yield this.video.play()),debug$1("stream player resume",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){const e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}}function func$3(e){return typeof e===RAW_FUNCTION$2}class AudioPlayer extends Emitter{constructor(e,t){super(),this.audioLevel=1,this.playEvent=()=>{this.audioStatus="PLAYING",info$1("stream audio playing",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.pauseEvent=()=>{this.audioStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"pause"}]),info$1("stream audio pause",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.stalledEvent=()=>{this.audioStatus="PAUSED",this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"stalled"}]),info$1("stream audio stalled",LOGGER_TAG_PLAYER,this.stream.getUserId())},this.element=e,this.options=t}get streamId(){return this.stream.getStreamId()}playAudio(){if(!this.audio){if(!this.stream.getAudioTrack())return;this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id=`audio_${this.stream.getStreamId()}_back`,this.element.appendChild(this.audio),this.stream.getAudioDeviceId()&&this.setSinkId(this.stream.getAudioDeviceId()),this.audio.volume=this.audioLevel,this.audio.addEventListener("playing",this.playEvent),this.audio.addEventListener("pause",this.pauseEvent),this.audio.addEventListener("stalled",this.stalledEvent)}let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e,this.audioStatus="STOPPED"}setSinkId(e){return __awaiter$1(this,void 0,void 0,(function*(){this.audio&&func$3(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audioLevel=e,this.audio.volume=e)}play(e){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e,this.stream.hasAudio()&&this.playAudio();try{this.audio&&(yield this.audio.play())}catch(e){error$2("player play audio failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}}))}replay(e,t=!0,r=!0){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e;try{this.stream.hasAudio()&&r&&this.playAudio(),this.stream.hasAudio()&&r&&(yield this.audio.play())}catch(e){error$2("player replay audio failed","","",[JSON.stringify(e)]),this.fire(PLAYER_STATE_CHANGED,[{type:"error",reason:e}])}debug$1("audio stream replay",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){var e,t,r;null===(e=this.audio)||void 0===e||e.removeEventListener("playing",this.playEvent),null===(t=this.audio)||void 0===t||t.removeEventListener("pause",this.pauseEvent),null===(r=this.audio)||void 0===r||r.removeEventListener("stalled",this.stalledEvent);try{this.element.removeChild(this.audio)}catch(e){}this.audio=null,debug$1("stream player destroy",LOGGER_TAG_PLAYER,this.stream.getUserId())}resume(){return __awaiter$1(this,void 0,void 0,(function*(){this.audio?(yield this.audio.play(),info$1("stream player resume",LOGGER_TAG_PLAYER,this.stream.getUserId())):error$2("try resume audio play, but, audio not exits",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}}const enumAudioInputDevices=BRTC$2.exports.enumAudioInputDevices,enumAudioOutputDevices=BRTC$2.exports.enumAudioOutputDevices,enumVideoDevices=BRTC$2.exports.enumVideoDevices,getPermissions=BRTC$2.exports.getPermissions,checkSystemSupport=BRTC$2.exports.checkSystemSupport,createStream=BRTC$2.exports.createStream;class BoomError$1 extends Error{constructor(e,t,r,i){super(),this.code=e,this.error=r,this.BoomErrorFlag=!0,this.eName=i,this.message=t}static instanceOf(e){return!(!e||!e.BoomErrorFlag)}getCode(){return this.code}}const LOCAL_ERROR=1e3,INVALID_PARAMETER=1001,INVALID_OPERATION=1002,CLIENT_BANNED=4005,USER_NOT_EXIT=9001,DEBUG=1,WARN=3,EMPTY_FUNCTION=function(){};function formatLog$1(e,t,r,i){let n=[];return r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function info(e,t,r,i=[]){i.unshift(formatLog$1("INFO",e,t,r)),console.log(...i)}function warn(e,t,r,i=[]){i.unshift(formatLog$1("WARN",e,t,r)),console.log(...i)}function error$1(e,t,r,i=[]){i.unshift(formatLog$1("ERROR",e,t,r)),console.log(...i)}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}/BRTC/.test(EMPTY_FUNCTION.toString());var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,r,i,n;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=__values(s),a=o.next();!a.done;a=o.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(isFunction(c))try{c()}catch(e){n=e instanceof UnsubscriptionError?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var d=__values(u),l=d.next();!l.done;l=d.next()){var h=l.value;try{execFinalizer(h)}catch(e){n=null!=n?n:[],e instanceof UnsubscriptionError?n=__spreadArray(__spreadArray([],__read(n)),__read(e.errors)):n.push(e)}}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}}if(n)throw new UnsubscriptionError(n)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&arrRemove(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),EMPTY_SUBSCRIPTION=Subscription.EMPTY;function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}var config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},timeoutProvider={setTimeout:function(e,t){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var n=timeoutProvider.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,__spreadArray([e,t],__read(r))):setTimeout.apply(void 0,__spreadArray([e,t],__read(r)))},clearTimeout:function(e){var t=timeoutProvider.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}var context=null;function errorContext(e){if(config.useDeprecatedSynchronousErrorHandling){var t=!context;if(t&&(context={errorThrown:!1,error:null}),e(),t){var r=context,i=r.errorThrown,n=r.error;if(context=null,i)throw n}}else e()}var Subscriber=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,isSubscription(t)&&t.add(r)):r.destination=EMPTY_OBSERVER,r}return __extends(t,e),t.create=function(e,t,r){return new SafeSubscriber(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),_bind=Function.prototype.bind;function bind(e,t){return _bind.call(e,t)}var ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,r,i){var n,s,o=e.call(this)||this;isFunction(t)||!t?n={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=i?i:void 0}:o&&config.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},n={next:t.next&&bind(t.next,s),error:t.error&&bind(t.error,s),complete:t.complete&&bind(t.complete,s)}):n=t;return o.destination=new ConsumerObserver(n),o}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var i=this,n=isSubscriber(e)?e:new SafeSubscriber(e,t,r);return errorContext((function(){var e=i,t=e.operator,r=e.source;n.add(t?t.call(n,r):r?i._subscribe(n):i._trySubscribe(n))})),n},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=getPromiseCtor(t))((function(t,i){var n=new SafeSubscriber({next:function(t){try{e(t)}catch(e){i(e),n.unsubscribe()}},error:i,complete:t});r.subscribe(n)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,r){var i;t.subscribe((function(e){return i=e}),(function(e){return r(e)}),(function(){return e(i)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}var ObjectUnsubscribedError=createErrorClass((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),Subject=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return __extends(t,e),t.prototype.lift=function(e){var t=new AnonymousSubject(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new ObjectUnsubscribedError},t.prototype.next=function(e){var t=this;errorContext((function(){var r,i;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var n=__values(t.currentObservers),s=n.next();!s.done;s=n.next()){s.value.next(e)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}}))},t.prototype.error=function(e){var t=this;errorContext((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}}))},t.prototype.complete=function(){var e=this;errorContext((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,i=r.hasError,n=r.isStopped,s=r.observers;return i||n?EMPTY_SUBSCRIPTION:(this.currentObservers=null,s.push(e),new Subscription((function(){t.currentObservers=null,arrRemove(s,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,i=t.thrownError,n=t.isStopped;r?e.error(i):n&&e.complete()},t.prototype.asObservable=function(){var e=new Observable;return e.source=this,e},t.create=function(e,t){return new AnonymousSubject(e,t)},t}(Observable),AnonymousSubject=function(e){function t(t,r){var i=e.call(this)||this;return i.destination=t,i.source=r,i}return __extends(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:EMPTY_SUBSCRIPTION},t}(Subject),BehaviorSubject=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return __extends(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,i=e._value;if(t)throw r;return this._throwIfClosed(),i},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Subject);Object.freeze({}),Object.freeze([]);const LOGGER_TAG_CLIENT="c";var MODEL_SORT_ENUM_STAND,MODEL_SORT_ENUM_ZY,STREAM_TYPE;!function(e){e[e.SCREEN_MASTER=0]="SCREEN_MASTER",e[e.SCREEN_MANAGER_AUDIO_VIDEO=1]="SCREEN_MANAGER_AUDIO_VIDEO",e[e.SCREEN_MANAGER_AUDIO=2]="SCREEN_MANAGER_AUDIO",e[e.SCREEN_MANAGER_VIDEO=3]="SCREEN_MANAGER_VIDEO",e[e.SCREEN_MANAGER=4]="SCREEN_MANAGER",e[e.SCREEN_GUEST_AUDIO_VIDEO=5]="SCREEN_GUEST_AUDIO_VIDEO",e[e.SCREEN_GUEST_AUDIO=6]="SCREEN_GUEST_AUDIO",e[e.SCREEN_GUEST_VIDEO=7]="SCREEN_GUEST_VIDEO",e[e.SCREEN_GUEST=8]="SCREEN_GUEST",e[e.SCREEN_COMMONUSER_AUDIO_VIDEO=9]="SCREEN_COMMONUSER_AUDIO_VIDEO",e[e.SCREEN_COMMONUSER_AUDIO=10]="SCREEN_COMMONUSER_AUDIO",e[e.SCREEN_COMMONUSER_VIDEO=11]="SCREEN_COMMONUSER_VIDEO",e[e.SCREEN_OTHER=12]="SCREEN_OTHER",e[e.MASTER=13]="MASTER",e[e.LOCAL=14]="LOCAL",e[e.MANAGER_AUDIO_VIDEO=15]="MANAGER_AUDIO_VIDEO",e[e.MANAGER_AUDIO=16]="MANAGER_AUDIO",e[e.MANAGER_VIDEO=17]="MANAGER_VIDEO",e[e.MANAGER=18]="MANAGER",e[e.RAISE_HAND=19]="RAISE_HAND",e[e.RAISE_AUDIO=20]="RAISE_AUDIO",e[e.RAISE_VIDEO=21]="RAISE_VIDEO",e[e.GUEST_AUDIO_VIDEO=22]="GUEST_AUDIO_VIDEO",e[e.GUEST_AUDIO=23]="GUEST_AUDIO",e[e.GUEST_VIDEO=24]="GUEST_VIDEO",e[e.GUEST=25]="GUEST",e[e.SIGNAL=26]="SIGNAL",e[e.COMMONUSER_AUDIO_VIDEO=27]="COMMONUSER_AUDIO_VIDEO",e[e.COMMONUSER_AUDIO=28]="COMMONUSER_AUDIO",e[e.COMMONUSER_VIDEO=29]="COMMONUSER_VIDEO",e[e.OTHER=30]="OTHER"}(MODEL_SORT_ENUM_STAND||(MODEL_SORT_ENUM_STAND={})),function(e){e[e.SCREEN=0]="SCREEN",e[e.RAISE_AUDIO=1]="RAISE_AUDIO",e[e.RAISE_VIDEO=2]="RAISE_VIDEO",e[e.LOCAL=3]="LOCAL",e[e.MASTER_AUDIO_VIDEO=4]="MASTER_AUDIO_VIDEO",e[e.MANAGER_AUDIO_VIDEO=5]="MANAGER_AUDIO_VIDEO",e[e.AUDIO_VIDEO=6]="AUDIO_VIDEO",e[e.MASTER_AUDIO=7]="MASTER_AUDIO",e[e.MANAGER_AUDIO=8]="MANAGER_AUDIO",e[e.AUDIO=9]="AUDIO",e[e.MASTER_VIDEO=10]="MASTER_VIDEO",e[e.MANAGER_VIDEO=11]="MANAGER_VIDEO",e[e.VIDEO=12]="VIDEO",e[e.MASTER=13]="MASTER",e[e.MANAGER=14]="MANAGER",e[e.GUEST=15]="GUEST",e[e.COMMON_USER=16]="COMMON_USER",e[e.SIGNAL=17]="SIGNAL",e[e.OTHER=18]="OTHER"}(MODEL_SORT_ENUM_ZY||(MODEL_SORT_ENUM_ZY={})),function(e){e[e.SUB_MAIN=0]="SUB_MAIN",e[e.SINGLE=1]="SINGLE",e[e.SHARE=2]="SHARE",e[e.OTHER=3]="OTHER"}(STREAM_TYPE||(STREAM_TYPE={}));const STREAM_SUFFIX_SCREEN="_screen",MOBILE_STREAM_SUFFIX_SCREEN="screen-",SIGNAL_SUFFIX="xinhao_",RECEIVE_SUBSCRIBE_MESSAGE="sub-message",USER_SORT_NUM_CHANGE="user-sort-num-change",BIND_ELEMENT="bind-element",HANDLE_STREAM_CONNECT_ERROR="stream-connect-error",RAISE_HAND="raise-hand",MANUAL_SUBSCRIPTION="manual-subscription",UNSUBSCRIBE_STREAM="unsubscribe-stream",CHANG_IS_GUEST="change-is-guest",BIND_BIG_ELEMENT="bind-big-element",NO_CONTAINER="no-container",MODEL_SORT_NUM_CHANGE="model-sort-num-change",ADD_PULL_USER="add-pull-user",SET_VOLUME="set-volume",ADD_AUDIO_PLAY="add-audio-play";function mitt(e){return{all:e=e||new Map,on:function(t,r){var i=e.get(t);i?i.push(r):e.set(t,[r])},off:function(t,r){var i=e.get(t);i&&(r?i.splice(i.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var i=e.get(t);i&&i.slice().map((function(e){e(r)})),(i=e.get("*"))&&i.slice().map((function(e){e(t,r)}))}}}class BoomEmitter{static getInstance(){return BoomEmitter.emitter||(BoomEmitter.emitter=mitt()),BoomEmitter.emitter}}function getSortNum(e){return 2===_selfSortType?sortZY(e):sortStand(e)}function sortStand(e){let t=MODEL_SORT_ENUM_STAND.OTHER;return e.isSharing?(t=e.isMaster?MODEL_SORT_ENUM_STAND.SCREEN_MASTER:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO_VIDEO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_AUDIO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER_VIDEO:e.isManager?MODEL_SORT_ENUM_STAND.SCREEN_MANAGER:e.isCommonUser?e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_OTHER:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.SCREEN_GUEST_VIDEO:MODEL_SORT_ENUM_STAND.SCREEN_GUEST,t):(e.isMaster?t=MODEL_SORT_ENUM_STAND.MASTER:e.isLocal?t=MODEL_SORT_ENUM_STAND.LOCAL:e.isManager?t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_VIDEO:MODEL_SORT_ENUM_STAND.MANAGER:e.raiseHand?t=MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?t=MODEL_SORT_ENUM_STAND.RAISE_AUDIO:e.raiseVideoHands?t=MODEL_SORT_ENUM_STAND.RAISE_VIDEO:e.isCommonUser?e.isSignal?t=MODEL_SORT_ENUM_STAND.SIGNAL:e.isCommonUser&&(t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_VIDEO:MODEL_SORT_ENUM_STAND.OTHER):t=e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO_VIDEO:e.audioEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO:e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_VIDEO:MODEL_SORT_ENUM_STAND.GUEST,t)}function sortZY(e){let t;return t=e.isToupingma?MODEL_SORT_ENUM_ZY.SCREEN:e.raiseHand?MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?MODEL_SORT_ENUM_ZY.RAISE_AUDIO:e.raiseVideoHands?MODEL_SORT_ENUM_ZY.RAISE_VIDEO:e.isLocal?MODEL_SORT_ENUM_ZY.LOCAL:e.isMaster&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO_VIDEO:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO_VIDEO:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.AUDIO_VIDEO:e.isMaster&&e.audioEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO:e.audioEnable?MODEL_SORT_ENUM_ZY.AUDIO:e.isMaster&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_VIDEO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_VIDEO:e.videoEnable?MODEL_SORT_ENUM_ZY.VIDEO:e.isMaster?MODEL_SORT_ENUM_ZY.MASTER:e.isManager?MODEL_SORT_ENUM_ZY.MANAGER:e.isCommonUser?MODEL_SORT_ENUM_ZY.COMMON_USER:e.isSignal?MODEL_SORT_ENUM_ZY.SIGNAL:MODEL_SORT_ENUM_ZY.GUEST,t}BoomEmitter.emitter=void 0,BoomEmitter.removeEmitter=()=>{var e,t,r,i,n,s,o,a,c,u,d,l,h,m;null===(e=BoomEmitter.emitter)||void 0===e||e.off(RECEIVE_SUBSCRIBE_MESSAGE),null===(t=BoomEmitter.emitter)||void 0===t||t.off(USER_SORT_NUM_CHANGE),null===(r=BoomEmitter.emitter)||void 0===r||r.off(HANDLE_STREAM_CONNECT_ERROR),null===(i=BoomEmitter.emitter)||void 0===i||i.off(RAISE_HAND),null===(n=BoomEmitter.emitter)||void 0===n||n.off(UNSUBSCRIBE_STREAM),null===(s=BoomEmitter.emitter)||void 0===s||s.off(MANUAL_SUBSCRIPTION),null===(o=BoomEmitter.emitter)||void 0===o||o.off(CHANG_IS_GUEST),null===(a=BoomEmitter.emitter)||void 0===a||a.off(BIND_ELEMENT),null===(c=BoomEmitter.emitter)||void 0===c||c.off(BIND_BIG_ELEMENT),null===(u=BoomEmitter.emitter)||void 0===u||u.off(NO_CONTAINER),null===(d=BoomEmitter.emitter)||void 0===d||d.off(MODEL_SORT_NUM_CHANGE),null===(l=BoomEmitter.emitter)||void 0===l||l.off(ADD_PULL_USER),null===(h=BoomEmitter.emitter)||void 0===h||h.off(SET_VOLUME),null===(m=BoomEmitter.emitter)||void 0===m||m.off(ADD_AUDIO_PLAY),BoomEmitter.emitter=void 0};class BMUser{constructor(e,t=!1){var r;this.streamModels=new Map,this.sortNum=100,this.raiseVideoHands=!1,this.raiseAudioHands=!1,this.raiseHand=!1,this.isAudience=!1,this.isCommonUser=!1,this.inBackground=!1,this.raiseHandTime=0,this.userId=e.userId,this.userInfo=e.userInfo,this.nickName=e.nickname,this.isMaster=!!e.isMaster,this.isManager=!!e.isManager,this.isToupingma=!!e.isToupingma,this.isLocal=t,this.hasMultiple=!!e.hasMultiple,this.isCreate=!!e.isCreate,this.hasShare=!!e.hasShare,this.avatar=null===(r=e.userInfo)||void 0===r?void 0:r.avatar,this.permission=e.permission,this.raiseAudioHands=!!e.raiseAudioHands,this.raiseVideoHands=!!e.raiseVideoHands,this.raiseHand=!!e.raiseHand,this.isAudience=!!e.isAudience,this.isCommonUser=!!e.isCommonUser,this.inBackground=!!e.inBackground,this.audienceEnableSpeaking=!!e.audienceEnableSpeaking,this.raiseHandTime=e.raiseHandTime||0;const i={operation:"none",user:this};this.watcher=new BehaviorSubject(i),this.updateSortNum(!1)}get isWeb(){return!(!this.userInfo.pos||!this.userInfo.pos.includes("web")&&!this.userInfo.pos.includes("pc"))}setup(e,t,r){this.isLocal=!0,this.userId=e,this.userInfo=t,this.nickName=r||t.nickname,this.avatar=t.avatar}getMainStreamModel(){return this.streamModels.get(this.userId)}get nickname(){return this.nickName}getShareStreamModel(){return this.streamModels.get(`${this.userId}${STREAM_SUFFIX_SCREEN}`)}get audioEnable(){const e=this.getMainStreamModel();return!!e&&e._audio_enable}get isMixer(){return this.userId.includes("-mixer-")}get videoEnable(){const e=this.getMainStreamModel();return!!e&&e._video_enable}get isSharing(){let e=!1;for(let t of this.streamModels.values())if(t.isShare){e=!0;break}return e}get isSignal(){var e;return!!(null===(e=this.userId)||void 0===e?void 0:e.startsWith(SIGNAL_SUFFIX))}checkLocalHasMaster(){return this.isMaster||this.isManager}addStream(e,t){this.streamModels.set(e,t),this.watcher.next({operation:"changeShare",user:this})}removeStream(e){this.streamModels.delete(e),e.includes(STREAM_SUFFIX_SCREEN)&&info("删除的是共享屏幕的流:","","",["streamId =>",e]),setTimeout((()=>{this.watcher.next({operation:"changeShare",user:this})}),400)}getID(){return this.userId}getNickName(){return this.nickName}getUserInfo(){return this.userInfo}getStreams(){return this.streamModels}updateUserInfo(e,t={},r){var i,n,s,o,a,c;const u=null===(i=null==t?void 0:t.params)||void 0===i?void 0:i.customInfo,d=(null==u?void 0:u.updateKeys)||[];let l=!1,h="none";if(info("updateUserInfo =>","updateUser",e.userId,["updateKeys",d.toString(),"permission",null===(n=e.permission)||void 0===n?void 0:n.permission,"isMaster =>",this.isMaster,"isManager =>",this.isManager]),this.nickName!==e.nickname&&(h="changeNickName"),this.isMaster||!this.isManager||e.permission.getManage()||(h="removeManager",this.isManager=!1),this.isMaster||this.isManager||!e.permission.getManage()||-1!=d.indexOf("changeMaster")||(h="getManager",this.isManager=!0),e.userinfo.pos)this.userInfo=e.userinfo;else{const t=this.userInfo.pos;this.userInfo=e.userinfo,this.userInfo.pos=t}(d.includes("changeMaster")||d.includes("permission"))&&(e.permission=t.getPermission()),d.includes("raiseHandsAudio")&&(this.raiseAudioHands=u.raiseHandsAudio,h="raiseHandsAudio",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsAudio",user:this}),l=!0),d.includes("raiseHandsVideo")&&(this.raiseVideoHands=u.raiseHandsVideo,h="raiseHandsVideo",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsVideo",user:this}),l=!0),d.includes("raiseHand")&&(this.raiseHand=u.raiseHand,this.raiseHandTime=u.raiseHandTime,h="raiseHand",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHand",user:this}),l=!0),1!==r.conferenceMode&&this.isAudience&&d.includes("permission")&&(-1!==(null===(o=null===(s=t.params)||void 0===s?void 0:s.customInfo)||void 0===o?void 0:o.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!0),this.audienceEnableSpeaking=!0,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceEnable()),-1===(null===(c=null===(a=t.params)||void 0===a?void 0:a.customInfo)||void 0===c?void 0:c.permission.indexOf("A"))&&(r.enableAudienceSpeakingWatcher.next(!1),this.audienceEnableSpeaking=!1,h="audienceEnableSpeaking",r.bmLiveVM.handleAudienceDisable())),d.includes("inBackground")&&(h="inBackground",this.inBackground=u.inBackground),this.nickName=e.nickname,this.permission=e.permission;let m=!this.isCommonUser;this.isCommonUser=!e.permission.getSubscribe(),m!==!this.isCommonUser&&(info(`身份有发生过变化,从${m?"嘉宾":"普通参会者"} => ${this.isCommonUser?"普通参会者":"嘉宾"}`),BoomEmitter.emitter.emit(CHANG_IS_GUEST,{user:this,isGuest:!this.isCommonUser,preIsGuest:m})),h&&this.watcher.next({operation:h,user:this}),(!l||l&&!this.isLocal)&&this.updateSortNum(!0)}hasManager(){return this.isManager||this.isMaster}getNicknameSuffix(){let e="";return this.isLocal&&this.isMaster?e="(我、主持人)":this.isLocal&&this.isManager?e="(我、联席主持人)":this.isLocal?e="(我)":this.isMaster?e="(主持人)":this.isManager?e="(联席主持人)":this.isSharing&&!this.isToupingma?e="的共享屏幕":this.isSharing&&this.isToupingma&&(e="(仅共享屏幕)"),e}updateSortNum(e=!0,t=!1){let r=getSortNum(this);this.setSortNum(r,e,t)}setSortNum(e,t,r){this.sortNum!==e&&(this.sortNum=e,t&&BoomEmitter.emitter.emit(USER_SORT_NUM_CHANGE,{isCommon:this.isCommonUser,shouldDelay:r}))}}const NULL=null,UNDEFINED=void 0,RAW_FUNCTION="function";Object.freeze({}),Object.freeze([]);const EMPTY_STRING="";function func(e){return typeof e===RAW_FUNCTION}function indexOf(e,t,r){return e.indexOf(t,r!==UNDEFINED?r:0)}function has(e,t){return indexOf(e,t)>=0}function toString(e,t){return e!=NULL&&e.toString?e.toString():t!==UNDEFINED?t:EMPTY_STRING}function isNative(e){return func(e)&&has(toString(e),"[native code]")}typeof setImmediate===RAW_FUNCTION&&isNative(setImmediate)&&setImmediate,typeof MessageChannel===RAW_FUNCTION&&isNative(MessageChannel);const notGetTalkInterval=3e5;function handleTime(e){let t=new Date(e),r=new Date,i=t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,n=t.getDate()<10?"0"+t.getDate():t.getDate(),s=t.getHours()<10?"0"+t.getHours():t.getHours(),o=t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes();return r.setHours(0,0,0,0)==t.setHours(0,0,0,0)?s+":"+o:i+"月"+n+"日 "+s+":"+o}function sortUsers(e){return e.sort(((e,t)=>e.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND&&t.sortNum===MODEL_SORT_ENUM_STAND.RAISE_HAND?e.raiseHandTime-t.raiseHandTime:e.sortNum-t.sortNum))}function sortStreamModels(e){return e.sort(((e,t)=>e.sortNum!==t.sortNum?t.sortNum-e.sortNum:Number(e.getUser().isCommonUser)-Number(t.getUser().isCommonUser)))}function getIsCommonUser(e){return!getPermission(e,"s")}function getIsManager(e){return getPermission(e,"m")}function getIsMaster(e){return getPermission(e,"o")}function getPermission(e,t){return e.toLowerCase().includes(t)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}var freeGlobal="object"==typeof global$3&&global$3&&global$3.Object===Object&&global$3,freeGlobal$1=freeGlobal,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal$1||freeSelf||Function("return this")(),root$1=root,Symbol$1=root$1.Symbol,Symbol$2=Symbol$1,objectProto$1=Object.prototype,hasOwnProperty=objectProto$1.hasOwnProperty,nativeObjectToString$1=objectProto$1.toString,symToStringTag$1=Symbol$2?Symbol$2.toStringTag:void 0;function getRawTag(e){var t=hasOwnProperty.call(e,symToStringTag$1),r=e[symToStringTag$1];try{e[symToStringTag$1]=void 0;var i=!0}catch(e){}var n=nativeObjectToString$1.call(e);return i&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),n}var objectProto=Object.prototype,nativeObjectToString=objectProto.toString;function objectToString(e){return nativeObjectToString.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$2?Symbol$2.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag}var reWhitespace=/\s/;function trimmedEndIndex(e){for(var t=e.length;t--&&reWhitespace.test(e.charAt(t)););return t}var reTrimStart=/^\s+/;function baseTrim(e){return e?e.slice(0,trimmedEndIndex(e)+1).replace(reTrimStart,""):e}function isObject(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var NAN=NaN,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;function toNumber(e){if("number"==typeof e)return e;if(isSymbol(e))return NAN;if(isObject(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=isObject(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=baseTrim(e);var r=reIsBinary.test(e);return r||reIsOctal.test(e)?freeParseInt(e.slice(2),r?2:8):reIsBadHex.test(e)?NAN:+e}var now=function(){return root$1.Date.now()},now$1=now,FUNC_ERROR_TEXT="Expected a function",nativeMax=Math.max,nativeMin=Math.min;function debounce(e,t,r){var i,n,s,o,a,c,u=0,d=!1,l=!1,h=!0;if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT);function m(t){var r=i,s=n;return i=n=void 0,u=t,o=e.apply(s,r)}function p(e){return u=e,a=setTimeout(g,t),d?m(e):o}function f(e){var r=e-c;return void 0===c||r>=t||r<0||l&&e-u>=s}function g(){var e=now$1();if(f(e))return v(e);a=setTimeout(g,function(e){var r=t-(e-c);return l?nativeMin(r,s-(e-u)):r}(e))}function v(e){return a=void 0,h&&i?m(e):(i=n=void 0,o)}function _(){var e=now$1(),r=f(e);if(i=arguments,n=this,c=e,r){if(void 0===a)return p(c);if(l)return clearTimeout(a),a=setTimeout(g,t),m(c)}return void 0===a&&(a=setTimeout(g,t)),o}return t=toNumber(t)||0,isObject(r)&&(d=!!r.leading,s=(l="maxWait"in r)?nativeMax(toNumber(r.maxWait)||0,t):s,h="trailing"in r?!!r.trailing:h),_.cancel=function(){void 0!==a&&clearTimeout(a),u=0,i=c=n=a=void 0},_.flush=function(){return void 0===a?o:v(now$1())},_}var numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}const ignoreUserId=["-mixer-","-rtmpmixer-","record#","robot_","stt_"],BLOUD_PAGE_SIZE=500,PERMISSION_NOT_COMMON="RWPSAVMO,RWPSAVM,RWPSAV";class BMUserVM{constructor(e,t,r){this.userList=new Map,this.audiencesList=new Map,this.signalList=new Map,this.commonUserList=new Map,this.userListWatcher=new BehaviorSubject(Array.from(this.userList.values())),this.audiencesListWatcher=new BehaviorSubject(Array.from(this.audiencesList.values())),this.commonUserListWatcher=new BehaviorSubject(Array.from(this.commonUserList.values())),this.signalListWatcher=new BehaviorSubject(Array.from(this.signalList.values())),this.masterUserWatcher=new BehaviorSubject(null),this.getForceUserWatcher=new BehaviorSubject(!1),this.commTimer=200,this.addBCUser=(e,t=!1)=>{var r;const i=this.addUser(e);if(!this.room.bmStreamVm.streamModels.get(e.userId)){const t=this.getUser(e.userId);t?this.room.bmStreamVm.createStreamModel(t):error$1(`there is no user named ${e.userId}, and create streamModel failed!!!`)}{const i=this.room.bmStreamVm.streamModels.get(e.userId);i&&(e.stream.size?e.stream.forEach((r=>__awaiter$2(this,void 0,void 0,(function*(){var n,s;const{video_enable:o,audio_enable:a,customInfo:c}=r;if(r.screen){this.room.bmStreamVm.shareBloudStateMap.set(e.userId,{audio:a,video:o,customInfo:c,userId:e.userId,streamId:r.getID(),isScreen:!0});const u={id:i.userId,isScreen:!0,isWeb:i.isWeb};if(t){const t=new Map;t.set(e.userId,u),yield null===(n=this.room)||void 0===n?void 0:n.processUser(t)}else null===(s=this.room)||void 0===s||s.addUser2Queue(u)}else i&&i.updateBloudStream({video:o,audio:a,isScreen:r.screen,customInfo:c},this.room.bmStreamVm)})))):(i.bloudStream&&i.updateBloudStream(void 0,this.room.bmStreamVm),null===(r=this.room)||void 0===r||r.bmStreamVm.removeShareStreamModelByUId(e.userId)))}return i&&i.isMaster&&this.masterUserWatcher.next(i),null==i||i.updateSortNum(!1),i},this.updateAllSort=()=>{this.updateUserSort(),this.updateCommonUserSort()},this.updateSortByType=e=>{var t,r;(null===(t=this.room)||void 0===t?void 0:t.isSingleColumns)||e.isCommon?(null===(r=this.room)||void 0===r?void 0:r.isBig)&&e.shouldDelay?this.updateDelayCommonUserSort():this.updateCommonUserSort():this.updateUserSort()},this.updateUserSort=debounce((()=>{const e=this.sortUsers();this.userListWatcher.next(BMUserVM.filterUsers(e))}),200,{maxWait:1e3}),this.updateCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),this.commTimer,{maxWait:12e3}),this.updateDelayCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),12e4,{maxWait:12e4}),this.updateAudienceUserSort=()=>{const e=this.sortAudiences();this.audiencesListWatcher.next(BMUserVM.filterUsers(e))},this.updateSignalUserSort=()=>{const e=this.sortSignalUsers();this.signalListWatcher.next(e)},this.transBloudUsers=(e,t="",r=!1,i=0)=>__awaiter$2(this,void 0,void 0,(function*(){const n=new Map;yield this.getAllUsers(e,n,t,r).catch((()=>i<3?(error$1("get bloud user error, retry"),i+=1,void this.transBloudUsers(e,t,r,i)):void error$1("get current page of bloud users after 10 times final failed","","",[" page ",e," permission ",t]))),yield this.initUserList(n),n.clear();let s=[];for(let e of this.userList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands)&&s.push(e);this.room.roomInfo.setRaiseHandsList(s),this.updateAllSort(),this.room.bmStreamVm.updateModelSort()})),this.boomCore=e,this.localUser=t,this.room=r,BoomEmitter.emitter||error$1("init boom emitter error"),BoomEmitter.emitter.on(CHANG_IS_GUEST,this.handleUserRoleChange.bind(this)),BoomEmitter.emitter.on(USER_SORT_NUM_CHANGE,this.updateSortByType)}handleUserRoleChange(e){var t,r,i;return __awaiter$2(this,void 0,void 0,(function*(){const{user:n,isGuest:s,preIsGuest:o}=e,a=null===(t=this.room)||void 0===t?void 0:t.roomInfo.isBigRoom;info("handleUserRoleChange","",n.userId,["isGuest =>",s,"preIsGuest =>",o,"isBigRoom =>",a]);if(1===(null===(r=this.room)||void 0===r?void 0:r.userListColumns)||(o?this.userList.delete(n.userId):this.commonUserList.delete(n.userId),s?this.userList.set(n.userId,n):this.commonUserList.set(n.userId,n)),a)if(s)n.isLocal&&(yield this.initUsers());else{const e=null===(i=this.room)||void 0===i?void 0:i.getLocalParticipant().isCommonUser;if(n.isLocal&&(this.handleUnSubCommonUser(),this.handleCommonUserChange(),this.commonUserList.set(n.userId,n)),e){const e=n.getMainStreamModel();e&&e.unSubscribeStream(),n.isLocal||this.commonUserList.delete(n.userId)}}this.updateAllSort()}))}addUser(e){var t;const r=this.getUser(e.userId);if(r)return info("该用户已经加入房间",LOGGER_TAG_CLIENT,e.userId),this.updateUser(r,e),null;let i;return this.boomCore.userId==e.userId?(this.updateUser(this.localUser,e),i=this.localUser):i=this.toBMUser(e),1===(null===(t=this.room)||void 0===t?void 0:t.userListColumns)?this.commonUserList.set(i.userId,i):i.isAudience?this.audiencesList.set(i.userId,i):i.isSignal?this.signalList.set(i.userId,i):i.isCommonUser?this.commonUserList.set(i.userId,i):this.userList.set(i.userId,i),i}removeUser(e){let t=this.userList.delete(e);return t||(t=this.signalList.delete(e)),t||(t=this.audiencesList.delete(e)),t||(t=this.commonUserList.delete(e)),t||warn("userList中未找到该用户, 移除无效",LOGGER_TAG_CLIENT,e),t}videoEnable(e){const t=this.getUser(e);if(t)return t.videoEnable;throw new BoomError$1(USER_NOT_EXIT,"用户不存在")}audioEnable(e){const t=this.getUser(e);if(t)return t.audioEnable;throw new BoomError$1(USER_NOT_EXIT,"用户不存在")}checkIsMaster(e){if(!e)return!1;const t=this.boomCore.getMaster();return!!t&&t===e}checkLocalHasMaster(){return this.localUser.isMaster||this.localUser.isManager}checkUserHasMaster(e){const t=this.userList.get(e);return!!t&&t.permission.getManage()}getUser(e){let t;return t=(null==e?void 0:e.startsWith(SIGNAL_SUFFIX))?this.signalList.get(e):this.userList.get(e),t||(t=this.commonUserList.get(e)),t||(t=this.audiencesList.get(e)),t}getAllUsers(e,t,r="",i=!1){return __awaiter$2(this,void 0,void 0,(function*(){let n;if(i){let{users:t,total:i}=yield this.boomCore.getUsersList(e,r,BLOUD_PAGE_SIZE);n=t}else{let{users:t,total:i}=yield this.boomCore.getUsers(e,r,BLOUD_PAGE_SIZE);n=t}n.forEach((e=>{t.set(e.userId,e)}))}))}initUserList(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){const i=e.get(this.localUser.userId);if(i){const e=this.addUser(i);if(!(null===(t=this.room)||void 0===t?void 0:t.bmStreamVm.getStreamModelByUId(i.userId))){const e=this.getUser(i.userId);e?null===(r=this.room)||void 0===r||r.bmStreamVm.createStreamModel(e):error$1("there is no local streamModel exits, and create failed!!!")}(null==e?void 0:e.isMaster)&&this.masterUserWatcher.next(e)}e.delete(this.localUser.userId),e&&e.size>0&&this.addBcUsersMap(e)}))}addBcUsersMap(e,t=!1){e.forEach((e=>{this.addBCUser(e,t)}))}updateMaster(e,t,r){const i=this.getUser(e);i&&(i.isManager&&(i.isManager=!1),i.isMaster=!0,i.updateSortNum());const n=this.getUser(t);return n&&(n.isMaster=!1,r&&(n.isManager=!0),n.updateSortNum()),i||n||error$1("未找到该用户, updateMaster未生效",LOGGER_TAG_CLIENT,e,["masterId => ",e,"oldMasterId => ",t]),{master:i,oldMaster:n}}managerChangeToGuest(e){const t=this.getUser(e);return t?t.isManager?(t.permission.setManage(!1),t.permission.setSubscribe(!0),this.boomCore.updateUser(e,{customInfo:{permission:t.permission.get()}}),t.watcher.next({operation:"getGuest",user:t}),this.updateAllSort()):error$1("该用户不是管理员,无法设置为嘉宾",LOGGER_TAG_CLIENT,e):error$1("未找到该用户, managerChangeToGuest未生效",LOGGER_TAG_CLIENT,e),t}updateManager(e,t,r=!0){const i=this.getUser(e);return i?(i.permission.setManage(t),i.permission.setSubscribe(t),this.boomCore.updateUser(e,{customInfo:{permission:i.permission.get()}}),i.watcher.next({operation:t?"getManager":"removeManager",user:i}),this.updateAllSort()):error$1("userList中未找到该用户, updateManager未生效",LOGGER_TAG_CLIENT,e),i}getLocalUser(){return this.localUser}updateUser(e,t){var r,i,n,s,o;const a=this.checkIsMaster(t.userId),c=((null===(r=t.permission)||void 0===r?void 0:r.getManage())||getIsManager(null===(i=t.permission)||void 0===i?void 0:i.permission))&&!((null===(n=t.permission)||void 0===n?void 0:n.getOwn())||getIsMaster(null===(s=t.permission)||void 0===s?void 0:s.permission));let u="none";const d=e.isMaster;e.isManager!==c&&(u=c?"getManager":"removeManager"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),10),d!==a&&(u=a?"getMaster":"removeMaster"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),100);e.raiseHand!==t.customInfo.raiseHand&&setTimeout((()=>{e.watcher.next({operation:"raiseHand",user:e})}),300);e.nickname!==t.nickname&&setTimeout((()=>{e.watcher.next({operation:"changeNickName",user:e})}),300),e.userInfo=t.userinfo,e.nickName=t.nickname,e.userId=t.userId,e.permission=t.permission,e.avatar=t.userinfo.avatar,e.isToupingma=t.userinfo.pos.includes("_toupingma"),e.isMaster=a,e.isCreate=this.boomCore.getCreator()===t.userId,e.isAudience=!t.permission.getAudio(),e.isCommonUser=!t.permission.getSubscribe(),e.isManager=c,e.inBackground=!!(null===(o=null==t?void 0:t.customInfo)||void 0===o?void 0:o.inBackground),e.updateSortNum()}updateLocalUserPermission(e){const t=this.getLocalUser();t.isMaster=getIsMaster(e),t.isManager=!getIsMaster(e)&&getIsManager(e),t.isCommonUser=getIsCommonUser(e),t.watcher.next({operation:"none",user:t})}toBMUser(e){var t,r;let i={};i.userInfo=e.userinfo,i.nickname=e.nickname,i.userId=e.userId,i.streamModels=[],i.permission=e.permission,i.stream=e.stream,i.isToupingma=!(!e.userinfo.pos||!e.userinfo.pos.includes("_toupingma")),i.isMaster=this.checkIsMaster(i.userId),i.isAudience=!e.permission.getAudio(),i.isCommonUser=!e.permission.getSubscribe()||getIsCommonUser(e.permission.permission),i.raiseAudioHands=e.customInfo.raiseHandsAudio,i.raiseVideoHands=e.customInfo.raiseHandsVideo,i.raiseHand=e.customInfo.raiseHand,i.raiseHandTime=e.customInfo.raiseHandTime,i.inBackground=e.customInfo.inBackground,i.isCreate=this.boomCore.getCreator()===e.userId;let n=this.boomCore.getLocalParticipant();if(!n)throw new BoomError$1(INVALID_PARAMETER,"BCUserVM addUser时未找到本地用户");return n.getID()==i.userId&&(i.isLocal=!0),!(null===(t=i.permission)||void 0===t?void 0:t.getManage())&&!getIsManager(null===(r=i.permission)||void 0===r?void 0:r.permission)||i.isMaster||(i.isManager=!0),new BMUser(i,i.isLocal)}sortUsers(){return sortUsers(Array.from(this.userList.values()))}sortAudiences(){return sortUsers(Array.from(this.audiencesList.values()))}sortCommonUsers(){return sortUsers(Array.from(this.commonUserList.values()))}sortSignalUsers(){return sortUsers(Array.from(this.signalList.values()))}static filterUsers(e){return e.filter((e=>!ignoreUserId.some((t=>e.userId.includes(t)))))}initUsers(){var e;return __awaiter$2(this,void 0,void 0,(function*(){const t=yield this.getTotalUserNumber();info(`initUsers total users num: ${t}`);const r=Math.ceil(t/BLOUD_PAGE_SIZE);let i=0;const n=[],s=e=>__awaiter$2(this,void 0,void 0,(function*(){e<r&&(yield this.transBloudUsers(e-1))})),o=e=>__awaiter$2(this,void 0,void 0,(function*(){for(const t of e)yield t(),yield sleep(50)}));if(this.localUser.isCommonUser&&(null===(e=this.room)||void 0===e?void 0:e.isBig))this.commonUserList.set(this.localUser.userId,this.localUser),yield this.transBloudUsers(-1,PERMISSION_NOT_COMMON,!0);else{for(;i<r;)n.push(s.bind(null,i)),i+=1;o(n)}}))}handleUnSubCommonUser(){this.commonUserList.forEach((e=>{const t=e.getMainStreamModel();(null==t?void 0:t.hasPulled)&&t.unSubscribeStream()}))}handleCommonUserChange(){let e=new Map;this.room.bmStreamVm.streamModels.forEach((t=>{t.getUser().isCommonUser&&!t.isLocal||e.set(t.userId,t)})),this.room.bmStreamVm.streamModels=e,this.commonUserList.clear()}getUsers(e,t,r="RWPAV"){return __awaiter$2(this,void 0,void 0,(function*(){const{users:i,total:n}=yield this.boomCore.getUsers(e,r,t),s=[];return i.forEach((e=>{const t=this.toBMUser(e);s.push(t)})),{userList:s,total:n}}))}getUsersList(e,t,r="",i=!1){var n,s;return __awaiter$2(this,void 0,void 0,(function*(){const{users:o,total:a,pageIndex:c}=yield this.boomCore.getUsersList(e,r,t,i),u=[];return o.forEach((e=>{const t=this.toBMUser(e);u.push(t)})),i&&(null===(n=this.room)||void 0===n?void 0:n.roomInfo.totalWaitRoomUserWatcher.value)!==a&&(null===(s=this.room)||void 0===s||s.roomInfo.totalWaitRoomUserWatcher.next(a)),{userList:u,total:a,pageIndex:c}}))}getTotalUserNumber(){return __awaiter$2(this,void 0,void 0,(function*(){const e=()=>__awaiter$2(this,void 0,void 0,(function*(){const{total:e}=yield this.boomCore.getUsers(0,"",1);return e})),t=r=>{e().then((e=>{r(e)})).catch((e=>{error$1("getTotalUserNumber error","","",[JSON.stringify(e)]),t(r)}))};return new Promise(((e,r)=>__awaiter$2(this,void 0,void 0,(function*(){t(e)}))))}))}clearUsers(){this.userList.clear(),this.commonUserList.clear(),this.audiencesList.clear(),this.signalList.clear()}searchUsers(e,t){return __awaiter$2(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!1);let i=[],n=[];return r.forEach((e=>{const t=this.userList.get(e.userId);if(t)return void i.push(t);const r=this.commonUserList.get(e.userId);r&&n.push(r)})),{userList:i,commonUserList:n}}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"boomCore.searchUsers发生错误:"+(null==e?void 0:e.message)))}}))}searchWaitRoomUsers(e,t){return __awaiter$2(this,void 0,void 0,(function*(){try{const{users:r}=yield this.boomCore.searchUsers(e,t,!0),i=[];return r.forEach((e=>{const t=this.toBMUser(e);i.push(t)})),i}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"search wait room users error"))}}))}}class BMMessageInfo{constructor(e){this.isMeetingNotice=!1,this.userId=e.userId,this.message=e.message,this.role=e.role,this.isLocal=e.isLocal,this.avatar=e.avatar,this.nickName=e.nickName,this.to=e.to,this.isDanger=e.isDanger,this.seq=e.seq,this.failed=e.failed;let t=!1;e.isMeetingNotice&&(t=!0),this.isMeetingNotice=t,e.sendTime?(this.timeStamp=e.sendTime,this.time=handleTime(this.timeStamp)):(this.timeStamp=(new Date).getTime(),this.time=handleTime(this.timeStamp))}}var BCEvent;!function(e){e.ROOM_CONNECTED="room-connected",e.ROOM_RECONNECTING="room-reconnecting",e.ROOM_RECONNECTED="room-reconnected",e.ROOM_SYNC="room-synced",e.JOINUSER="participant-joined",e.LEAVEUSER="participant-left",e.ROOMERROR="room-error",e.UNPUBLISH="participant-unpublished",e.PUBLISHED="participant-published",e.SENDMESSAGE="new-message",e.CUSTOMMESSAGE="custom-message",e.STREAMERROR="error-media",e.STREAMDISCONNECTED="stream-disconnected",e.EVICTED="participant-evicted",e.UPDATESTATS="update-stats",e.CUSTOMSTATS="update-custom-stats",e.UPDATEUSER="participant-update",e.CHANGEMASTER="change-master",e.USERREJOINED="user-rejoined",e.TOKENWILLEXPIRE="token-will-expire",e.TOKENEXPIRE="token-expire",e.ICECANDIDATE="onIceCandidate",e.STREAMUPDATE="stream-update",e.UPDATE="update",e.ANALYSISDATA="analysis-data",e.ANALYSISERROR="analysis-error",e.STARTANALYSIS="start-analyze",e.STOPANALYSIS="stop-analyze",e.REPORTINFO="info-reported",e.STREAM_ADDED="stream-added",e.STREAM_REMOVED="stream-removed",e.STREAM_UPDATED="stream-updated",e.BLOUD_STREAM_UPDATED="bloud-stream-update",e.MOVE_USER_ROOM="move-user-room",e.STREAM_PUBLISHED="stream-published",e.STREAM_SUBSCRIBED="stream-subscribed",e.MUTE_VIDEO="mute-video",e.UNMUTE_VIDEO="unmute-video",e.MUTE_AUDIO="mute-audio",e.UNMUTE_AUDIO="unmute-audio",e.ERROR="error",e.PEER_JOINED="peer-joined",e.PEER_LEAVED="peer-leaved",e.CLIENT_BANNED="client-banned",e.USER_KICKED="user-kicked",e.TOKEN_WILL_EXPIRE="token-will-expire",e.TOKEN_EXPIRE="token-expire",e.ROOM_CLOSED="room-closed",e.NETWORK_ERROR="network-error",e.BRTC_SYNC_ROOM_COMPLETED="sync-room-completed",e.BRTC_ROOM_ROCONNECTING="brtc-room-reconnecting",e.BRTC_ROOM_RECONNECTED="brtc-room-reconnected",e.JOIN_READY="join-ready",e.BRTC_SHARE_SYNC_ROOM_COMPLETED="brtc-share-sync-room-completed",e.LEAVE_USERS="leaveUsers",e.ROOM_ERROR="error-room",e.UPDATE_STREAM="update-stream"}(BCEvent||(BCEvent={}));var BCEvent$1=BCEvent,BoomCoreErrorCode;function isShareStream(e){const t=e.getStreamId();return e.getUserId().endsWith(STREAM_SUFFIX_SCREEN)||t.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()}class BoomError extends Error{constructor(e,t,r){let i;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,i="string"==typeof t?t:JSON.stringify(t),this.message=i,r&&(this.name=r)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}}!function(e){e[e.BloudLock=28]="BloudLock",e[e.ShareScreenNoPermission=100]="ShareScreenNoPermission",e[e.ShareScreenCanceled=101]="ShareScreenCanceled",e[e.ShareScreenOtherError=102]="ShareScreenOtherError",e[e.ShareScreenContentHintError=103]="ShareScreenContentHintError",e[e.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",e[e.BrtcShareSigError=105]="BrtcShareSigError",e[e.ToggleShareScreenError=106]="ToggleShareScreenError",e[e.BrtcCreateStreamError=107]="BrtcCreateStreamError",e[e.BrtcSubscribeError=108]="BrtcSubscribeError",e[e.BrtcPublishError=109]="BrtcPublishError",e[e.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",e[e.BrtcUnPublishError=111]="BrtcUnPublishError",e[e.RepeatJoinError=112]="RepeatJoinError",e[e.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",e[e.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",e[e.JoinUserInfoError=115]="JoinUserInfoError",e[e.JoinTypeError=116]="JoinTypeError",e[e.JoinBrtcError=117]="JoinBrtcError",e[e.JoinBloudError=118]="JoinBloudError",e[e.UpdateCustomStatsError=119]="UpdateCustomStatsError",e[e.CreateBloudError=120]="CreateBloudError"}(BoomCoreErrorCode||(BoomCoreErrorCode={})),new BoomError(BoomCoreErrorCode.ShareScreenNoPermission,"没有打开共享屏幕录制权限","no share permission"),new BoomError(BoomCoreErrorCode.ShareScreenCanceled,"取消共享屏幕","cancel share"),new BoomError(BoomCoreErrorCode.ShareScreenContentHintError,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed"),new BoomError(BoomCoreErrorCode.ShareScreenClientJoinedError,"共享屏幕brtc client入会失败","share client join failed"),new BoomError(BoomCoreErrorCode.BrtcShareSigError,"brtcShareSig为空","brtc share sig is empty");const RepeatJoinError=new BoomError(BoomCoreErrorCode.RepeatJoinError,"正在 join,请勿重复调用","repeat join error");new BoomError(BoomCoreErrorCode.ProxiesUrlTypeError,"proxies url 必须为字符串","get bloud proxies param error"),new BoomError(BoomCoreErrorCode.JoinUserInfoError,"userinfo传递错误,请检查"),new BoomError(BoomCoreErrorCode.JoinTypeError,"type传递错误,请检查");const updateCustomStatsError=e=>new BoomError(BoomCoreErrorCode.UpdateCustomStatsError,e,"bloud updateCustomStats failed");var BoomMeetingErrorCode;!function(e){e[e.BmJoinError=200]="BmJoinError",e[e.BMLeaveError=201]="BMLeaveError",e[e.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",e[e.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",e[e.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",e[e.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",e[e.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",e[e.BmChangeMasterError=207]="BmChangeMasterError",e[e.BmUpdateManagerError=208]="BmUpdateManagerError",e[e.BmEvictUserError=209]="BmEvictUserError",e[e.BmUpdateUserError=210]="BmUpdateUserError",e[e.BmSetAudioOffError=211]="BmSetAudioOffError",e[e.BmSetVideoOffError=212]="BmSetVideoOffError",e[e.BmSetMsgOffError=213]="BmSetMsgOffError",e[e.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",e[e.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",e[e.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",e[e.BmCheckDeviceError=217]="BmCheckDeviceError"}(BoomMeetingErrorCode||(BoomMeetingErrorCode={}));const BmLeaveError=e=>new BoomError(BoomMeetingErrorCode.BMLeaveError,e,"boommeeting leave failed"),BmSetRemoteVideoEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetRemoteVideoEnable,e,"开关对端摄像头失败"),BmSetRemoteAudioEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetRemoteAudioEnable,e,"开关对端麦克风发生失败"),BmSetLocalVideoEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalVideoEnable,e,"开关本地摄像头失败"),BmSetLocalAudioEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalAudioEnable,e,"开关本地麦克风失败"),BmSetLocalSpeakerEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalSpeakerEnable,e,"开关扬声器失败"),BmChangeMasterError=e=>new BoomError(BoomMeetingErrorCode.BmChangeMasterError,e,"转移主持人发生错误"),BmUpdateManagerError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateManagerError,e,"改变联席主持人发生错误"),BmEvictUserError=e=>new BoomError(BoomMeetingErrorCode.BmEvictUserError,e,"踢出用户发生错误"),BmUpdateUserError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateUserError,e,"更新用户信息发生错误"),BmSetAudioOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetAudioOffError,e,"全员静音发生错误"),BmSetVideoOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetVideoOffError,e,"全员禁用摄像头发生错误"),BmSetMsgOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetMsgOffError,e,"全员禁用聊天发生错误"),BmUpdateCustomStatsError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateCustomStatsError,e,"更新房间自定义属性状态发生错误"),BmChangeVideoProfileError=e=>new BoomError(BoomMeetingErrorCode.BmChangeVideoProfileError,e,"远程调节对方视频发生错误"),BmChangeAudioProfileError=e=>new BoomError(BoomMeetingErrorCode.BmChangeAudioProfileError,e,"远程调节对方音频发生错误"),BmCheckDeviceError=e=>new BoomError(BoomMeetingErrorCode.BmCheckDeviceError,e,"远程检测对方设备发生错误");var StreamErrorMap;!function(e){e[e.createStream=1302]="createStream",e[e.noCameraDevice=1303]="noCameraDevice",e[e.noMicroDevice=1304]="noMicroDevice",e[e.noSpeakerDevice=1305]="noSpeakerDevice",e[e.openCamera=1301]="openCamera",e[e.cameraNotAuth=1314]="cameraNotAuth",e[e.cameraOccupy=1315]="cameraOccupy",e[e.openMicro=1302]="openMicro",e[e.micNotAuth=1317]="micNotAuth",e[e.micOccupy=1319]="micOccupy",e[e.streamDisconnected=1320]="streamDisconnected",e[e.syncFail=1321]="syncFail",e[e.getStreamFail=1322]="getStreamFail",e[e.streamConnectError=1323]="streamConnectError",e[e.streamReconnectSuccess=1324]="streamReconnectSuccess",e[e.streamReconnectFailed=1325]="streamReconnectFailed",e[e.shareStreamConnectError=1326]="shareStreamConnectError",e[e.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",e[e.shareStreamConnectFailed=1328]="shareStreamConnectFailed"}(StreamErrorMap||(StreamErrorMap={}));const BMCreateStreamError=e=>new BoomError(StreamErrorMap.createStream,`采集${e}流失败,请重试`),getStreamError=e=>new BoomError(StreamErrorMap.getStreamFail,`当前${e}不可用, 请确保您的${e}连接正确, 或更换其他${e}`),BMOpenCameraError=()=>new BoomError(StreamErrorMap.openCamera,"打开摄像头失败"),BMCameraNotAuthError=()=>new BoomError(StreamErrorMap.cameraNotAuth,"摄像头设备未授权, 无法开启视频, 启动摄像头失败, 请在系统或浏览器“设置-隐私”中允许使用摄像头"),BMCameraOccupyError=()=>new BoomError(StreamErrorMap.cameraOccupy,"当前摄像头被占用, 请检查或切换其他摄像头"),BMOpenMicroError=()=>new BoomError(StreamErrorMap.openMicro,"打开麦克风失败"),BMMicNotAuthError=()=>new BoomError(StreamErrorMap.micNotAuth,"麦克风设备未授权, 无法开启麦克风, 启动麦克风失败, 请在系统或浏览器“设置-隐私”中允许使用麦克风"),BMMicOccupyError=()=>new BoomError(StreamErrorMap.micOccupy,"当前麦克风被占用, 请检查或切换其他麦克风"),BMStreamDisconnectedError=e=>new BoomError(StreamErrorMap.streamDisconnected,`${e}连接已断开,正在重试,请稍后`),BmSyncStreamFailError=()=>new BoomError(StreamErrorMap.syncFail,"状态同步异常,请重试, 麦克风和摄像头已自动关闭"),BMStreamConnectError=()=>new BoomError(StreamErrorMap.streamConnectError,"网络连接异常,正在重试"),BMShareStreamConnectError=()=>new BoomError(StreamErrorMap.shareStreamConnectError,"共享屏幕网络连接异常,正在重试"),BMStreamReconnectSuccess=(e,t)=>{let r="";return e&&t?r="麦克风和摄像头":e?r="麦克风":t&&(r="摄像头"),new BoomError(StreamErrorMap.streamReconnectSuccess,`网络连接成功, ${r}已自动打开`)},BMShareStreamReconnectSuccess=()=>new BoomError(StreamErrorMap.shareStreamConnectSuccess,"共享屏幕网络连接成功, 已自动打开"),BMStreamReconnectFailed=()=>new BoomError(StreamErrorMap.streamReconnectFailed,"网络连接失败,请检查网络,麦克风和摄像头已自动关闭"),BMShareStreamReconnectFailed=()=>new BoomError(StreamErrorMap.streamReconnectFailed,"共享屏幕网络连接失败,请检查网络,共享屏幕已自动关闭");function checkStreamIsNormal(e){var t,r,i,n;if(e&&!e.isLocal){(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)))&&setTimeout((()=>{var t,r,i,n;(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(r=e.stream)||void 0===r?void 0:r.getVideoTrack())||e.audioEnable&&!(null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)))&&(warn("用户流检测,但是流订阅出现了问题,需要重新订阅","用户流检测",e.userId,[" nickname => ",e.nickname,"isDisplay =>",e.isDisplay]),e.hasPulled=!1,e.pulledStreamType="small",e.sendMessage2Room())}),2e3)}}function handleBloudReconnectStreamEvent(e){var t,r;const i=e.getLocalStreamModel();if(i&&!(null==i?void 0:i.stream))e.bloudStream&&(info("brtc 已经没有流了,bloud 的流要取消掉"),e.bloudStream.unpublish(),i.updateBloudStream(void 0,e),e.bloudStream=null);else if(i&&i.stream){info("brtc 流已经重推上去了,bloud要重新发推流的逻辑");const t=i.stream.getAudioOn(),r=i.stream.getVideoOn();e.publishBloudStream(t,r).then((()=>{info("brtc stream repub success bloud repub success, notify reconnect success"),e.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess(t,r))}))}if(e.localIsShare){info("brtc has share stream, and bloud need to republish share stream");const i=null===(t=e.room)||void 0===t?void 0:t.boomCore.shareScreenStream;if(i){const t=i.getAudioOn(),n=i.getVideoOn();try{null===(r=e.room)||void 0===r||r.boomCore.createAndPubBloudShareStream(t,n)}catch(e){error$1("bloud 共享屏幕流,断网重连重推流失败")}}}}const handleReconnectedStream=debounce((e=>{if(e.networkState.bloud&&e.networkState.brtc)try{e.streamQueue.restart()}catch(t){e.streamQueue.setQueueProcessor(e.queueProcessor),e.streamQueue.restart()}}),300);function handleStreamPublished(e,t,r,i){const n=e.stream;if(info("本地推流","本地推流",n.getUserId()),n){const e=t.getLocalStreamModel();if(e&&t.updateStreamModel(e,n),i[BCEvent$1.STREAM_PUBLISHED].next({published:!0,model:e}),1===r.conferenceMode){r.getLocalParticipant().isAudience&&t.getStreamModels().forEach((e=>{e.sendMessage2Room()}))}}else i[BCEvent$1.STREAM_PUBLISHED].next({published:!1})}function handleBloudStreamPublished(e,t,r){info("bloud publish stream"),handleBloudStreamPubAUpdate(e,t,!0),r[BCEvent$1.PUBLISHED].next(e)}function handleBloudStreamPubAUpdate(e,t,r=!1){var i;info("bloud stream update","","",[JSON.stringify(e)]);const n=e.userId,s=e.isScreen,o=t.streamModels.get(n);if(o)if(s){t.shareBloudStateMap.set(n,e);const r={id:n,isWeb:o.isWeb,isScreen:s};null===(i=t.room)||void 0===i||i.addUser2Queue(r)}else o.updateBloudStream(e,t,r),o.getUser().updateSortNum();else error$1("bloud stream update, but can not get streamModel","",n)}function handleBloudStreamUnPublished(e,t,r){info("bloud unpublish stream","","",[JSON.stringify(e)]),handleBloudStreamUnpublish(e,t),r[BCEvent$1.UNPUBLISH].next(e)}function handleBloudStreamUpdated(e,t,r){info("bloud stream update","","",[JSON.stringify(e)]);const i=e.streamId,n=e.userId,s=e.params.customInfo;let o;o=i.includes("_screen")?t.shareStreamModels.get(n):t.streamModels.get(n),o?o.updateBloudCustomInfo(s):error$1("bloud stream update, but can not get streamModel","",n,["streamId =>",i]),r[BCEvent$1.UPDATE_STREAM].next(e)}function handleBloudStreamUnpublish(e,t){var r,i,n;const s=e.userId;if(e.isScreen){const e=t.shareStreamModels.get(s);if(e){const r=e.stream;r?(t.remoteStreamUnpublished(r),r.destroy()):t.removeShareStreamModelByUId(s);const i={id:s,isWeb:e.isWeb,isScreen:!0};null===(n=t.room)||void 0===n||n.streamQueue.removeUsers([i])}}else{const e=t.streamModels.get(s);if(e){e.updateBloudStream(void 0,t);const n=e.stream;n&&(null===(r=t.room.audioPlayer)||void 0===r||r.removeStream(n),t.remoteStreamUnpublished(n),n.destroy());const o={id:s,isWeb:e.isWeb,isScreen:!1};null===(i=t.room)||void 0===i||i.streamQueue.removeUsers([o])}}}function handleShareStreamFailed(e,t){setTimeout((()=>__awaiter$2(this,void 0,void 0,(function*(){info("handle republish share stream");try{const r=e.boomCore.shareScreenStream;if(r){const i=r.getAudioOn(),n=r.getVideoOn();yield e.boomCore.shareBrtcClient.publish(r),e.boomCore.createAndPubBloudShareStream(i,n),info("handle republish share stream success"),t.localShareError.next(BMShareStreamReconnectSuccess())}else warn("no share stream exist")}catch(e){error$1("handle republish share stream failed , now unpublish"),t.localShareError.next(BMShareStreamReconnectFailed()),yield t.toggleShareScreen(!1,void 0)}}))),1e3)}function setupRoomInfo(e,t,r){const i=e.permission,n=e.total;i&&r.updateLocalUserPermission(i),t.isInWaitRoom=e.joinwait;const s=e.waitroom;t.roomInfo.isOpenWaitRoom.next(s),t.roomInfo.totalUserWatcher.next(n)}function handleRoomConnected(e,t,r,i,n=!0){var s;return __awaiter$2(this,void 0,void 0,(function*(){info("room-connected",t.getLocalParticipant().userId,"room-connected",["roomId =>",t.roomInfo.roomID," local permission => ",e.permission]),t.forceId=null===(s=e.customStats.forceOn)||void 0===s?void 0:s.user,handleInitRoomInfo(e,t),setupRoomInfo(e,t,r),n&&i[BCEvent$1.ROOM_CONNECTED].next(e)}))}function handleInitJoinRoomUsers(e){return __awaiter$2(this,void 0,void 0,(function*(){info("join ready init users"),e.isInWaitRoom||(e.forceId&&(yield e.getForceUser(e.forceId)),yield e.userVM.initUsers())}))}function handleRoomUpdated(e,t){info("update-stats "," ","",["options => ",JSON.stringify(e.options)]),e.options&&"audiooff"==e.options[0]||"selfopenaudio"==e.options[1]?t.roomInfo.setAudioOff(e.room.audiooff,e.room.selfopenaudio):e.options&&"lock"==e.options[0]?t.roomInfo.setlock(e.room.lock):e.options&&"waitroom"==e.options[0]&&t.roomInfo.isOpenWaitRoom.next(e.stats.waitroom)}function handleInitRoomInfo(e,t){t.roomInfo.msgSeq=e.msgSeq,e.customStats&&t.roomInfo.initCustomStats(e.customStats)}function exitUserUpdateStream(e,t,r,i,n){var s;e.updateUser(t,r);const o=r.stream,a=i.streamModels.get(t.userId);if(a||error$1("bmUserVM中存在该用户,但是bmStreamModelVM中不存在该用户,佛了"),!o.size){(null==a?void 0:a.bloudStream)&&(a.updateBloudStream(void 0,i),n.streamQueue.removeUsers([{id:t.userId,isScreen:!1},{id:t.userId,isScreen:!0}]));const e=i.shareStreamModels.get(t.userId);e&&!e.isLocal&&(null===(s=e.stream)||void 0===s||s.destroy(),i.removeShareStreamModel(e))}o.get(`${t.userId}_screen`)&&n.addUser2Queue({id:t.userId,isScreen:!0,isWeb:t.isWeb});const c=o.get(t.userId);c&&(null==a||a.updateBloudStream({audio:c.audio_enable,video:c.video_enable,isScreen:!1},i))}function addUsers(e,t,r,i){e.isSingleColumns?t.commonUserList.forEach((n=>{const s=r.get(n.userId);if(s)return r.delete(n.userId),void exitUserUpdateStream(t,n,s,i,e);t.commonUserList.delete(n.userId),i.streamModels.delete(n.userId),i.shareStreamModels.delete(n.userId)})):t.userList.forEach((n=>{const s=r.get(n.userId);if(s)return exitUserUpdateStream(t,n,s,i,e),void(n.isCommonUser?t.userList.delete(n.userId):r.delete(n.userId));t.userList.delete(n.userId),i.streamModels.delete(n.userId),i.shareStreamModels.delete(n.userId)})),e.userVM.addBcUsersMap(r)}function handleRoomSync(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){const n=t.getLocalParticipant().userId,{users:s}=yield t.boomCore.queryUsers([n]),o=s.get(n);o&&r.updateUser(r.localUser,o);const a=t.getLocalParticipant().isCommonUser;if(t.isBig&&a){const{users:e}=yield t.boomCore.getUsersList(0,PERMISSION_NOT_COMMON,500);addUsers(t,r,e,i)}else{const e=(yield t.userVM.getTotalUserNumber())/BLOUD_PAGE_SIZE;let n=new Map;for(let r=0;r<e;r++){let{users:e}=yield t.boomCore.getUsers(r-1,"",BLOUD_PAGE_SIZE);e.forEach((e=>{n.set(e.userId,e)}))}addUsers(t,r,n,i)}handleInitRoomInfo(e,t),t.userVM.updateAllSort(),t.bmStreamVm.updateModelSort()}))}function handleBrtcRoomReconnecting(e,t,r){info("brtc room reconnecting"),t.networkState.brtc=!1,t.streamWSReconnectWatcher.next(!1),r[BCEvent$1.BRTC_ROOM_ROCONNECTING].next(e)}function handleBrtcRoomReconnected(e,t,r){info("brtc room reconnected"),t.networkState.brtc=!0,handleReconnectedStream(t),r[BCEvent$1.BRTC_ROOM_RECONNECTED].next(e)}function handleBloudRoomReconnecting(e,t,r){info("bloud room reconnecting"),t.networkState.bloud=!1,t.bloudWSReconnectWatcher.next(!1),r[BCEvent$1.ROOM_RECONNECTING].next(e)}function handleBloudRoomReconnected(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){t.hasSyncPermission?(info("bloud room reconnected"),t.bloudWSReconnectWatcher.next(!1),r[BCEvent$1.MOVE_USER_ROOM].next(null),yield t.syncRoom().then((()=>{t.hasSyncPermission=!0,r[BCEvent$1.ROOM_RECONNECTED].next(e)})).catch((e=>{error$1("sync room error",JSON.stringify(e));if(43===e.code)return t.hasSyncPermission=!1,void r[BCEvent$1.USERREJOINED].next(e);t.hasSyncPermission=!1,r[BCEvent$1.NETWORK_ERROR].next(e)}))):r[BCEvent$1.NETWORK_ERROR].next(e)}))}function handleBloudRoomSync(e,t,r,i,n){return __awaiter$2(this,void 0,void 0,(function*(){info("bloud sync room completed"),setupRoomInfo(e,r,t),yield handleRoomSync(e,r,t,i),handleBloudReconnectStreamEvent(i),r.networkState.bloud=!0,handleReconnectedStream(r),r.bloudWSReconnectWatcher.next(!0),n[BCEvent$1.ROOM_SYNC].next(e)}))}function handleParticipantJoin(e,t,r,i,n,s){var o,a,c,u,d,l,h,m,p,f,g,v,_;const y=null===(a=null===(o=null==e?void 0:e.participant)||void 0===o?void 0:o.params)||void 0===a?void 0:a.info.sync,S=e.mode;info("用户入会","用户入会",e.user.userId,["sync => ",y,"mode =>",S]);const E=t.room.isBig&&r.streamModels.size>1e3;let b=!1;if(y){let r=t.userList.get(e.user.userId);if(r||(r=t.commonUserList.get(e.user.userId)),r)return void(r.inBackground!=!!(null===(u=null===(c=e.user)||void 0===c?void 0:c.customInfo)||void 0===u?void 0:u.inBackground)&&(r.inBackground=!!(null===(l=null===(d=e.user)||void 0===d?void 0:d.customInfo)||void 0===l?void 0:l.inBackground),r.watcher.next({operation:"inBackground",user:r})))}1===S&&(null===(h=t.room)||void 0===h?void 0:h.isBig)&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId));if(getIsCommonUser(e.user.permission.permission)){t.userList.get(e.user.userId)&&(t.userList.delete(e.user.userId),r.streamModels.delete(e.user.userId),b=!0)}else{const i=t.commonUserList.get(e.user.userId);(null===(m=t.room)||void 0===m?void 0:m.isSingleColumns)||i&&(t.commonUserList.delete(e.user.userId),r.streamModels.delete(e.user.userId),b=!0)}let T=t.addBCUser(e.user);if(T){T.inBackground!=!!(null===(f=null===(p=e.user)||void 0===p?void 0:p.customInfo)||void 0===f?void 0:f.inBackground)&&(T.inBackground=!!(null===(v=null===(g=e.user)||void 0===g?void 0:g.customInfo)||void 0===v?void 0:v.inBackground),T.watcher.next({operation:"inBackground",user:T}));let o=!1;if(ignoreUserId.forEach((e=>{(null==T?void 0:T.userId.includes(e))&&(o=!0)})),b?t.updateAllSort():(null===(_=t.room)||void 0===_?void 0:_.isSingleColumns)?t.updateCommonUserSort():T?T.isCommonUser?E?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),!o){if(1!==e.mode){const e=new BMMessageInfo({isMeetingNotice:!0,userId:T.userId,message:T.nickName+"加入"+(2==i.roomType?"直播":"会议")});n.addMessage(e,!0)}s[BCEvent$1.JOINUSER].next({user:T,mode:S,data:e})}}}function handleLeaveUsers(e,t,r,i,n,s,o){var a;const c=e.userIds;info("bloud leave users","","",["userIds =>",c]),c.length&&(c.forEach((e=>{const a=leaveUser(e,t,r,n);a&&sendLeveNotification(a,s,o,i,!0,0)})),(null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():t.updateAllSort(),n.updateModelSort())}function handleParticipantLeft(e,t,r,i,n,s,o){var a;info(`bloud participant left ===>${e.userId}, ${e.mode}`);const c=1===e.mode,u=e.userId,d=r.isBig&&n.streamModels.size>1e3;if(u){const l=leaveUser(u,t,r,n);if((null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():l?l.isCommonUser?d?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),n.updateModelSort(),c)return void i[BCEvent$1.LEAVEUSER].next({user:l,mode:e.mode,data:e});l&&sendLeveNotification(l,s,o,i,1!==e.mode,e.mode)}else warn("participant-left触发=======>但是该用户信息不存在",LOGGER_TAG_CLIENT,null,[e.userId]),i[BCEvent$1.LEAVEUSER].next({user:e.userId,mode:e.mode,data:e})}function sendLeveNotification(e,t,r,i,n,s){let o=!1;if(ignoreUserId.forEach((t=>{(null==e?void 0:e.userId.includes(t))&&(o=!0)})),!o){if(n){const i=new BMMessageInfo({isMeetingNotice:!0,userId:e.userId,message:(null==e?void 0:e.nickName)+"离开"+(2==t.roomType?"直播":"会议")});r.addMessage(i,!0)}i[BCEvent$1.LEAVEUSER].next({user:e,mode:s})}}function leaveUser(e,t,r,i){const n=t.getUser(e);return t.removeUser(e),r.streamQueue.removeUsers([{id:e,isScreen:!1},{id:e,isScreen:!0}]),i.removeStreamModelByUId(e),i.removeShareStreamModelByUId(e),r.roomInfo.removeRaiseHandUser(e),r.roomInfo.removeVideoRaiseHandUser(e),r.roomInfo.removeSimpleRaiseHandUser(e),i.shareBloudStateMap.delete(e),n}function handleChangeMaster(e,t,r,i,n){info("changeMaster =>","changeMaster","",["master: => ",e.master,"oldMaster =>",e.oldMaster]);const s=e.master,o=e.oldMaster,a=e.isKeep;if(s){let c=t.updateMaster(s,o,a);c.master&&(c.master.watcher.next({operation:"getMaster",user:c.master}),r.userVM.masterUserWatcher.next(c.master)),c.oldMaster&&(c.oldMaster.watcher.next({operation:"removeMaster",user:c.oldMaster}),a&&c.oldMaster.watcher.next({operation:"getManager",user:c.oldMaster}));const u=n.getStreamModelByUId(o),d=n.getStreamModelByUId(s);null==u||u.updateSortNum(),null==d||d.updateSortNum(),i[BCEvent$1.CHANGEMASTER].next({master:c.master,oldMaster:c.oldMaster,data:e})}else warn("change-master触发=======>但是房间内找不到master",LOGGER_TAG_CLIENT,null,s),i[BCEvent$1.CHANGEMASTER].next(null)}function handleEvict(e,t,r,i,n){var s;const o=e.userId,a=t.getUser(o);info("踢出用户 => ","evict ",null==a?void 0:a.userId,["nickname => ",null==a?void 0:a.nickName]);const c=leaveUser(o,t,i,r);(null===(s=t.room)||void 0===s?void 0:s.isSingleColumns)?t.updateCommonUserSort():c?c.isCommonUser?t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),r.updateModelSort(),n[BCEvent$1.EVICTED].next(e)}function handleUpdateUser(e,t,r,i,n){var s,o;if(info("用户信息被改变","",null===(s=e.user)||void 0===s?void 0:s.userId),null===(o=e.user)||void 0===o?void 0:o.userId){let s=t.getUser(e.user.userId),o=i.getStreamModelByUId(e.user.userId);s?s.updateUserInfo(e.user,e.participant,r):console.warn("participant-update: bmUser is null"),o&&o.updateSortNum(!0),n[BCEvent$1.UPDATEUSER].next({bmUser:s,params:e.participant.params})}}const handleUserRejoined=debounce(((e,t,r)=>{e[t.USERREJOINED].next(r)}),1e3);function handleMoveUserRoom(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){info("bloud move user room","","",[r]);const n=r.toWait;if(e.isInWaitRoom=n,n){e.handleResetOtherStreamStatus(),t.userList.clear(),t.userListWatcher.next([]),t.commonUserList.clear(),t.commonUserListWatcher.next([]),e.bmStreamVm.streamModels.clear(),i[BCEvent$1.CUSTOMMESSAGE].next(null),e.messageWatcher.next({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),e.audioPlayer.destroy();const r=e.bmStreamVm.localModel;r&&e.bmStreamVm.streamModels.set(r.userId,r),e.bmStreamVm.streamModelsWatcher.next([]),e.bmStreamVm.shareStreamModels.clear(),e.bmStreamVm.shareStreamModelsWatcher.next([]),e.roomInfo.raiseHandsWatcher.next([]),e.roomInfo.raiseVideoHandsWatcher.next([]),e.roomInfo.raiseSimpleHandsWatcher.next([])}else{yield handleRoomConnected(r.info,e,t,i,!1);const{audioOff:n,selfopenaudio:s,lock:o}=r.info;o!==e.roomInfo.lock&&e.roomInfo.setlock(o),n===e.roomInfo.audioOff&&s===e.roomInfo.selfopenaudio||e.roomInfo.setAudioOff(n,s),yield handleInitJoinRoomUsers(e)}i[BCEvent$1.MOVE_USER_ROOM].next(n)}))}function handleSendMessage(e,t,r,i){var n,s,o,a,c,u,d,l,h;let m=Object.assign({},e);if(m.message){if(m.message="string"==typeof m.message?JSON.parse(m.message):m.message,info("new-message","","",[" method => ",m.message.method]),"send-talk"===m.message.method){const i=m.user===(null===(n=t.getLocalUser())||void 0===n?void 0:n.userId),p=(null===(o=null===(s=m.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.status)||"",f=null===(u=null===(c=null===(a=m.message)||void 0===a?void 0:a.params)||void 0===c?void 0:c.stream)||void 0===u?void 0:u.avatar,g=e.seq,v=new BMMessageInfo({userId:m.user,message:p,isLocal:i,avatar:f,to:m.to,seq:g,nickName:null===(h=null===(l=null===(d=m.message)||void 0===d?void 0:d.params)||void 0===l?void 0:l.stream)||void 0===h?void 0:h.nickname,sendTime:(new Date).getTime()});r.addMessage(v,!1)}i[BCEvent$1.SENDMESSAGE].next(m)}}function handleCustomMessage(e,t,r){var i,n,s,o,a,c,u,d,l,h,m,p,f;let g=Object.assign({},e);if(g.message)if(g.message="string"==typeof g.message?JSON.parse(g.message):g.message,info("custom-message","","",[" method => ",g.message.method]),"video-force-change"==g.message.method){const e="enabled"==g.message.params.status;info(`远端控制本地摄像头: ${e}`),t.messageWatcher.next({type:MessageType.VIDEO_FORCE_CHANGE,status:e,fromUserId:g.user})}else if("audio-force-change"==g.message.method){let e;e="checkUserAudio"==g.message.params.status?g.message.params.status:"enabled"==g.message.params.status,info(`远端控制本地麦克风: ${e}`),t.messageWatcher.next({type:MessageType.AUDIO_FORCE_CHANGE,status:e,fromUserId:g.user,isNotCancelRootReport:null===(i=g.message.params)||void 0===i?void 0:i.isNotCancelRootReport})}else if("raise-hands"===g.message.method)t.raiseHandleRespWatcher.next(g.message.params);else if("give-like"===g.message.method)null===(n=t.roomVM)||void 0===n||n.giveLikeList.push({userId:g.user,nickName:null===(a=null===(o=null===(s=g.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.stream)||void 0===a?void 0:a.nickname,time:(new Date).getTime(),type:null===(d=null===(u=null===(c=g.message)||void 0===c?void 0:c.params)||void 0===u?void 0:u.stream)||void 0===d?void 0:d.type}),null===(l=t.roomVM)||void 0===l||l.giveLikeListWatcher.next(null===(h=t.roomVM)||void 0===h?void 0:h.giveLikeList);else if("resp-to-check-devices"===g.message.method)(null===(m=g.message)||void 0===m?void 0:m.params)&&(g.message.params.fromUserId=g.user),r[BCEvent$1.CUSTOMMESSAGE].next(g);else if("usercount"===g.message.method){if(g.message.params){let e=null===(f=null===(p=g.message)||void 0===p?void 0:p.params)||void 0===f?void 0:f.total;e?(e=Number(e),e<0&&(warn("服务返回的usercount为负数,"+e),e=0)):(warn("服务未返回usercount,"+e),e=0),t.roomInfo.totalUserWatcher.next(e)}}else if("waitusercount"===g.message.method){if(g.message.params){const e=g.message.params.total;t.roomInfo.totalWaitRoomUserWatcher.next(e)}}else r[BCEvent$1.CUSTOMMESSAGE].next(g)}let reconnectFailed=0,shareReconnectFailed=0;const NETWORK_ERROR_QUEUE=new Set;function handleBRTCRoomError(e,t,r,i,n){return __awaiter$2(this,void 0,void 0,(function*(){error$1("brtc error","brtc error","",[(new Date).toLocaleTimeString(),JSON.stringify(e),e.getCode()]);if(4002===e.getCode()){t.BRTCConnectFailed=!0,t.networkState.brtc=!1,warn("brtc 信令通道错误,需要重新走入会","brtc error",""),t.streamWSReconnectWatcher.next(!1);try{yield r.brtcClient.leave("room_close")}catch(e){error$1("brtc 离会失败")}setTimeout((()=>__awaiter$2(this,void 0,void 0,(function*(){t.handleResetOtherStreamStatus(),yield reconnectBrtcWS(r,t,n,e).catch((t=>{info("brtc断网重连失败, 处理一下退会逻辑","","",[JSON.stringify(t)]),n[BCEvent$1.ERROR].next(e)}))}))),1e3)}else n[BCEvent$1.ERROR].next(e)}))}function reconnectBrtcWS(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{setTimeout((()=>{info("brtc重连"),e.brtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>__awaiter$2(this,void 0,void 0,(function*(){info("brtc断网重连成功, 重新处理拉流和推流"),t.networkState.brtc=!0,setTimeout((()=>{t.brtcNetEnableWatcher.next(!0)}),2e3),handleReconnectedStream(t),t.BRTCConnectFailed=!1,reconnectFailed=0,yield t.handleRePushSelf(),t.streamWSReconnectWatcher.next(!0),n(!0)})))).catch((n=>{const o=n.getCode();info("断网重连入会失败","","",[n,o]),reconnectFailed<=10?(reconnectFailed+=1,e.brtcClient.isJoinning=!1,setTimeout((()=>{reconnectBrtcWS(e,t,r,i)}),2e3)):(error$1("brtc断网重连失败,处理一下退会"),reconnectFailed=0,r[BCEvent$1.ERROR].next(i),s(!1))}))}),7e3)}))}))}function reconnectBRTCShareWS(e){return __awaiter$2(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{setTimeout((()=>{info("共享屏幕重连"),e.shareBrtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>{shareReconnectFailed=0,t(!0)})).catch((t=>{const r=t.getCode();if(info("共享屏幕断网重连入会失败","","",[t,r]),!(shareReconnectFailed<=3))throw error$1("共享屏幕用户重连失败,处理一下取消共享屏幕"),shareReconnectFailed=0,new Error("共享屏幕重连失败");shareReconnectFailed+=1,reconnectBRTCShareWS(e)}))}),7e3)}))}))}function handleBloudError(e,t,r,i,n){return __awaiter$2(this,void 0,void 0,(function*(){error$1("network-error","network-error","local-client",["本地链接出现问题","netconnectiong => ",e.netConnecting]),e.netConnecting?yield handleBloudRoomReconnected(i,e,n):n[BCEvent$1.NETWORK_ERROR].next(i)}))}function handleCustomStats(e,t,r){let i=null==e?void 0:e.updateKeys;info("update-custom-stats"," "," ",["updateKeys => ",JSON.stringify(i)]),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich"))||(null==i?void 0:i.includes("fileUpdateLook"))||(null==i?void 0:i.includes("fileUpdateDown"))||(null==i?void 0:i.includes("fileUpdateEdit"))||(null==i?void 0:i.includes("fileUpdateModel"))||(null==i?void 0:i.includes("screenShareModel"))||(null==i?void 0:i.includes("onlyOnePersonShare"))||(null==i?void 0:i.includes("chatEnable"))||(null==i?void 0:i.includes("giveLikeEnable"))||(null==i?void 0:i.includes("cloudRecord"))||(null==i?void 0:i.includes("joinAudioEnable"))||(null==i?void 0:i.includes("joinVideoEnable"))||(null==i?void 0:i.includes("userListEnable"))||(null==i?void 0:i.includes("audioEnable"))||(null==i?void 0:i.includes("videoEnable"))||(null==i?void 0:i.includes("modifyNameEnable"))||(null==i?void 0:i.includes("backgroundAIEnable"))||(null==i?void 0:i.includes("recordEnable"))||(null==i?void 0:i.includes("joinMicrophoneDisable"))||(null==i?void 0:i.includes("joinCameraDisable"))||(null==i?void 0:i.includes("raiseHandEnable"))||(null==i?void 0:i.includes("forceOpenUserMic"))||(null==i?void 0:i.includes("forceOpenUserCamera"))||(null==i?void 0:i.includes("joinCueVoice")))&&t.roomInfo.updateOperationPermission(e.customStats),((null==i?void 0:i.includes("chatNotice"))||(null==i?void 0:i.includes("chatNoticeRich")))&&t.roomInfo.chatNoticeWatcher.next(e),r[BCEvent$1.CUSTOMSTATS].next(e)}var dist={},eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,i,s,o){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new n(i,s||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,o=new Array(s);n<s;n++)o[n]=i[n].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,n,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,u,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,s),!0;case 6:return d.fn.call(d.context,t,i,n,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var h,m=d.length;for(u=0;u<m;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,i);break;case 4:d[u].fn.call(d[u].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,i,n){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||n&&!a.once||i&&a.context!==i||o(this,s);else{for(var c=0,u=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||i&&a[c].context!==i)&&u.push(a[c]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(eventemitter3);var pTimeout$1={exports:{}},pFinally$1=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))));const pFinally=pFinally$1;class TimeoutError extends Error{constructor(e){super(e),this.name="TimeoutError"}}const pTimeout=(e,t,r)=>new Promise(((i,n)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const s=setTimeout((()=>{if("function"==typeof r){try{i(r())}catch(e){n(e)}return}const s=r instanceof Error?r:new TimeoutError("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),n(s)}),t);pFinally(e.then(i,n),(()=>{clearTimeout(s)}))}));pTimeout$1.exports=pTimeout,pTimeout$1.exports.default=pTimeout,pTimeout$1.exports.TimeoutError=TimeoutError;var priorityQueue={},lowerBound$1={};function lowerBound(e,t,r){let i=0,n=e.length;for(;n>0;){const s=n/2|0;let o=i+s;r(e[o],t)<=0?(i=++o,n-=s+1):n=s}return i}Object.defineProperty(lowerBound$1,"__esModule",{value:!0}),lowerBound$1.default=lowerBound,Object.defineProperty(priorityQueue,"__esModule",{value:!0});const lower_bound_1=lowerBound$1;class PriorityQueue{constructor(){Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]})}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const i=lower_bound_1.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}priorityQueue.default=PriorityQueue,Object.defineProperty(dist,"__esModule",{value:!0});const EventEmitter=eventemitter3.exports,p_timeout_1=pTimeout$1.exports,priority_queue_1=priorityQueue,empty=()=>{},timeoutError=new p_timeout_1.TimeoutError;class PQueue extends EventEmitter{constructor(e){var t,r,i,n;if(super(),Object.defineProperty(this,"_carryoverConcurrencyCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isIntervalIgnored",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalCap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalEnd",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queueClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_concurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isPaused",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveEmpty",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_resolveIdle",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_throwOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:priority_queue_1.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(n=null===(i=e.interval)||void 0===i?void 0:i.toString())&&void 0!==n?n:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother()}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=empty,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=empty)}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={},r=null){return new Promise(((i,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const s=void 0===this._timeout&&void 0===t.timeout?e():p_timeout_1.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(timeoutError),r&&r("resolve-timeout")}));r&&r("resolving"),i(await s),this._isPaused?r&&r("resolve-paused"):r&&r("resolve")}catch(e){this._isPaused?r&&r("resolve-paused"):r&&r("resolve"),n(e)}this._next()}),t),this._tryToStartAnother()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}var _default=dist.default=PQueue;class Pqueue{constructor(e,t=!0){this.queue=new _default({concurrency:e,autoStart:t,carryoverConcurrencyCount:!0,timeout:3e3,completeAction:e=>{console.log("task complete",e)}}),this.queueArray=[],this.isTaskPending=t}addQueue(e,t,r=0,i=""){this.queue.isPaused&&this.queue.start();let n={};n.taskID=t,n.status="pending",this.queue.add(e,{priority:r,timeout:3e3},(e=>{if(n.status=e,"resolve"===n.status||"resolve-paused"===n.status||"resolve-timeout"===n.status){const e=this.queueArray.findIndex((e=>n.taskID===e.taskID));-1!==e&&this.queueArray.splice(e,1)}})),this.queueArray.push(n)}clearQueue(){this.queue.clear(),this.queueArray=[],this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{console.log("clearQueue全部完事")}))}startQueue(){this.queue.start()}pauseQueue(){return this.queue.pause(),console.log(`size:${this.size()}`),this.isTaskPending=!1,this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{})),this.queueArray}size(){return this.queue.size}pending(){return this.queue.pending}checkTaskStatus(){return this.isTaskPending}setTaskStatus(e){this.isTaskPending=e}onIdle(){return this.queue.onIdle()}onEmpty(){return this.queue.onEmpty()}}const streamPullQueue=new Pqueue(4),eventQueue=new Pqueue(10);var MessageType;function attachEvents(e,t,r,i,n){info("attachEvents init");let s={};return e.on("toggle-screen-share",(()=>{error$1("share stream video track ended, now unpublish share stream"),r.localShareError.next(BMShareStreamReconnectFailed()),r.toggleShareScreen(!1,void 0).then((()=>{}))})),e.on("client-banned",(()=>__awaiter$2(this,void 0,void 0,(function*(){yield n.boomCore.leaveShare()})))),e.on("share-brtc-error",(t=>__awaiter$2(this,void 0,void 0,(function*(){if(4002===t.getCode())try{info("brtc share client disconnected, reconnecting"),yield e.shareBrtcClient.leave("room_close"),reconnectBRTCShareWS(e).then((()=>__awaiter$2(this,void 0,void 0,(function*(){info("brtc share client reconnected, retry repub share stream"),yield sleep(1e3);const t=e.shareScreenStream.getAudioOn(),r=e.shareScreenStream.getVideoOn();e.shareBrtcClient.publish(e.shareScreenStream),e.createAndPubBloudShareStream(t,r)})))).catch((e=>{throw new Error("共享屏幕重新入会失败")}))}catch(e){r.toggleShareScreen(!1,void 0).then((()=>{})).catch((e=>{error$1("共享发生错误退会失败","","",[JSON.stringify(e)])}))}})))),Object.values(BCEvent).forEach((e=>{s[e]=new BehaviorSubject(null)})),Object.values(BCEvent).forEach((o=>{switch(o){case BCEvent.STREAM_PUBLISHED:e.on(BCEvent.STREAM_PUBLISHED,(e=>{eventQueue.addQueue(handleStreamPublished.bind(null,e,r,n,s),BCEvent.STREAM_PUBLISHED)}));break;case BCEvent.BRTC_SYNC_ROOM_COMPLETED:e.on(BCEvent.BRTC_SYNC_ROOM_COMPLETED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(n.handleResetOtherStreamStatus.bind(n),BCEvent.BRTC_SYNC_ROOM_COMPLETED)}))));break;case BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED:e.on(BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED,(()=>{info("brtc share client sync completed, retry publish share stream"),eventQueue.addQueue(handleShareStreamFailed.bind(null,n,r),BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));break;case BCEvent.BRTC_ROOM_ROCONNECTING:e.on(BCEvent.BRTC_ROOM_ROCONNECTING,(e=>{eventQueue.addQueue(handleBrtcRoomReconnecting.bind(null,e,n,s),BCEvent.BRTC_ROOM_ROCONNECTING)}));break;case BCEvent.BRTC_ROOM_RECONNECTED:e.on(BCEvent.BRTC_ROOM_RECONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBrtcRoomReconnected.bind(null,e,n,s),BCEvent.BRTC_ROOM_RECONNECTED)}))));break;case BCEvent.CLIENT_BANNED:e.on(BCEvent.CLIENT_BANNED,(e=>{info("brtc client banned"),handleUserRejoined(s,BCEvent,e)}));break;case BCEvent.ERROR:e.on(BCEvent.ERROR,(t=>__awaiter$2(this,void 0,void 0,(function*(){n.netConnecting?eventQueue.addQueue(handleBRTCRoomError.bind(null,t,n,e,r,s),BCEvent.ERROR):NETWORK_ERROR_QUEUE.add(handleBRTCRoomError.bind(null,t,n,e,r,s))}))));break;case BCEvent.ROOM_ERROR:e.on(BCEvent.ROOM_ERROR,(e=>{error$1("bloud sync failed, leave room"),s[BCEvent.NETWORK_ERROR].next(e)}));break;case BCEvent.ROOM_CONNECTED:e.on(BCEvent.ROOM_CONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){return handleRoomConnected(e,n,t,s)}))));break;case BCEvent.JOIN_READY:e.on(BCEvent.JOIN_READY,(()=>handleInitJoinRoomUsers(n)));break;case BCEvent.JOINUSER:e.on(BCEvent.JOINUSER,(o=>__awaiter$2(this,void 0,void 0,(function*(){n.isInWaitRoom||eventQueue.addQueue(handleParticipantJoin.bind(null,o,t,r,e,i,s),BCEvent.JOINUSER)}))));break;case BCEvent.LEAVEUSER:e.on(BCEvent.LEAVEUSER,(o=>{n.isInWaitRoom||eventQueue.addQueue(handleParticipantLeft.bind(null,o,t,n,s,r,e,i),BCEvent.LEAVEUSER)}));break;case BCEvent.LEAVE_USERS:e.on(BCEvent.LEAVE_USERS,(o=>eventQueue.addQueue(handleLeaveUsers.bind(null,o,t,n,s,r,e,i),BCEvent.LEAVE_USERS)));break;case BCEvent.CHANGEMASTER:e.on(BCEvent.CHANGEMASTER,(e=>{eventQueue.addQueue(handleChangeMaster.bind(null,e,t,n,s,r),BCEvent.CHANGEMASTER)}));break;case BCEvent.SENDMESSAGE:e.on(BCEvent.SENDMESSAGE,(e=>{eventQueue.addQueue(handleSendMessage.bind(null,e,t,i,s),BCEvent.SENDMESSAGE)}));break;case BCEvent.CUSTOMMESSAGE:e.on(BCEvent.CUSTOMMESSAGE,(e=>{eventQueue.addQueue(handleCustomMessage.bind(null,e,n,s),BCEvent.CUSTOMMESSAGE)}));break;case BCEvent.EVICTED:e.on(BCEvent.EVICTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleEvict.bind(null,e,t,r,n,s),BCEvent.EVICTED)}))));break;case BCEvent.UPDATEUSER:e.on(BCEvent.UPDATEUSER,(e=>{eventQueue.addQueue(handleUpdateUser.bind(null,e,t,n,r,s),BCEvent.UPDATEUSER)}));break;case BCEvent.UPDATESTATS:e.on(BCEvent.UPDATESTATS,(e=>{eventQueue.addQueue(handleRoomUpdated.bind(null,e,n),BCEvent.UPDATESTATS)}));break;case BCEvent.CUSTOMSTATS:e.on(BCEvent.CUSTOMSTATS,(e=>{eventQueue.addQueue(handleCustomStats.bind(null,e,n,s),BCEvent.CUSTOMSTATS)}));break;case BCEvent.NETWORK_ERROR:e.on(BCEvent.NETWORK_ERROR,(t=>{eventQueue.addQueue(handleBloudError.bind(null,n,e,r,t,s),BCEvent.NETWORK_ERROR)}));break;case BCEvent.USERREJOINED:e.on(BCEvent.USERREJOINED,(e=>{info("bloud user rejoined"),handleUserRejoined(s,BCEvent,e)}));break;case BCEvent.ROOM_RECONNECTING:e.on(BCEvent.ROOM_RECONNECTING,(e=>{eventQueue.addQueue(handleBloudRoomReconnecting.bind(null,e,n,s),BCEvent.ROOM_RECONNECTING)}));break;case BCEvent.ROOM_RECONNECTED:e.on(BCEvent.ROOM_RECONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomReconnected.bind(null,e,n,s),BCEvent.ROOM_RECONNECTED)}))));break;case BCEvent.ROOM_SYNC:e.on(BCEvent.ROOM_SYNC,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomSync.bind(null,e,t,n,r,s),BCEvent.ROOM_SYNC)}))));break;case BCEvent.PUBLISHED:e.on(BCEvent.PUBLISHED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPublished.bind(null,e,r,s),BCEvent.PUBLISHED)}))));break;case BCEvent.UNPUBLISH:e.on(BCEvent.UNPUBLISH,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUnPublished.bind(null,e,r,s),BCEvent.UNPUBLISH)}))));break;case BCEvent.UPDATE_STREAM:e.on(BCEvent.UPDATE_STREAM,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUpdated.bind(null,e,r,s),BCEvent.UPDATE_STREAM)}))));case BCEvent.BLOUD_STREAM_UPDATED:e.on(BCEvent.BLOUD_STREAM_UPDATED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPubAUpdate.bind(null,e,r),BCEvent.BLOUD_STREAM_UPDATED)}))));break;case BCEvent.MOVE_USER_ROOM:e.on(BCEvent.MOVE_USER_ROOM,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleMoveUserRoom.bind(null,n,t,e,s),BCEvent.MOVE_USER_ROOM)}))));break;default:e.on(o,(e=>s[o].next(e)))}})),s}!function(e){e.INIT="init",e.VIDEO_FORCE_CHANGE="video-force-change",e.AUDIO_FORCE_CHANGE="audio-force-change"}(MessageType||(MessageType={}));class BMRoomVM{constructor(e,t,r){this.room=null,this.tipQueueObj={},this.roomInfo=r,this.userVM=t,this.boomCore=e,this.giveLikeList=[],this.giveLikeListWatcher=new Subject}initWithRoom(e){this.room=e}evictUser(e,t){return __awaiter$2(this,void 0,void 0,(function*(){if(!e)return Promise.reject(BmEvictUserError("未传递用户id"));if(!this.userVM.checkLocalHasMaster())return Promise.reject(BmEvictUserError("只有主持人权限才能踢出用户"));if(this.userVM.checkIsMaster(e))return Promise.reject(BmEvictUserError("主持人不能被踢出"));try{yield this.boomCore.evictUser(e,t)}catch(e){return Promise.reject(BmEvictUserError(`踢出用户失败${JSON.stringify(e)}`))}}))}updateUser(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return e?t?void(yield this.boomCore.updateUser(e,{customInfo:t}).catch((e=>Promise.reject(BmUpdateUserError(`boomCore updateUser出错 ${JSON.stringify(e)}`))))):Promise.reject(BmUpdateUserError("info为空,请写入要更新的信息")):Promise.reject(BmUpdateUserError("未传递目标用户id"))}))}changeMaster(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()||(null===(r=this.userVM.getUser(e))||void 0===r?void 0:r.isCreate)?yield this.boomCore.changeMaster(e,t).catch((e=>Promise.reject(BmChangeMasterError(`boomCore changeMaster error ${e}`)))):(console.error("该用户没有管理员权限, 无法改变主持人",LOGGER_TAG_CLIENT,e),Promise.reject(BmChangeMasterError("您没有管理员权限, 无法改变主持人"))):Promise.reject(BmChangeMasterError("未传递主持人id"))}))}updateManager(e,t,r=!0){return __awaiter$2(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()?this.userVM.updateManager(e,t,r):(console.error("该用户没有管理员权限, 无法改变联席主持人",LOGGER_TAG_CLIENT,e),Promise.reject(BmUpdateManagerError("该用户没有管理员权限, 无法改变主持人"))):Promise.reject(BmUpdateManagerError("未传递联席主持人id"))}))}changeNickName(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={nickname:t};yield this.updateUser(e,r)}))}sendMessageWithMaster(e,t){return __awaiter$2(this,void 0,void 0,(function*(){if(!this.userVM.checkLocalHasMaster())return Promise.reject(BmSetRemoteAudioEnable("您不是主持人,没有该权限"));if(t){if(!this.userVM.getUser(t))return Promise.reject(BmSetRemoteAudioEnable(`uid: ${t} 未找到用户`))}try{yield this.boomCore.customMessage(JSON.stringify(e),t)}catch(e){return Promise.reject(e)}}))}setRemoteAudioEnable(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){let i=e?"enabled":"disabled";"enabled"==i&&r&&(i="checkUserAudio");let n={domain:"room-control",method:"audio-force-change",params:{status:i,isNotCancelRootReport:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(n,t).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}setRemoteVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){let r={domain:"room-control",method:"video-force-change",params:{status:e?"enabled":"disabled",fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(BmSetRemoteVideoEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}closeRemoteShare(e){return __awaiter$2(this,void 0,void 0,(function*(){let t={domain:"room-control",method:"close-remote-share",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}tipUser(e,t,r,i){return __awaiter$2(this,void 0,void 0,(function*(){let n={domain:"room-control",method:"tip-user",params:{fromUserId:this.boomCore.getLocalParticipant().getID(),message:t,richMsg:r}};i?this.tipQueueObj[e]=setTimeout((()=>{this.sendMessageWithMaster(n,e)}),60*(i.minutes||0)*1e3+1e3*(i.seconds||0)):this.sendMessageWithMaster(n,e).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${JSON.stringify(e)}`))))}))}raiseHands(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){const i=null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().getID();let n={};"raiseHand"===e?(n.raiseHand=t,n.raiseHandTime=Math.floor((new Date).getTime()/1e3)):n["audio"===e?"raiseHandsAudio":"raiseHandsVideo"]=t,yield this.updateUser(i,n)}))}handleRaiseHands(e,t,r){var i,n,s;return __awaiter$2(this,void 0,void 0,(function*(){let o={domain:"user-control",method:"raise-hands",params:{raiseHandsType:e,raiseHands:t}};try{if(r)yield this.boomCore.customMessage(JSON.stringify(o),r);else{const t=null===(i=this.room)||void 0===i?void 0:i.roomInfo.raiseHandsWatcher.getValue(),r=null===(n=this.room)||void 0===n?void 0:n.roomInfo.raiseVideoHandsWatcher.getValue(),a=null===(s=this.room)||void 0===s?void 0:s.roomInfo.raiseSimpleHandsWatcher.getValue();0===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})),null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),1===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),2===e&&(null==r||r.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),3===e&&(null==a||a.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})))}}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"boomCore.sendMessage发生错误"))}}))}updateCustomStats(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){yield this.boomCore.updateCustomStats(e,t).catch((t=>Promise.reject(updateCustomStatsError(`${JSON.stringify(e)} - ${JSON.stringify(t)}`))))}))}sendChatNotice(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatNotice:e,chatNoticeRich:t,showTipNotice:r}).catch((e=>e))}))}giveLikeEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({giveLikeEnable:e}).catch((e=>e))}))}changeAutoMute(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({autoMute:e})}))}allUserReceiveJoinLeaveMessages(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({allUserReceiveJoinLeaveMessages:e})}))}userJoinMasterVoice(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({userJoinMasterVoice:e})}))}userGiveLike(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){let i=(new Date).getTime(),n={domain:"room-control",method:"give-like",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:i,nickname:this.userVM.localUser.nickName,type:e||1}}},s=this.userVM.getLocalUser();try{yield this.boomCore.customMessage(JSON.stringify(n),void 0),this.giveLikeList.push({userId:null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant().userId,nickName:null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().nickName,time:(new Date).getTime(),type:e}),this.giveLikeListWatcher.next(this.giveLikeList)}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==s?void 0:s.userId),new BoomError$1(CLIENT_BANNED,"用户点赞==>sendMessage出错")}}))}chatEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatEnable:e}).catch((e=>e))}))}joinAudioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinAudioEnable:e}).catch((e=>e))}))}joinVideoEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinVideoEnable:e}).catch((e=>e))}))}userListEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({userListEnable:e}).catch((e=>e))}))}audioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({audioEnable:e}).catch((e=>e))}))}videoEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({videoEnable:e}).catch((e=>e))}))}modifyNameEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({modifyNameEnable:e}).catch((e=>e))}))}backgroundAIEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({backgroundAIEnable:e}).catch((e=>e))}))}forceOpenUserCamera(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserCamera:e}).catch((e=>e))}))}forceOpenUserMic(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserMic:e}).catch((e=>e))}))}joinCueVoice(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCueVoice:e}).catch((e=>e))}))}recordEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({recordEnable:e}).catch((e=>e))}))}raiseHandEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({raiseHandEnable:e}).catch((e=>e))}))}joinMicrophoneDisable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinMicrophoneDisable:e}).catch((e=>e))}))}joinCameraDisable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCameraDisable:e}).catch((e=>e))}))}changeFileUpdateModelPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateModel:e}).catch((e=>e))}))}changeFileUpdateLookPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateLook:e}).catch((e=>e))}))}changeFileUpdateDownPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateDown:e}).catch((e=>e))}))}changeFileUpdateEditPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateEdit:e}).catch((e=>e))}))}changeScreenShareModelPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({screenShareModel:e}).catch((e=>e))}))}changeOnlyOnePersonSharePermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({onlyOnePersonShare:e}).catch((e=>e))}))}setForceOnUser(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOn:{user:e}}).catch((e=>e))}))}updateHostLayout(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){if(this.userVM.checkLocalHasMaster())return this.updateCustomStats({from:{fromTag:"masterId"},hostLayout:e},t);info("您不是主持人,没有该上报权限",LOGGER_TAG_CLIENT)}))}checkDevices(e){return __awaiter$2(this,void 0,void 0,(function*(){const t={domain:"user-control",method:"check-devices",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(BmCheckDeviceError(`检测对方设备send-message发生错误: ${e}`))))}))}resp2CheckDevices(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-check-devices",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};if(!t)return Promise.reject(BmCheckDeviceError(`响应设备检测: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(BmCheckDeviceError(`响应响应设备检测send-message发生错误 ${e}`))}}))}changeRemoteVideoProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-video-profile",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(BmChangeVideoProfileError(`调节对方的视频分辨率send-message发生错误: ${e}`))))}))}resp2ChangeRemoteVideoProfile(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"resp-to-change-video-profile",params:{status:e,profile:r,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(BmChangeVideoProfileError(`响应调节视频分辨率: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(i),t)}catch(e){return Promise.reject(BmChangeVideoProfileError(`响应调节视频分辨率send-message发生错误 ${e}`))}}))}changeRemoteAudioProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"change-audio-profile",params:{microphoneDevice:e.microphoneDevice,speakerDevice:e.speakerDevice,echoCancellation:e.echoCancellation,noiseSuppression:e.noiseSuppression,autoGainControl:e.autoGainControl,speakerVolume:e.speakerVolume,microVolume:e.microVolume,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(r,t).catch((e=>Promise.reject(BmChangeAudioProfileError(`调节音频send-message发生错误 ${JSON.stringify(e)}`))))}))}resp2ChangeRemoteAudioProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-change-audio-profile",params:{status:e,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(BmChangeAudioProfileError(`响应调节音频: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(BmChangeAudioProfileError(`响应调节音频send-message发生错误 ${e}`))}}))}}class BMChatVM{constructor(e,t,r){this.messageList=[],this.hasDangerMessageWatcher=new Subject,this.notificationMessageList=debounce((()=>{this.messageListWatcher.next(this.messageList)}),500),this.boomCore=e,this.userVM=t,this.bmRoom=r,this.messageListWatcher=new BehaviorSubject(this.messageList)}sendMessage(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){let i=e.replace(/(^\s*)|(\s*$)/g,""),n=(new Date).getTime(),s={domain:"room-control",method:"send-talk",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:n,nickname:this.userVM.localUser.nickName},status:i}},o=this.userVM.getLocalUser();try{let e,a=!1,c=r;c||(yield this.boomCore.sendMessage(JSON.stringify(s),t).then((t=>{e=t.seq})).catch((e=>{warn("sendmessage 出错","",null==o?void 0:o.userId,[e]),e&&39===e.code&&(a=!0,this.hasDangerMessageWatcher.next(!0))})));const u=new BMMessageInfo({userId:null==o?void 0:o.userId,message:i,isLocal:null==o?void 0:o.isLocal,avatar:null==o?void 0:o.avatar,nickName:null==o?void 0:o.nickName,sendTime:n,to:t,isDanger:a,seq:e,failed:c});return this.addMessage(u,!1),c?Promise.reject(u):Promise.resolve()}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==o?void 0:o.userId),new BoomError$1(CLIENT_BANNED,"发送聊天消息==>sendMessage出错")}}))}addMessage(e,t){if(!t||this.bmRoom.participantNotice){if(0==this.messageList.length||e.timeStamp-this.messageList[this.messageList.length-1].timeStamp>=notGetTalkInterval){const e=new BMMessageInfo({isMeetingNotice:!0,message:""});this.messageList.push(e)}this.messageList.push(e),this.notificationMessageList()}}updateMessageListWatcher(e){this.messageList=e,this.messageListWatcher.next(this.messageList)}getHistoryMessage(){return __awaiter$2(this,void 0,void 0,(function*(){const e=yield this.boomCore.getMessages(0,this.boomCore.getMsgSeq());let t=[];return e.items.forEach((e=>{if(e.private||e.to)return!1;if(0==e.msg.length||-1==e.msg.indexOf("{"))return!1;const r=JSON.parse(e.msg);if("send-talk"!=r.method)return!1;const i=e.seq;let n=r.params,s=n.stream.user?n.stream.user:e.userId;n.stream.nickname,n.status,(new Date).getTime();const o=new BMMessageInfo({userId:s,message:n.status,nickName:n.stream.nickname,isLocal:s==this.userVM.localUser.userId,avatar:n.stream.avatar,sendTime:n.stream.sendTime,seq:i});t.push(o)})),Promise.resolve(t)}))}}class BMSpeaker{constructor(e,t){this.user=e,this.stream=t}getID(){return this.stream.getStreamId()}getUser(){return this.user}}function getMasterSort(e,t){return 16|~~e<<1|~~t}function getLocalSort(e,t){return 12|~~e<<1|~~t}function getManagerSort(e,t){return 8|~~e<<1|~~t}function getGuestSort(e,t){return 4|~~e<<1|~~t}const namespace=`.streammodel${Math.random()}`;class BMStreamModel{constructor(e,t){this.streamType=STREAM_TYPE.OTHER,this.pullFailedNum=0,this._video_enable=!1,this._audio_enable=!1,this.videoEnableWatcher=new BehaviorSubject(this._video_enable),this.audioEnableWatcher=new BehaviorSubject(this._audio_enable),this.streamUpdateWatcher=new Subject,this.isSubScribedWatcher=new Subject,this.playStateChangeWatcher=new Subject,this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.audioLevelWatcher=new Subject,this.isCurrentDisplay=!1,this.isDisplay=!1,this.isDisplayObserve=new Subject,this.isInBig=!1,this.isInBigObserve=new Subject,this._hasPulled=!1,this.playerId="",this.shouldPull=!1,this._pulledStreamType="small",this.pulledStreamGoal="small",this.bigPlayerId="",this.isPlayingBig=!1,this.muted=!1,this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount=0,this.sortNum=-1,this.handleDisplayChange=e=>{var t;this.isDisplay!==e&&(this.isDisplay=e,null===(t=this.stream)||void 0===t||t.stop(),this.isDisplay||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.pulledStreamType="small"),this.sendMessage2Room())},this.onPlayerStateChange=e=>{var t,r;"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&(info("播放失败, 需要调用 resume 方法"),this.playStateChangeWatcher.next(this)),"PAUSED"!==e.state&&"pause"!==e.reason||(this.player&&(null===(t=this.player)||void 0===t||t.resume()),null===(r=this.stream)||void 0===r||r.resume())},this.handleStreamConnectError=()=>{info("流出现的connect-error userId","",this.userId,["streamId ==>",this.streamId,"nickname =>",this.nickname,"isLocal => ",this.isLocal]),this.isLocal?BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!0}):BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!1})},this.bindElement=e=>{this.playerId=e,this.emitBindElement()},this.bindBigElement=e=>{this.bigPlayerId=e,this.emitBindBigElement()},this.sendMessage2Room=debounce((()=>{BoomEmitter.emitter.emit(RECEIVE_SUBSCRIBE_MESSAGE,{stream:this})}),30),this.emitBindElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_ELEMENT,{stream:this})}),50),this.emitBindBigElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_BIG_ELEMENT,{stream:this})}),50),this.currentIsPlaying=()=>{const e=document.getElementById(this.playerId);let t=!1,r=0;if(e){const i=e.querySelectorAll('div[id^="player_"]');t=i.length>0,i.forEach((e=>{0===e.children.length&&(r+=1)}))}return t&&0>r},this.currentBigIsPlaying=()=>{if(!!!document.getElementById(this.bigPlayerId))return!1;if(this.stream){const e=document.getElementById(`player_${this.stream.getStreamId()}_big_container`);let t=0,r=0;if(e){e.querySelectorAll('div[id^="player_"]').forEach((e=>{0===e.children.length&&(r+=1)}))}return e&&t>r}},this.play=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){var e;const t=this.stream;if(t)if(this.isDisplay&&this.videoEnable){const e=document.getElementById(this.playerId),r=!!e;let i=!1;if(e){const t=e.querySelectorAll('div[id^="player_"]');i=t.length>0,t.forEach((t=>{0===t.children.length&&(t.style.display="none",null==e||e.removeChild(t))}))}if(r)try{t.isPlaying()&&i||(t.stop(),yield t.play(this.playerId,{backgroundColor:"#202020",fit:"contain",audio:!autoPlayAudio}),this.checkSmallVideo()),info("远端流播放结束",this.userId,this.streamId,[this.nickname])}catch(e){t.stop(),setTimeout((()=>{error$1("播放小流失败, 尝试重新播放","播放",this.userId,[this.streamId,this.stream,"error => ",JSON.stringify(e)]),this.play()}),2e3)}else warn("找不到播放器容器","stream play",this.userId,["流 id =>",this.streamId,"nickname =>",this.nickname,"playerId =>",this.playerId]),this.playerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"small"})}else null===(e=this.stream)||void 0===e||e.stop()}))),300),this.playInBig=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){var e,t,r;const i=this.stream;if(i){const n=document.getElementById(this.bigPlayerId);if(n){n.querySelectorAll('div[id^="player_"]').forEach((e=>{0===e.children.length&&(e.style.display="none",null==n||n.removeChild(e))}))}this.isInBig?this.videoEnable?n?(null===(e=this.player)||void 0===e||e.destroy(),this.player=null,this.initBigPlayer(),this.player&&(yield this.player.play(i),this.isPlayingBig=!0,this.checkBigVideo()),info("远端流大流播放结束",this.userId,this.streamId,[this.nickname])):(warn("找不到 bigPlayerId","大流播放",this.userId,["流 id =>",this.streamId]),this.bigPlayerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"big"})):(null===(t=this.player)||void 0===t||t.destroy(),this.player=null,this.isPlayingBig=!1):(null===(r=this.player)||void 0===r||r.destroy(),this.player=null,this.isPlayingBig=!1)}}))),300),this.collectAudioLevel=()=>{this.stream?(this.stream.off("audio-level"+namespace,this.handleAudioLevel),this.stream.on("audio-level"+namespace,this.handleAudioLevel)):warn("collection audio level but not have brtc stream")},this.handleAudioLevel=e=>{this.audioLevelWatcher.next(e)},this.user=e,this.updateUser(e),this._stream=t,this.isDisplayObserve.subscribe((e=>{this.handleDisplayChange(e)})),this.isInBigObserve.subscribe((e=>{this.handleIsInBig(e)})),this.updateSortNum(!1)}get hasPulled(){return this._hasPulled}set hasPulled(e){this._hasPulled=e}get pulledStreamType(){return this._pulledStreamType}set pulledStreamType(e){this._pulledStreamType=e}get uuid(){return this.isShare?`${this.userId}_share`:this.userId}get isAudience(){return this.user.isAudience}get canShow(){return!this.isAudience||(this.audioEnable||this.videoEnable)}changeMute(e){this.muted!==e&&(this.muted=e,this.handleSpeakerChange())}handleSpeakerChange(){var e,t;this.isLocal||(this.muted?null===(e=this.stream)||void 0===e||e.setAudioVolume(0):null===(t=this.stream)||void 0===t||t.setAudioVolume(1))}get isToupingma(){return this.user.isToupingma}get isMixer(){return this.user.isMixer}get isSignal(){return this.user.isSignal}genReceiveSubMsg(){let e=null;return e=this.isDisplay?{audio:!0,video:!0,streamType:"small"}:{audio:!0,video:!1,streamType:"small"},e}handleIsInBig(e){this.isInBig!==e&&(this.isInBig=e,info("isInBig change","",this.userId,["streamId =>",this.streamId,"isInBig => ",e]),this.isInBig?this.pulledStreamGoal="big":this.pulledStreamGoal="small",this.sendMessage2Room(),this.isShare&&(this.isInBig||(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0)))}setVideoEnable(e){this._video_enable!==e&&(this._video_enable=e,this.videoEnableWatcher.next(e))}setAudioEnable(e){this._audio_enable!==e&&(this._audio_enable=e,this.audioEnableWatcher.next(e))}updateStream(e,t=!0,r){if(this._stream&&this._stream.off(namespace),this._stream=e,e){this.streamType=e.type;const i=e.getVideoOn(),n=e.getAudioOn();info("更新用户的流","updateStream",null==e?void 0:e.getUserId(),["nickname =>",this.nickname,"audioOn",n,"videoOn",i,"streamId",e.getStreamId()]),n&&(this.isShare||r.addToDetector(new BMSpeaker(this.user,e)),this.collectAudioLevel()),e.on("player-state-changed"+namespace,this.onPlayerStateChange),e.on("connect-error"+namespace,this.handleStreamConnectError),e.on("stream-connection-error"+namespace,this.handleStreamConnectError),t&&this.sendMessage2Room()}else this.hasPulled=!1,this.pulledStreamType="small",this.streamType=STREAM_TYPE.OTHER}updateBloudStream(e,t,r=!1){var i,n,s,o;let a=!1,c=!1;e?(this.bloudStream={audio:e.audio,video:e.video,isScreen:e.isScreen},e.customInfo&&(this.bloudStream.customInfo&&(null===(i=this.bloudStream.customInfo)||void 0===i?void 0:i.volume)===e.customInfo.volume||Number.isNaN(e.customInfo.volume)||this.setRemoteAudioLevel(e.customInfo.volume),this.bloudStream.customInfo=e.customInfo),this.stream&&(this.bloudStream.audio?this.isShare||(t.addToDetector(new BMSpeaker(this.user,this.stream)),this.collectAudioLevel()):t.removeFromDetector(this.stream.getStreamId())),this.bloudStream.video!==this._video_enable&&(a=!0),this.bloudStream.audio!=this._audio_enable&&(c=!0),this.setVideoEnable(this.bloudStream.video),this.setAudioEnable(this.bloudStream.audio),r&&(null===(n=this.stream)||void 0===n||n.destroy(),this.stream&&(null===(s=t.room.audioPlayer)||void 0===s||s.removeStream(this.stream)),this.updateStream(void 0,!1,t),this._stream=void 0),c&&!this.audioEnable&&this.stream&&(null===(o=t.room.audioPlayer)||void 0===o||o.removeStream(this.stream)),(this.bloudStream.audio||this.bloudStream&&this.isDisplay)&&(!this.stream||r?BoomEmitter.emitter.emit(ADD_PULL_USER,{id:this.userId,isWeb:this.isWeb,isScreen:this.isShare}):(this.isLocal||this.hasPulled&&this.stream.isSubscribed()||this.sendMessage2Room(),a&&this.sendMessage2Room(),!this.isLocal&&c&&this.audioEnable&&this.stream.isSubscribed()&&BoomEmitter.getInstance().emit(ADD_AUDIO_PLAY,{stream:this})))):(this.bloudStream=void 0,this.setVideoEnable(!1),this.setAudioEnable(!1),this.stream&&t.removeFromDetector(this.stream.getStreamId())),this.updateSortNum(!0),this.streamUpdateWatcher.next(!0)}updateBloudCustomInfo(e){var t;this.bloudStream?(this.bloudStream.customInfo&&(null===(t=this.bloudStream.customInfo)||void 0===t?void 0:t.volume)===e.volume||Number.isNaN(e.volume)||this.setRemoteAudioLevel(e.volume),this.bloudStream.customInfo=e):error$1("updateBloudCustomInfo, but bloudStream is undefined","","",["userId =>",this.userId])}get streamId(){return this._stream?this._stream.getStreamId():this.userId}get bStreamId(){return this.isShare?`${this.userId}_screen`:this.userId}get userId(){return this.user.userId}get stream(){return this._stream}get isLocal(){return this.user.isLocal}get isShare(){var e,t,r;return this.stream?this.user.isWeb?null===(t=null===(e=this.stream)||void 0===e?void 0:e.getUserId())||void 0===t?void 0:t.endsWith(STREAM_SUFFIX_SCREEN):!(!this.stream||!this.stream.getType||"assist"!==this.stream.getType()):!!(null===(r=this.bloudStream)||void 0===r?void 0:r.isScreen)}get isWeb(){return this.user.isWeb}get audioEnable(){return this._audio_enable}get videoEnable(){return this._video_enable}get nickname(){var e;return this.user.isToupingma?`${this.user.nickName}(的投屏)`:(null===(e=this.streamId)||void 0===e?void 0:e.includes(STREAM_SUFFIX_SCREEN))?`${this.user.nickName}(的屏幕共享)`:this.user.nickName}get audioLevel(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.getAudioLevel())||0}getUser(){return this.user}setRemoteAudioLevel(e){if(this.isLocal)throw new Error("不能设置本地流的音量");BoomEmitter.emitter.emit(SET_VOLUME,{streamId:this.streamId,volume:e})}getStats(){var e;return null===(e=this._stream)||void 0===e?void 0:e.getStats()}initBigPlayer(){try{if(this.bigPlayerId){const e=document.querySelector(`#${this.bigPlayerId}`);e||console.error("播放大流失败,找不到大流容器",this.userId,this.streamId,this.bigPlayerId),!this.player&&e&&(this.player=new Player(e,{fit:"contain"}),this.player.on("player-state-changed",(e=>{var t;this.stream&&(info("big player state change","","",[JSON.stringify(e)]),"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&this.playStateChangeWatcher.next(this),"PAUSED"===e.state&&(null===(t=this.player)||void 0===t||t.resume()))})))}}catch(e){error$1("初始化大窗口的播放器失败",this.userId,this.streamId,e.message)}}stop(){var e;null===(e=this._stream)||void 0===e||e.stop()}destroy(){var e;null===(e=this._stream)||void 0===e||e.destroy()}isPlaying(){var e;return null===(e=this._stream)||void 0===e?void 0:e.isPlaying()}replay(){var e;return null===(e=this._stream)||void 0===e?void 0:e.replay()}resume(){var e,t;null===(e=this._stream)||void 0===e||e.resume(),null===(t=this.player)||void 0===t||t.resume()}hasAudio(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasAudio())||!1}hasVideo(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasVideo())||!1}updateUser(e){this.user=e;const t=this.user.userInfo.pos;t?t.includes("web")||t.includes("pc")?this.streamType=STREAM_TYPE.SUB_MAIN:t.includes("_toupingma")?this.streamType=STREAM_TYPE.SHARE:this.streamType=STREAM_TYPE.SINGLE:this.streamType=STREAM_TYPE.SINGLE}updateSortNum(e=!0){const t=this.getSortNum();this.setSortNum(t,e)}setSortNum(e,t){this.sortNum!==e&&(this.sortNum=e,t&&(BoomEmitter.emitter.emit(MODEL_SORT_NUM_CHANGE,null),this.user.updateSortNum(!0)))}getSortNum(){return this.user.isMaster?getMasterSort(this.audioEnable,this.videoEnable):this.user.isLocal?getLocalSort(this.audioEnable,this.videoEnable):this.user.isManager?getManagerSort(this.audioEnable,this.videoEnable):getGuestSort(this.audioEnable,this.videoEnable)}checkSmallVideo(){if(this.videoEnable&&this.stream&&!this.isShare){const e=`video_${this.stream.getStreamId()}`;if(!!document.getElementById(e))return void this.checkVideoDecodeFrame(e);error$1("stream is play, but no video element, replay now")}}checkBigVideo(){if(this.videoEnable&&this.stream){const e=`video_${this.stream.getStreamId()}_big`;if(!this.isShare&&this.isDisplay&&this.playerId){const t=!!document.getElementById(e);if(this.isInBig){if(t)return void this.checkVideoDecodeFrame(e);error$1("stream is playing in big, but no video element, replay now"),this.playInBig()}}this.isShare&&this.isInBig&&this.bigPlayerId&&this.checkVideoDecodeFrame(e)}}checkVideoDecodeFrame(e){const t=document.getElementById(e);if(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),!t)return info("黑帧检测没有播放容器",this.userId,"",["streamId =>",this.streamId,"isShare =>",this.isShare,"playerId =>",this.playerId,"bigPlayerId =>",this.bigPlayerId,"isDisplay => ",this.isDisplay,"isInbig =>",this.isInBig]),void(this.isShare&&this.isInBig&&this.bigPlayerId&&(warn("share stream has no video player, retry play"),this.playInBig()));this.checkVideoTimer=setTimeout((()=>{var r,i,n;const s=(null==t?void 0:t.getVideoPlaybackQuality)&&(null===(r=null==t?void 0:t.getVideoPlaybackQuality())||void 0===r?void 0:r.totalVideoFrames)||0;if(!t||t.getVideoPlaybackQuality)return s>0?(clearTimeout(this.checkVideoTimer),void(this.checkFailedCount=0)):this.checkCount>10?(error$1("检测超过了十次,还没有视频流,需要重新拉取","黑帧检测",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname,"videoContainer => ",e]),this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount+=1,void(this.checkFailedCount<=3&&(this.hasPulled=!1,this.pulledStreamType="small",null===(i=this._stream)||void 0===i||i.off(namespace),null===(n=this._stream)||void 0===n||n.destroy(),this._stream=void 0,this.sendMessage2Room()))):(this.checkCount+=1,void this.checkVideoDecodeFrame(e));this.checkVideoTimer&&clearTimeout(this.checkVideoTimer)}),200)}subscribeStream(){this.shouldPull=!0,BoomEmitter.emitter.emit(MANUAL_SUBSCRIPTION,{stream:this})}unSubscribeStream(){this.shouldPull=!1,BoomEmitter.emitter.emit(UNSUBSCRIBE_STREAM,{stream:this})}}function getHTMLMediaStreamOptions(e){let t=null;const r=e.videoElement,i=r.offsetWidth,n=r.offsetHeight;if(r.captureStream?t=r.captureStream():r.mozCaptureStream&&(t=r.mozCaptureStream()),t){const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];return{video:!!e,audio:!!r,videoSource:e,audioSource:r,width:i,height:n}}return null}function getMediaStreamInfo(e,t){try{const r=e.getVideoTracks()[0],i=e.getAudioTracks()[0];return{video:!!r,audio:!!i,videoSource:r,audioSource:i,width:t.width,height:t.height}}catch(e){return console.log("获取共享音频参数有误",e),null}}function transShareScreen2User(e){return e.split("_")[0]}class BMStreamModelVM{constructor(){this.streamModels=new Map,this.streamModelsWatcher=new BehaviorSubject(BMStreamModelVM.filterStreamModels(this.sortStreamModels())),this.shareStreamModels=new Map,this.shareStreamModelsWatcher=new BehaviorSubject(Array.from(this.shareStreamModels.values())),this.localStreamErrorWatcher=new Subject,this.localModel=null,this.room=null,this.bloudStream=null,this.videoStream=null,this.audioStream=null,this.audioStats=!1,this.videoStats=!1,this.localIsShare=!1,this.isShareWatcher=new Subject,this._speaker_enable=!0,this.speakerEnableWatcher=new BehaviorSubject(this._speaker_enable),this.mixStreamModelWatcher=new BehaviorSubject(null),this.canvasTimer=null,this._isRecording=!1,this._slicingRecord=!1,this.isRecordingWatcher=new BehaviorSubject(this._isRecording),this._speaker=null,this._speakers=new Map,this.speakerWatcher=new BehaviorSubject(this._speaker),this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.localStreamConnectErrorWatcher=new Subject,this.localShareError=new Subject,this.shareBloudStateMap=new Map,this.updateModelSort=debounce((()=>{const e=this.sortStreamModels();this.streamModelsWatcher.next(BMStreamModelVM.filterStreamModels(e))}),200,{maxWait:500}),this.handleNoContainer=e=>{const{type:t,container:r,id:i}=e;let n;n="share"===t?this.shareStreamModels.get(i):this.streamModels.get(i),n&&("small"===r?this.noContainerWatcher.next(n):this.noBigContainerWatcher.next(n))},this.getHTMLMediaStream=getHTMLMediaStreamOptions,this.getMediaStream=getMediaStreamInfo,this.createCanvas(),setTimeout((()=>{this.canvasDisplay()}),100),BoomEmitter.emitter.on(MODEL_SORT_NUM_CHANGE,this.updateModelSort),BoomEmitter.emitter.on(NO_CONTAINER,this.handleNoContainer)}static filterStreamModels(e){return e.filter((e=>!e.isToupingma)).filter((e=>!ignoreUserId.some((t=>e.userId.includes(t))))).filter((e=>e.canShow))}initWithRoom(e){return this.room=e,this}setSpeakerEnable(e){var t;this._speaker_enable!==e&&(null===(t=this.room.audioPlayer)||void 0===t||t.mute(!e),this._speaker_enable=e,this.speakerEnableWatcher.next(e))}getStreamModels(){return Array.from(this.streamModels.values())}getStreamModelByUId(e){return this.streamModels.get(e)}getShareStreamModelByUId(e){return this.shareStreamModels.get(e)}getLocalStreamModel(){return this.localModel}createStreamModel(e,t){const r=new BMStreamModel(e,void 0);return t&&r.updateStream(t,!0,this),r.isShare?(e.addStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`,r),this.addShareStreamModel(r)):(e.addStream(e.userId,r),this.addStreamModel(r)),r}addStreamModel(e){e&&(e.isLocal?this.localModel||(this.localModel=e,this.streamModels.set(this.localModel.userId,this.localModel)):this.streamModels.set(e.userId,e))}addShareStreamModel(e){e&&(e.isLocal||(this.shareStreamModels.set(e.userId,e),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))))}removeStreamModel(e){if(!e)return;const t=e.getUser();this.streamModels.delete(e.userId),t.removeStream(e.userId)}removeShareStreamModelByUId(e){var t,r,i,n;const s=this.shareStreamModels.get(e);s&&(null===(t=s.stream)||void 0===t||t.stop(),null===(r=s.stream)||void 0===r||r.destroy(),s.audioEnable&&s.stream&&(null===(n=null===(i=this.room)||void 0===i?void 0:i.audioPlayer)||void 0===n||n.removeStream(s.stream)),this.removeShareStreamModel(s))}removeShareStreamModel(e){if(!e)return;const t=e.getUser();this.shareStreamModels.delete(e.userId),t.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`),t.updateSortNum(!0),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}removeStreamModelByUId(e){var t,r,i;const n=this.getStreamModelByUId(e);return n&&(n.stream&&(this.removeFromDetector(n.streamId),n.stream.stop(),n.stream.destroy()),n.audioEnable&&(n.stream?null===(r=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===r||r.removeStream(n.stream):null===(i=this.room)||void 0===i||i.audioPlayer.removeStreamByUid(e)),this.removeStreamModel(n)),n}remoteStreamPublished(e){const t=e.getStreamId(),r=e.getUserId();let i,n=this.getStreamModelByUId(r);if(n||(i=transShareScreen2User(String(r)),n=this.getStreamModelByUId(i)),n){if(isShareStream(e)){let t;if(i&&(t=this.shareStreamModels.get(i)),t){if(t.isLocal)return;t.hasPulled=!1,t.pulledStreamType="small",t.updateStream(e,!0,this),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}else{const t=this.createStreamModel(n.getUser(),e),r=e.getVideoOn(),i=e.getAudioOn(),s=this.shareBloudStateMap.get(n.userId);s?t.updateBloudStream({audio:s.audio,video:s.video,isScreen:!0,customInfo:s.customInfo},this):t.updateBloudStream({audio:i,video:r,isScreen:!0},this),t.streamType=STREAM_TYPE.SHARE}}else n.hasPulled=!1,n.pulledStreamType="small",this.updateStreamModel(n,e);n.getUser().isMixer&&this.mixStreamModelWatcher.next(n),this.changeSingleStreamSpeaker(n).catch((e=>{error$1("设置单股流的扬声器的播放出现了问题","设置播放音量",null==n?void 0:n.userId)}))}else error$1("brtc有人推流了,但是找不到对应的streamModel, 找不到对应的用户","",r,["streamId => ",t,"type =>",e.getType&&e.getType()])}remoteStreamUnpublished(e){var t,r,i;let n;const s=e.getUserId(),o=e.getStreamId();let a=!1;if(s.includes(STREAM_SUFFIX_SCREEN)){const e=transShareScreen2User(String(s));if(e==(null===(r=null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant())||void 0===r?void 0:r.userId))return info("本地用户取消共享屏幕","取消共享屏幕",s),void this.localModel.getUser().removeStream(s);n=this.getShareStreamModelByUId(e),a=!0}else o.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()?(n=this.getShareStreamModelByUId(s),a=!0):n=this.getStreamModelByUId(s);if(this.removeFromDetector(o),this.removeFromRecorder(e),!n)return void error$1("brtc有人取消推流 但是找不到对应的streamModel","取消推流",s,[o]);const c=null===(i=n.stream)||void 0===i?void 0:i.getStreamId();if(c===o)return n.hasPulled=!1,n.pulledStreamType="small",a||n.streamType===STREAM_TYPE.SHARE?(this.removeShareStreamModel(n),void n.updateStream(void 0,!0,this)):(n.updateStream(void 0,!0,this),n);error$1("当前取消推流的和当前绑定的不是同一股流","",s,["streamId =>",o,"streamModel.streamId",c])}sortStreamModels(){return sortStreamModels(Array.from(this.streamModels.values()))}updateStreamModel(e,t){e.updateStream(t,!0,this)}updateShareStreamModel(e,t){e.updateStream(t,!0,this)}setLocalVideoEnable(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){if(!(null===(r=this.room)||void 0===r?void 0:r.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地摄像头,不与响应");if(!this.room.mediaPermission.camera)return Promise.reject(BMCameraNotAuthError());const i=this.getLocalStreamModel();if(info(`开关本地摄像头, 状态 => ${e}`,"本地用户",null==i?void 0:i.userId),i)if(e)if(null==i?void 0:i.stream){if(t)yield i.stream.replaceTrack(t).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}));else{if("CanvasCaptureMediaStreamTrack"===i.stream.getVideoTrack().constructor.name){const e=yield this.createVideoStream().catch((e=>Promise.reject(e)));yield i.stream.replaceTrack(e).then((()=>{info("replace video track success")})).catch((e=>(error$1("本地视频流更换视频流失败","","",JSON.stringify(e)),this.handleStreamUpdateFailed(),Promise.reject(BMOpenCameraError()))))}}if(!(yield i.stream.unmuteVideo()))return error$1("brtc unmuteVideo失败"),this.handleStreamUpdateFailed(),Promise.reject(BMOpenCameraError());info("brtc unmute video success"),yield this.bloudStream.setVideoEnabled(!0).then((()=>{i.updateStream(i.stream,!0,this),i.updateBloudStream({video:!0,audio:i.audioEnable,isScreen:!1},this),i.playInBig()})).catch((e=>{error$1("bloud unmuteVideo失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!1,!0,i,t).catch((e=>{var t,r,i,n,s;return error$1("开启本地摄像头失败","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));else{i.stream&&(yield this.muteOrUnpublishStream("video",!0,i).catch((e=>(error$1("关闭本地摄像头失败","","",[e]),Promise.reject(BmSetLocalVideoEnable(e))))))}}))}handleStreamUpdateFailed(){return __awaiter$2(this,void 0,void 0,(function*(){error$1("brtc unmute stream failed, now unpublish"),yield this.unpublishStream()}))}setLocalAudioEnable(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(!(null===(t=this.room)||void 0===t?void 0:t.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地麦克风,不与响应");if(!this.room.mediaPermission.microphone)return Promise.reject(BMMicNotAuthError());const r=this.getLocalStreamModel();if(info(`开关本地麦克风, 状态 => ${e}`,"本地用户",null==r?void 0:r.userId),r)if(e){if(null==r?void 0:r.stream){const e=yield r.stream.unmuteAudio();if(info(`unmute local stream audio res : ${e}`),!e)return error$1("brtc unmuteAudio失败","本地用户",""),yield this.handleStreamUpdateFailed(),Promise.reject(BMOpenMicroError());info("unmute audio success"),yield this.bloudStream.setAudioEnabled(!0).then((()=>{info("bloud stream set audio enable"),r.updateStream(r.stream,!1,this),r.updateBloudStream({audio:!0,video:r.videoEnable,isScreen:!1},this)})).catch((e=>{error$1("bloud unmuteAudio失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!0,!1,r).catch((e=>{var t,r,i,n,s;return error$1("开启本地麦克风失败","","",[e]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));(null==r?void 0:r.stream)&&this.addToRecorder(null==r?void 0:r.stream)}else{const e=r.stream;if(e){this.removeFromRecorder(e),this.removeFromDetector(e.getStreamId());try{yield this.muteOrUnpublishStream("audio",!0,r)}catch(e){return error$1("关闭本地麦克风失败","","",[JSON.stringify(e)]),Promise.reject(BmSetLocalAudioEnable(e))}}}}))}joinWithAudioAndAudio(e,t){return __awaiter$2(this,void 0,void 0,(function*(){info("join with audio and video","join publish","",[e,t]);const r=this.getLocalStreamModel();r&&(yield this.createStreamAndPublish(e,t,r).catch((e=>{var t,r,i,n,s;return error$1("join create and publish failed","","",[JSON.stringify(e)]),null===(r=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===r||r.destroy(),(null===(i=this.bloudStream)||void 0===i?void 0:i.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)})))}))}changeSpeaker(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){if(info("change speaker","","",[JSON.stringify(e)]),!e.deviceId)throw new BoomError(LOCAL_ERROR,"切换扬声器失败!,原因: 选择的设备没有deviceId"+(null==e?void 0:e.name));try{this.room.setSelectSpeakerDevice(e),null===(r=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===r||r.setDevice(e.deviceId)}catch(e){throw error$1("切换扬声器失败","","",["error",null==e?void 0:e.message,JSON.stringify(e)]),new BoomError(LOCAL_ERROR,"切换扬声器失败")}}))}changeSingleStreamSpeaker(e){return __awaiter$2(this,void 0,void 0,(function*(){const t=this.room.selectAudioOutputDevice;t&&(e.isLocal||e.stream&&(yield e.stream.setAudioOutput(t.deviceId)))}))}changeAudioInput(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){info("change audio input device","","",[JSON.stringify(e)]);const i=null===(t=this.localModel)||void 0===t?void 0:t.stream;null===(r=this.room)||void 0===r||r.setSelectAudioDevice(e),i&&(this.removeFromRecorder(i),yield i.switchDevice("audio",e.deviceId),this.addToRecorder(i))}))}changeVideoInput(e){var t,r,i;return __awaiter$2(this,void 0,void 0,(function*(){info("change video input device","","",[JSON.stringify(e)]);const n=null===(t=this.localModel)||void 0===t?void 0:t.stream;null===(r=this.room)||void 0===r||r.setSelectVideoDevice(e),n&&(yield n.switchDevice("video",e.deviceId),(null===(i=this.localModel)||void 0===i?void 0:i.isDisplay)&&this.localModel.isInBig&&this.localModel.playInBig())}))}muteSpeaker(e){return __awaiter$2(this,void 0,void 0,(function*(){info("静音扬声器 状态 =>","","",["status =>",e]);try{this.setSpeakerEnable(e)}catch(t){return Promise.reject(BmSetLocalSpeakerEnable(`开关扬声器失败 ${e} error: ${JSON.stringify(t)}`))}}))}createLocalAudioStream(){var e;return __awaiter$2(this,void 0,void 0,(function*(){this.room.mediaPermission.microphone?(yield this.room.initDevices(),this.room.audioDevices.length?(null===(e=this.audioStream)||void 0===e||e.destroy(),this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},this.localModel.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e))))):error$1("there is no audio device exists")):error$1("there is no microphone permission")}))}createStreamAndPublish(e,t,r,i){var n,s,o,a,c,u,d,l;return __awaiter$2(this,void 0,void 0,(function*(){let h=BMStreamModelVM.getCanvasStream();if(yield this.room.initDevices(),t)null===(a=this.brtcStream)||void 0===a||a.destroy(),(null===(c=this.room)||void 0===c?void 0:c.audioDevices.length)||(error$1("当前电脑中没有音频输入设备,重新获取"),yield null===(u=this.room)||void 0===u?void 0:u.initDevices()),(null===(d=this.room)||void 0===d?void 0:d.videoDevices.length)||(error$1("当前电脑中没有视频输入设备, 重新获取"),yield null===(l=this.room)||void 0===l?void 0:l.initDevices()),this.room.audioDevices.length>0?this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:this.room.mediaPermission.microphone},r.userId).catch((e=>(error$1("create brtc audio and video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))):(error$1("没有音频输入设备,只能创建视频流"),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!1},r.userId).catch((e=>(error$1("create brtc video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))));else{const e=h.getVideoTracks()[0];this.audioStream||(this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},r.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e)))));const t=null===(n=this.audioStream)||void 0===n?void 0:n.getAudioTrack();if(!t||t&&t.muted)throw null===(s=this.audioStream)||void 0===s||s.destroy(),this.audioStream=null,this.localStreamErrorWatcher.next("audio"),error$1("麦克风设备不可用","","",["muted => ?",null==t?void 0:t.muted]),getStreamError("麦克风");null===(o=this.brtcStream)||void 0===o||o.destroy(),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!0,videoSource:e,audioSource:t},r.userId).catch((e=>Promise.reject(e)))}this.brtcStream&&(t||(yield this.brtcStream.muteVideo()),e||(yield this.brtcStream.muteAudio()),i&&(yield this.brtcStream.replaceTrack(i).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}))),yield this.room.publish(this.brtcStream).catch((e=>{var t,r;return null===(t=this.brtcStream)||void 0===t||t.destroy(),null===(r=this.localModel)||void 0===r||r.updateBloudStream(void 0,this),Promise.reject(e)})),this.brtcStream.on("video-track-mute",this.muteHandler.bind(this,"video")),this.brtcStream.on("video-track-ended",this.muteHandler.bind(this,"video")),this.brtcStream.on("audio-track-mute",this.muteHandler.bind(this,"audio")),this.brtcStream.on("audio-track-ended",this.muteHandler.bind(this,"audio")),yield this.publishBloudStream(e,t))}))}publishBloudStream(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){const i=this.localModel.userId;this.bloudStream=this.room.boomCore.creteBloudLocalStream({audio_enable:e,video_enable:t},i),yield this.bloudStream.publish({video_enable:t,audio_enable:e}),null===(r=this.localModel)||void 0===r||r.updateBloudStream({video:t,audio:e,isScreen:!1},this)}))}muteHandler(e){var t,r,i,n,s,o;return __awaiter$2(this,void 0,void 0,(function*(){this.localStreamConnectErrorWatcher.next(BMStreamDisconnectedError("video"===e?"摄像头":"麦克风"));error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",null===(t=this.localModel)||void 0===t?void 0:t.videoEnable,"audioEnable",null===(r=this.localModel)||void 0===r?void 0:r.audioEnable,"type",e]);const a=()=>__awaiter$2(this,void 0,void 0,(function*(){var e,t,r,i,n,s,o,a;(null===(e=this.localModel)||void 0===e?void 0:e.stream)&&(yield null===(t=this.room)||void 0===t?void 0:t.boomCore.unpublish(this.localModel.stream)),null===(i=null===(r=this.localModel)||void 0===r?void 0:r.stream)||void 0===i||i.destroy(),null===(n=this.audioStream)||void 0===n||n.destroy(),null===(s=this.videoStream)||void 0===s||s.destroy(),this.audioStream=null,this.videoStream=null,null===(o=this.localModel)||void 0===o||o.updateStream(void 0,!0,this),yield this.bloudStream.unpublish(),this.bloudStream=null,null===(a=this.localModel)||void 0===a||a.updateBloudStream(void 0,this)}));if(null===(i=this.localModel)||void 0===i?void 0:i.stream)if("video"===e)info("video track has problem, now unpublish"),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),yield a();else{null===(n=this.audioStream)||void 0===n||n.destroy(),this.audioStream=null,this.audioStream=yield null===(s=this.room)||void 0===s?void 0:s.createPBSingleLocalStream({video:!1,audio:!0});const e=null===(o=this.audioStream)||void 0===o?void 0:o.getAudioTrack();e&&!e.muted?this.localModel.stream&&(yield this.localModel.stream.replaceTrack(e).catch((e=>{error$1("本地流出现异常, 重新创建audio stream replace 失败","本地流出现异常","",[JSON.stringify(e)]),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),a()}))):(error$1("recreate audio stream failed, now unpub"),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),a())}this.localStreamErrorWatcher.next(e)}))}unpublishStream(){var e,t,r,i;return __awaiter$2(this,void 0,void 0,(function*(){info("unpublish stream");const n=this.getLocalStreamModel();if(n){const s=n.stream;s&&(yield null===(e=this.room)||void 0===e?void 0:e.unpublish(s).catch((e=>{error$1("brtc 取消发布失败","取消推流",n.userId,[JSON.stringify(e)])})));try{this.removeFromRecorder(s),null==s||s.destroy(),null===(t=this.videoStream)||void 0===t||t.destroy(),null===(r=this.audioStream)||void 0===r||r.destroy(),null===(i=this.brtcStream)||void 0===i||i.destroy(),this.videoStream=null,this.audioStream=null,this.brtcStream=void 0,n.updateStream(void 0,!0,this),yield this.bloudStream.unpublish().catch((e=>{error$1("bloud unpublish stream failed","bloud unpublish stream",n.userId,[JSON.stringify(e),null==e?void 0:e.code,null==e?void 0:e.message])})),n.updateBloudStream(void 0,this),this.bloudStream=null}catch(e){error$1("stream destroy failed","取消推流",n.userId,[JSON.stringify(e)])}}}))}muteOrUnpublishStream(e,t,r){var i;return __awaiter$2(this,void 0,void 0,(function*(){const t=r.stream;let n=!0;if("audio"===e?n=t.getVideoOn():"video"===e&&(n=t.getAudioOn()),n){if("audio"===e){(yield t.muteAudio())||error$1("brtc muteAudio失败","关闭本地音频","本地"),yield this.bloudStream.setAudioEnabled(!1).catch((e=>{error$1("bloud setAudioEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({audio:!1,video:!0,isScreen:!1},this)}else if("video"===e){const e=BMStreamModelVM.getCanvasStream().getVideoTracks()[0];try{yield t.replaceTrack(e),yield t.muteVideo()}catch(e){error$1("关闭本地视频失败","关闭本地视频","本地",[JSON.stringify(e)])}try{null===(i=this.videoStream)||void 0===i||i.destroy(),this.videoStream=null}catch(e){error$1("this.videoStream destroy failed")}yield this.bloudStream.setVideoEnabled(!1).catch((e=>{error$1("bloud setVideoEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),r.updateBloudStream({video:!1,audio:!0,isScreen:!1},this)}}else yield this.unpublishStream()}))}toggleShareScreen(e,t,r){var i,n,s,o,a;return __awaiter$2(this,void 0,void 0,(function*(){return info("开关共享屏幕","","开关共享屏幕",["stats => ",e]),!e&&(null===(i=this.room)||void 0===i?void 0:i.boomCore.shareScreenStream)&&this.removeFromRecorder(null===(n=this.room)||void 0===n?void 0:n.boomCore.shareScreenStream),yield null===(s=this.room)||void 0===s?void 0:s.boomCore.toggleShareScreen(e,t,r).then((()=>{var r;if(info("bmStreamVm toggleShareScreen success","切换共享屏幕","",["enable =>",e,"options =>",JSON.stringify(t)]),e){const e=null===(r=this.room)||void 0===r?void 0:r.boomCore.shareScreenStream;e&&this.remoteStreamPublished(e)}else this.localModel.getUser().removeStream(`${this.localModel.userId}_screen`),this.localModel.getUser().updateSortNum(!0)})).catch((r=>(error$1("bmStreamVm toggleShareScreen error","切换共享屏幕","",["enable =>",e,"options =>",t]),Promise.reject(r)))),e&&(null===(o=this.room)||void 0===o?void 0:o.boomCore.shareScreenStream)&&this.addToRecorder(null===(a=this.room)||void 0===a?void 0:a.boomCore.shareScreenStream),this.localIsShare=e,this.isShareWatcher.next(e),Promise.resolve(!0)}))}setShareScreenContentHint(e){var t;null===(t=this.room)||void 0===t||t.boomCore.setShareScreenContentHint(e)}createCanvas(){const e=document.createElement("canvas");e.id="tarCanvas",e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.bottom="0",document.body.appendChild(e)}canvasDisplay(){let e=document.getElementById("tarCanvas");if(e){e.width=640,e.height=360;let t=e.getContext("2d");t.fill(),t.beginPath(),t.fillStyle="rgb(0,0,0)",t.fillRect(0,0,e.width,e.height),this.canvasTimer&&clearTimeout(this.canvasTimer),this.canvasTimer=setTimeout((()=>{this.canvasDisplay()}),1e3)}}static getCanvasStream(){return document.getElementById("tarCanvas").captureStream()}createVideoStream(){var e,t,r;return __awaiter$2(this,void 0,void 0,(function*(){return yield this.room.initDevices(),null===(e=this.videoStream)||void 0===e||e.destroy(),this.videoStream=yield this.room.createPBSingleLocalStream({video:!0,audio:!1},this.localModel.userId).catch((e=>Promise.reject(BMCreateStreamError("视频")))),null===(t=this.videoStream)||void 0===t||t.on("video-track-mute",this.muteHandler.bind(this,"video")),null===(r=this.videoStream)||void 0===r||r.on("video-track-ended",this.muteHandler.bind(this,"video")),this.videoStream.getVideoTrack()}))}startRecord(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(this._recorder)return;this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(e),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended")})),this._recorder.on("started",(()=>{info("record started.")}));let r=!0;try{yield this._recorder.start(),this._isRecording=!0,this.isRecordingWatcher.next(!0),this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),r=!1,yield t.stop()}return r}))}addToRecorder(e){this._isRecording&&!this._slicingRecord&&(e.on("audio-track-ended",(()=>{this.removeFromRecorder(e)})),this._recorder.addStream(e))}removeFromRecorder(e){this._isRecording&&!this._slicingRecord&&this._recorder.removeStream(e)}stopRecord(){return __awaiter$2(this,void 0,void 0,(function*(){this._recorder&&(this._isRecording=!1,this.isRecordingWatcher.next(!1),yield this._recorder.stop(),this._recorder=void 0)}))}sliceRecord(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(!this._isRecording)return;let r=this._recorder._opts;this._slicingRecord=!0;try{yield this._recorder.stop()}catch(e){error$1("stop record exception","","",[JSON.stringify(e)])}r.filename=e,this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(r),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended.")})),this._recorder.on("started",(()=>{info("record started.")}));let i=!0;try{yield this._recorder.start(),this._slicingRecord=!1,this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),this._slicingRecord=!1,i=!1,yield t.stop()}return i}))}startSpeakerDetector(){var e;this._speaker=null,this._speakerDetector=null===(e=this.room)||void 0===e?void 0:e.boomCore.createSpeakerDetector(),this._speakerDetector.on("speaker",(e=>{var t,r,i;let n=!0;e?((null===(t=this._speaker)||void 0===t?void 0:t.getUserInfo().userId)===e.getUser().userId&&(n=!1),this._speaker=e.getUser()):(this._speaker||(n=!1),this._speaker=null),n&&(info("当前讲话人","语音激励",null===(r=this._speaker)||void 0===r?void 0:r.userId,["nickname => ",null===(i=this._speaker)||void 0===i?void 0:i.nickname]),this.speakerWatcher.next(this._speaker))}))}addToDetector(e){this._speakers.set(e.getID(),e),this._speakerDetector&&this._speakerDetector.addStream(e)}removeFromDetector(e){let t=this._speakers.get(e);this._speakerDetector&&t&&(this._speakers.delete(e),this._speakerDetector.removeStream(t))}shareCustomMedia(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){return null===(r=this.room)||void 0===r?void 0:r.boomCore.shareHTMLMedia(e,t)}))}updateBloudStreamCustomStats(e,t,r){var i;return null===(i=this.room)||void 0===i?void 0:i.boomCore.updateStream(e,t,r)}clearCache(){var e,t,r,i,n;null===(t=null===(e=this.localModel)||void 0===e?void 0:e.stream)||void 0===t||t.destroy(),null===(r=this.videoStream)||void 0===r||r.destroy(),null===(i=this.audioStream)||void 0===i||i.destroy(),this.streamModels.clear(),this.shareStreamModels.clear(),null===(n=this.room)||void 0===n||n.userVM.clearUsers(),this.shareBloudStateMap.clear()}}class BMRoomInfo{constructor(){this.room=null,this._roomName="",this.msgSeq="",this.roomID="",this.audioOff=!1,this.selfopenaudio=!1,this.lock=!1,this.leaveNotice=!1,this.openSelf=!1,this.chatNotice="",this.chatNoticeRich="",this.raiseHandsList=new Map,this.raiseHandsWatcher=new BehaviorSubject(Array.from(this.raiseHandsList.values())),this.raiseVideoHandsList=new Map,this.raiseVideoHandsWatcher=new BehaviorSubject(Array.from(this.raiseVideoHandsList.values())),this.raiseSimpleHandsList=new Map,this.raiseSimpleHandsWatcher=new BehaviorSubject(Array.from(this.raiseSimpleHandsList.values())),this.operationPermissionWatcher=new Subject,this.chatNoticeWatcher=new Subject,this.totalUserWatcher=new BehaviorSubject(0),this.totalWaitRoomUserWatcher=new BehaviorSubject(0),this.isOpenWaitRoom=new Subject,this.audioOffWatcher=new Subject,this.lockWatcher=new BehaviorSubject(this.lock),this.leaveNoticeWatcher=new BehaviorSubject(this.leaveNotice),this.openSelfWatcher=new BehaviorSubject(this.openSelf),this.setRaiseHandsWatcherValue=debounce((()=>{this.raiseHandsWatcher.next(Array.from(this.raiseHandsList.values()))}),1e3),this.setVideoRaiseHandsWatcherValue=debounce((()=>{this.raiseVideoHandsWatcher.next(Array.from(this.raiseVideoHandsList.values()))}),1e3),this.setSimpleRaiseHandsWatcherValue=debounce((()=>{this.raiseSimpleHandsWatcher.next(Array.from(this.raiseSimpleHandsList.values()))}),1e3),BoomEmitter.emitter.on(RAISE_HAND,(e=>{"raiseHandsAudio"===e.status?e.user.raiseAudioHands?this.addRaiseHandUser(e.user):this.removeRaiseHandUser(e.user.userId):"raiseHandsVideo"===e.status?e.user.raiseVideoHands?this.addVideoRaiseHandUser(e.user):this.removeVideoRaiseHandUser(e.user.userId):"raiseHand"===e.status&&(e.user.raiseHand?this.addSimpleRaiseHandUser(e.user):this.removeSimpleRaiseHandUser(e.user.userId))}))}get roomName(){return this._roomName||(this._roomName=this.room.getName()),this._roomName}get isBigRoom(){return this.room.isBig}setup(e){this.roomID=e.room,this.handleInitParams()}bindRoom(e){this.room=e}initCustomStats(e){this.operationPermission=e,void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}updateOperationPermission(e){this.operationPermission=Object.assign(Object.assign({},this.operationPermission),e),void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}handleInitParams(){const e=this.room.boomCore.getAudioOff(),t=this.room.boomCore.getSelfOpenAudio();this.setAudioOff(e,t)}setAudioOff(e,t){this.audioOff=e,this.selfopenaudio=t,this.audioOffWatcher.next({audioOff:e,selfopenaudio:t})}setlock(e){this.lock=e,this.lockWatcher.next(e)}setLeaveNotice(e){this.leaveNotice=e,this.leaveNoticeWatcher.next(e)}setRaiseHandsList(e){e.forEach((e=>{e.raiseAudioHands&&this.raiseHandsList.set(e.getID(),e),e.raiseVideoHands&&this.raiseVideoHandsList.set(e.getID(),e),e.raiseHand&&this.raiseSimpleHandsList.set(e.getID(),e)})),this.setRaiseHandsWatcherValue(),this.setVideoRaiseHandsWatcherValue(),this.setSimpleRaiseHandsWatcherValue()}addRaiseHandUser(e){this.raiseHandsList.set(e.getID(),e),this.setRaiseHandsWatcherValue()}removeRaiseHandUser(e){this.raiseHandsList.delete(e),this.setRaiseHandsWatcherValue()}addVideoRaiseHandUser(e){this.raiseVideoHandsList.set(e.getID(),e),this.setVideoRaiseHandsWatcherValue()}removeVideoRaiseHandUser(e){this.raiseVideoHandsList.delete(e),this.setVideoRaiseHandsWatcherValue()}addSimpleRaiseHandUser(e){this.raiseSimpleHandsList.set(e.getID(),e),this.setSimpleRaiseHandsWatcherValue()}removeSimpleRaiseHandUser(e){this.raiseSimpleHandsList.delete(e),this.setSimpleRaiseHandsWatcherValue()}}var name="@hysc/meeting",version="5.0.93",description="boom meeting",main="umd/index.js",module$1="esm/index.js",types="esm/index.d.ts",scripts={dev:"tsc --watch",build:"tsc",docs:"rimraf docs && typedoc"},keywords=[],files=["esm","umd"],author="yangliye",license="MIT",dependencies={"@hysc/bloud":"workspace:*","@hysc/core":"workspace:*","@hysc/logger":"workspace:*","lodash-es":"^4.17.21",mitt:"^3.0.0","@hysc/p-queue":"6.3.0",rxjs:"^7.5.5",typescript:"^4.6.3","@hysc/utils":"workspace:*"},peerDependencies={"@hysc/core":"workspace:*"},devDependencies={"@types/lodash-es":"^4.17.6"},PackageJson={name:name,version:version,description:description,main:main,module:module$1,types:types,private:!1,scripts:scripts,keywords:keywords,files:files,author:author,license:license,dependencies:dependencies,peerDependencies:peerDependencies,devDependencies:devDependencies};function formatLog(e,t,r,i){let n=[];return r&&n.push(r),i&&n.push(i),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}var LOGLEVEL=(e=>(e[e.INFO=0]="INFO",e[e.WARN=1]="WARN",e[e.ERROR=2]="ERROR",e[e.CLOSE=3]="CLOSE",e))(LOGLEVEL||{});const _Logger=class{static setEnableUpload(e){_Logger.enableUpload=e}static setLogLevel(e){_Logger.logLevel=e}static setNamespace(e){_Logger.namespace=e}static info(e,t,r,i=[]){_Logger.logLevel<=0&&(i.unshift(formatLog("INFO",e,t,r)),console.info(...i))}static warn(e,t,r,i=[]){_Logger.logLevel<=1&&(i.unshift(formatLog("WARN",e,t,r)),console.warn(...i))}static error(e,t,r,i=[]){_Logger.logLevel<=2&&(i.unshift(formatLog("ERROR",e,t,r)),console.error(...i))}};let Logger=_Logger;Logger.enableUpload=!1,Logger.logLevel=0,Logger.namespace="boom-core";class BMLiveVM{constructor(e){this.room=e}get localBMUser(){return this.room.getLocalParticipant()}get localIsAudience(){return this.room.getLocalParticipant().isAudience}handlePull(e){return __awaiter$2(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePull(e)):yield this.room.handlePull(e)}))}handleChangeStreamType(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.room.handleChangeStreamType(e)}))}handlePlay(e,t){return __awaiter$2(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePlay(e,t,!1)):yield this.room.handlePlay(e,t,!0)}))}handleAudienceDisable(){return __awaiter$2(this,void 0,void 0,(function*(){this.room.bmStreamVm.getStreamModels().forEach((e=>{var t;(null===(t=null==e?void 0:e.stream)||void 0===t?void 0:t.isSubscribed())&&e.hasPulled&&(e.hasPulled=!1,e.pulledStreamType="small",this.room.unsubscribe(e.stream).then((()=>{console.log("观众取消订阅这股流",e.userId,e.nickname,e.isDisplay,e.isCurrentDisplay)})))}));const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1))}))}handleAudienceEnable(){return __awaiter$2(this,void 0,void 0,(function*(){const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1)),this.room.bmStreamVm.getStreamModels().forEach((e=>{streamPullQueue.addQueue(this.room.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}))}))}}function addBrtcNetEvent(e){var t,r;null===(t=e.brtcClient.client)||void 0===t||t.signal.channel.on("reconnecting",(()=>e.fire(BCEvent$1.BRTC_ROOM_ROCONNECTING))),null===(r=e.brtcClient.client)||void 0===r||r.signal.channel.on("reconnected",(()=>e.fire(BCEvent$1.BRTC_ROOM_RECONNECTED)))}class SingletonQueue{constructor(){return this.pullMap=new Map,SingletonQueue.instance?SingletonQueue.instance:(SingletonQueue.instance=this,this)}addUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.set(`${e.id}_screen`,e):this.pullMap.set(e.id,e)})),this._callback&&this._callback(this.pullMap)}removeUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.delete(`${e.id}_screen`):this.pullMap.delete(e.id)}))}restart(){if(!this._callback)throw error$1("no callback exists in streamQueue please setQueueProcessor first!"),new Error("no callback");this._callback(this.pullMap)}setQueueProcessor(e){this._callback=e}removeQueueProcessor(){this._callback=void 0}}class AudioPlay{constructor(e,t){this.playMap=new WeakSet,this.playerMap=new Map,this.muted=!1,this.playStateChangeWatcher=new Subject;const r=document.getElementById(e);if(!r)throw new Error("no container found, play failed");this.container=r,this.room=t}addStream(e){if(this.room.shouldPlayAudio&&this.room.autoPlayAudio)if(this.playMap.has(e)){warn("stream is playing, replay",e.getUserId());const t=this.playerMap.get(e.getStreamId());t&&t.replay(e)}else info("add stream to player","",e.getUserId(),["streamId ",e.getStreamId()]),this.playMap.add(e),this.play(e)}removeStream(e){const t=e.getStreamId();let r=this.playerMap.get(t);r&&(r.off(),r.destroy()),info("remove audio player","","",["streamId =>",t]),this.playerMap.delete(t),this.playMap.delete(e)}removeStreamByUid(e){let t=new Map;this.playerMap.forEach((r=>{isShareStream(r.stream)||r.stream.getUserId()===e&&t.set(r.stream.getStreamId(),r)})),t.forEach(((e,t)=>{e.off(),e.destroy(),this.playerMap.delete(t),this.playMap.delete(e.stream)})),t.clear()}play(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(e.hasAudio()&&this.container){const r=new AudioPlayer(this.container,{});if(this.addPlayerEvent(r),yield r.play(e),this.deviceId&&(yield r.setSinkId(this.deviceId)),this.muted)r.setVolume(0);else{let i;const n=transShareScreen2User(e.getUserId());if(i=isShareStream(e)?this.room.bmStreamVm.shareStreamModels.get(n):this.room.bmStreamVm.streamModels.get(n),i){const e=null===(t=i.bloudStream)||void 0===t?void 0:t.customInfo;e&&e.volume&&(r.audioLevel=e.volume,r.setVolume(e.volume))}}this.playerMap.set(e.getStreamId(),r)}}))}mute(e){this.muted=e,e?this.playerMap.forEach((e=>e.setVolume(0))):this.playerMap.forEach((e=>{e.audioLevel>0?e.setVolume(e.audioLevel):e.setVolume(1)}))}setVolume(e,t){const r=this.playerMap.get(e);if(r){if(r.audioLevel=t,this.muted)return;r.setVolume(t)}else error$1("设置了流的音量,但是没有找到对应的播放器",e)}setDevice(e){this.deviceId=e,this.playerMap.forEach((t=>t.setSinkId(e)))}addPlayerEvent(e){e.on("player-state-changed",(t=>{e.stream&&(info("audio player state change","","",[JSON.stringify(t)]),"error"===t.type&&t.reason&&"NotAllowedError"===t.reason.name&&this.playStateChangeWatcher.next(e),"PAUSED"===t.state&&e.resume())}))}destroy(){this.playerMap.forEach((e=>e.destroy())),this.playerMap.clear(),this.playMap=new WeakSet}}let _selfSortType=1;const subscribeOptions={audio:!0,video:!0,streamType:"small",videoEnable:!0,audioEnable:!0};let autoPlayAudio=!0;class BMRoom{constructor({initDevices:e}={initDevices:!0}){this.roomVM=null,this.videoDevices=[],this.audioDevices=[],this.audioOutputDevices=[],this.selectVideoDevice=null,this.selectAudioDevice=null,this.selectAudioOutputDevice=null,this.streamQueue=new SingletonQueue,this.userListColumns=1,this.sortType=1,this.BRTCConnectFailed=!1,this.pubFailedNum=0,this.streamConnectedErrorQueue=[],this.conferenceMode=1,this.isBig=!1,this.selectVideoDeviceWatcher=new BehaviorSubject(this.selectVideoDevice),this.selectAudioDeviceWatcher=new BehaviorSubject(this.selectAudioDevice),this.selectAudioOutputDeviceWatcher=new BehaviorSubject(this.selectAudioOutputDevice),this.audioDevicesWatcher=new Subject,this.videoDevicesWatcher=new Subject,this.audioOutputDevicesWatcher=new Subject,this.raiseHandleRespWatcher=new Subject,this.enableAudienceSpeakingWatcher=new Subject,this.mediaPermission={microphone:!0,camera:!0,screen:!0},this.videoProfile="360p",this.audioProfile=null,this.streamWSReconnectWatcher=new Subject,this.bloudWSReconnectWatcher=new Subject,this.netConnecting=!0,this.netConnectingWatcher=new Subject,this.hasSyncPermission=!0,this.meetingControlOptions={cancelAutoPull:!1},this.forceId="",this.networkState={bloud:!0,brtc:!0},this.brtcNetEnableWatcher=new Subject,this.autoPlayAudio=!0,this.pubFailedTimer=null,this.messageWatcher=new BehaviorSubject({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),this.isInWaitRoom=!1,this.shouldPlayAudio=!0,this.handleReprocessStreamError=()=>{this.netConnecting&&this.networkState.brtc&&this.networkState.bloud&&this.streamConnectedErrorQueue.length&&(info("brtc 网络恢复正常,处理重推逻辑","","",this.streamConnectedErrorQueue),this.streamConnectedErrorQueue.forEach((e=>{this.handleStreamConnectError(e)})),this.streamConnectedErrorQueue=[])},this.handleMediaDevicesChange=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){const e=this.filterDevice(this.audioDevices);yield this.bmStreamVm.changeAudioInput(e);const t=this.filterDevice(this.audioOutputDevices);yield this.bmStreamVm.changeSpeaker(t)}))),1e3),this.enumVideoDevices=enumVideoDevices,this.enumAudioInputDevices=enumAudioInputDevices,this.enumAudioOutputDevices=enumAudioOutputDevices,this.getPermissions=getPermissions,this.checkSystemSupport=checkSystemSupport,this.createStream=createStream,this.participantNotice=!1,this.handleQueueTask=(e,t=!1)=>__awaiter$2(this,void 0,void 0,(function*(){this.BRTCConnectFailed||(e.isLocal||!this.meetingControlOptions.cancelAutoPull||e.shouldPull)&&(yield this.handleStreamTask(e,t))})),this.republishLocalStream=debounce((e=>__awaiter$2(this,void 0,void 0,(function*(){const t=e.getAudioOn()||!1,r=e.getVideoOn()||!1;info("republish local stream ","","",[t,r]),(t||r)&&(yield this.publish(e).then((()=>__awaiter$2(this,void 0,void 0,(function*(){this.bmStreamVm.bloudStream=null,yield this.bmStreamVm.publishBloudStream(t,r),info("local stream connect error, and republish success, bloud stream republish success","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess(t,r))})))).catch((()=>{info("local stream connect error, and republish failed","","",["audio =>",t," video => ",r]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectFailed())})))}))),1e3),this.processUser=e=>__awaiter$2(this,void 0,void 0,(function*(){const t=new Set;if(e.forEach((e=>{if(e.isScreen){const r=this.bmStreamVm.getShareStreamModelByUId(e.id);r&&r.stream||(e.isWeb?t.add(`${e.id}_screen`):t.add(e.id))}else{let r=this.bmStreamVm.streamModels.get(e.id);r&&!r.stream&&t.add(e.id)}})),info("brtc query streams","","",["queryIds => ",JSON.stringify(Array.from(t))]),t.size){const e=yield this.queryBrtcStreams(Array.from(t)).catch((e=>{error$1("query stream error","","",[JSON.stringify(e)])}));if(e&&e.length){const t=e.map((e=>[e.getUserId(),e.getStreamId()]));info("brtc query streams result","","",["streamInfo =>",JSON.stringify(t)]),e&&this.handleAddStreams(e)}}})),this.queueProcessor=debounce(this.processUser,500,{maxWait:1e3}),Logger.setLogLevel(LOGLEVEL.INFO),info(`\n******************************************************************************\n* 欢迎使用 BoomMeeting(${PackageJson.version}) Web SDK\n******************************************************************************\n `),Logger.info("this is formatted by hysc/logger module");const t=BoomEmitter.getInstance();this.localUser=new BMUser({},!0),this.roomInfo=new BMRoomInfo,this.roomInfo.bindRoom(this),this.bmLiveVM=new BMLiveVM(this),this.bmStreamVm=(new BMStreamModelVM).initWithRoom(this),this.boomCore=new BCClient({}),t.on(RECEIVE_SUBSCRIBE_MESSAGE,(e=>{this.handleSubMessage(e)})),t.on(HANDLE_STREAM_CONNECT_ERROR,(e=>{this.handleStreamConnectError(e)})),t.on(ADD_PULL_USER,(e=>{this.addUser2Queue(e)})),t.on(MANUAL_SUBSCRIPTION,(e=>{this.manualSubscribeStreamModel(e.stream)})),t.on(UNSUBSCRIBE_STREAM,(e=>{this.handleUnsubscribe(e.stream)})),t.on(BIND_ELEMENT,(e=>{this.handleStreamBindElement(e.stream)})),t.on(BIND_BIG_ELEMENT,(e=>{this.handleStreamBindBigElement(e.stream)})),t.on(SET_VOLUME,(e=>{var t;null===(t=this.audioPlayer)||void 0===t||t.setVolume(e.streamId,e.volume)})),t.on(ADD_AUDIO_PLAY,(e=>{const t=e.stream.stream;t&&!t.isLocalStream()&&(this.audioPlayer.playMap.has(t)||this.audioPlayer.addStream(t))})),window.addEventListener("offline",(()=>{this.netConnecting=!1,this.netConnectingWatcher.next(!1)})),window.addEventListener("online",(()=>{this.netConnecting=!0,this.netConnectingWatcher.next(!0),NETWORK_ERROR_QUEUE.forEach((e=>{e()})),NETWORK_ERROR_QUEUE.clear(),this.handleReprocessStreamError()})),window.navigator.mediaDevices&&e&&(window.navigator.mediaDevices.ondevicechange=()=>__awaiter$2(this,void 0,void 0,(function*(){yield this.initDevices(),yield this.handleMediaDevicesChange()})),this.initDevices()),this.streamQueue.setQueueProcessor(this.queueProcessor),this.brtcNetEnableWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()})),this.bloudWSReconnectWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()}))}get isSingleColumns(){return 1===this.userListColumns}setAutoPlayAudio(e){this.autoPlayAudio=e,autoPlayAudio=e}setMediaPermission(e){this.mediaPermission=Object.assign(Object.assign({},this.mediaPermission),e),info("current media permission is ","","",[JSON.stringify(this.mediaPermission)])}setShouldPlayAudio(e){this.shouldPlayAudio=e}initAudioPlayer(e){info("init audio player"),this.audioPlayer=new AudioPlay(e,this)}setupMeetingControlOptions(e){e&&(this.meetingControlOptions=Object.assign(Object.assign({},this.meetingControlOptions),e))}handleSubMessage(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e.stream),`${e.stream.streamId} - 订阅流 - display ${e.stream.isDisplay} - currentDisplay - ${e.stream.isCurrentDisplay}`,0,e.stream.nickname)}setVideoProfile(e){e&&(this.videoProfile=e)}setUserListColumns(e){const t=toNumber(e);if(!isNumber(t))throw new Error("参数必须是数字");this.userListColumns=t}setSortType(e){const t=toNumber(e);if(t>2||t<1)throw new Error("排序映射只能为 2 或者 1");this.sortType=t,_selfSortType=this.sortType}setAudioProfile(e){this.audioProfile=e}setSig(e){this.boomCore.setShareSig(e)}initDevices(){return __awaiter$2(this,void 0,void 0,(function*(){return Promise.all([this.enumVideoDevices().then((e=>{this.videoDevices=e,this.videoDevicesWatcher.next(e)})),this.enumAudioInputDevices().then((e=>{this.audioDevices=e,this.audioDevicesWatcher.next(e)})),this.enumAudioOutputDevices().then((e=>{this.audioOutputDevices=e,this.audioOutputDevicesWatcher.next(e)}))]).then((()=>{let e=this.videoDevices.filter((e=>{var t;return e.name==(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.name)}));const t=e[0]?e[0]:this.filterDevice(this.videoDevices);t&&this.setSelectVideoDevice(t);let r=this.audioDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.name)}));const i=r[0]?r[0]:this.filterDevice(this.audioDevices);i&&this.setSelectAudioDevice(i);let n=this.audioOutputDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.name)}));const s=n[0]?n[0]:this.filterDevice(this.audioOutputDevices);return s&&this.setSelectSpeakerDevice(s),{videoDevices:this.videoDevices,audioDevices:this.audioDevices,audioOutputDevices:this.audioOutputDevices,selectVideoDevice:this.selectVideoDevice,selectAudioDevice:this.selectAudioDevice,selectAudioOutputDevice:this.selectAudioOutputDevice}}))}))}filterDevice(e){const t=e.filter((e=>e.default))[0];return t||e[0]}setSelectAudioDevice(e){var t;(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectAudioDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioDevice=e,this.selectAudioDeviceWatcher.next(e))}setSelectVideoDevice(e){var t;(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectVideoDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectVideoDevice=e,this.selectVideoDeviceWatcher.next(e))}setSelectSpeakerDevice(e){var t;(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(info("setSelectSpeakerDevice","","",["deviceId =>",e.deviceId,"name =>",e.name]),this.selectAudioOutputDevice=e,this.selectAudioOutputDeviceWatcher.next(e))}observe(e,t){return this.observes[e].subscribe(t)}join(e){return __awaiter$2(this,void 0,void 0,(function*(){const t=e.brtc_host;t&&this.setCustomUrl(t);try{if(this.boomCore.client)return error$1("重复 join,请先调用 destroy"),Promise.reject(RepeatJoinError);this.conferenceMode=e.roomType,this.isBig=e.is_big,info("========================","join info",e.userId,["roomId: ",e.room," roomType: ",e.roomType," roomName: ",e.name]),this.localUser.setup(e.userId,e.userinfo,e.nickname),this.bmStreamVm.createStreamModel(this.localUser),this.userVM=new BMUserVM(this.boomCore,this.localUser,this),this.isBig&&(this.userVM.commTimer=1e3),this.roomVM=new BMRoomVM(this.boomCore,this.userVM,this.roomInfo),this.roomVM.initWithRoom(this),this.chatVM=new BMChatVM(this.boomCore,this.userVM,this),this._attachEvents(),yield this.boomCore.join(e).catch((e=>Promise.reject(e))),this.roomInfo.setup(this.boomCore.getRoomInfo());for(let e in this.observes)this.observe(e,(()=>{}));this.bmStreamVm.startSpeakerDetector(),this.roomInfo.setlock(this.boomCore.client.lock),addBrtcNetEvent(this.boomCore)}catch(e){return error$1("join room error","","",[JSON.stringify(e)]),Promise.reject(e)}}))}leave(){var e,t;return __awaiter$2(this,void 0,void 0,(function*(){try{this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedNum=0,BoomEmitter.removeEmitter(),autoPlayAudio=!0,null===(e=this.audioPlayer)||void 0===e||e.destroy(),this.bmStreamVm.clearCache(),this.bmStreamVm.canvasTimer&&clearTimeout(this.bmStreamVm.canvasTimer);const r=yield this.boomCore.leave().catch((()=>{error$1("bloud离会失败")}));for(let e in this.observes)null===(t=this.observes[e])||void 0===t||t.unsubscribe();return this.observes={},r}catch(e){return error$1("leave room error","","",[JSON.stringify(e)]),Promise.reject(BmLeaveError(JSON.stringify(e)))}}))}releaseRoom(){return __awaiter$2(this,void 0,void 0,(function*(){yield this.boomCore.releaseRoom()}))}startRecord(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.startRecord(e)}))}stopRecord(){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.stopRecord()}))}sliceRecord(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.sliceRecord(e)}))}close(){this.bmStreamVm.clearCache(),this.boomCore.close()}setRemoteVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setRemoteAudioEnable(e,t,r){return __awaiter$2(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteAudioEnable(e,t,r).catch((e=>Promise.reject(e)))}))}setLocalVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setLocalAudioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalAudioEnable(e).catch((e=>Promise.reject(e)))}))}setLocalSpeakerEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.muteSpeaker(e).catch((e=>Promise.reject(e)))}))}_attachEvents(){this.observes=attachEvents(this.boomCore,this.userVM,this.bmStreamVm,this.chatVM,this)}createSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter$2(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId};e.videoSource&&(n.videoSource=e.videoSource),e.audioSource&&(n.audioSource=e.audioSource),n.echoCancellation=!0,n.noiseSuppression=!0,n.autoGainControl=!0;const s=yield this.boomCore.createLocalStream(n,t).catch((t=>(error$1("create brtc stream error","","",[JSON.stringify(t),null==t?void 0:t.message]),Promise.reject(getStreamError(e.video?"摄像头":"麦克风")))));e.video&&("720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile));try{yield s.init()}catch(t){if(error$1("brtc init stream failed","","",[null==t?void 0:t.message]),String(t).includes("Permission denied by system")){if(e.video)return Promise.reject(BMCameraNotAuthError());if(e.audio)return Promise.reject(BMMicNotAuthError())}else{if(String(t).includes("Could not start video source"))return Promise.reject(BMCameraOccupyError());if(String(t).includes("Could not start audio source"))return Promise.reject(BMMicOccupyError())}return Promise.reject(BMCreateStreamError(e.video?"摄像头":"麦克风"))}return s}))}createPBSingleLocalStream(e={video:!0,audio:!0},t){var r,i;return __awaiter$2(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(r=this.selectVideoDevice)||void 0===r?void 0:r.deviceId,microphoneId:null===(i=this.selectAudioDevice)||void 0===i?void 0:i.deviceId,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},s=yield this.boomCore.createPBLocalStream(n,t).catch((e=>Promise.reject(e)));return"720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile),yield s.init(),s}))}subscribe(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return this.boomCore.subscribe(e,t)}))}unsubscribe(e){return this.boomCore.unsubscribe(e).catch((e=>Promise.reject(e)))}publish(e){return new Promise(((t,r)=>{this.boomCore.publish(e).then((()=>{info("brtc stream publish success"),t(!0)})).catch((()=>__awaiter$2(this,void 0,void 0,(function*(){this.pubFailedNum<=3?(this.pubFailedNum+=1,this.pubFailedTimer&&clearTimeout(this.pubFailedTimer),this.pubFailedTimer=setTimeout((()=>(error$1(`local publish stream failed, retry failed num: ${this.pubFailedNum}`),this.publish(e).then(t).catch(r))),3e3)):(error$1("retry publish local stream failed, ubpublish now"),yield this.bmStreamVm.unpublishStream(),r(!1))}))))}))}unpublish(e){return this.boomCore.unpublish(e).catch((e=>Promise.reject(e)))}getUser(e){return this.userVM.getUser(e)}changeMaster(e,t=!1){var r;return __awaiter$2(this,void 0,void 0,(function*(){return null===(r=this.roomVM)||void 0===r?void 0:r.changeMaster(e,t).catch((e=>e))}))}updateManager(e,t,r=!0){return __awaiter$2(this,void 0,void 0,(function*(){return this.roomVM.updateManager(e,t,r).catch((e=>e))}))}getMaster(){return this.boomCore.getMaster()}getCreator(){return this.boomCore.getCreator()}getName(){return this.boomCore.getName()}evictUser(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.evictUser(e,t).catch((e=>e))}))}updateUser(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){null===(r=this.roomVM)||void 0===r||r.updateUser(e,t).catch((e=>e))}))}getMsgSeq(){return this.boomCore.getMsgSeq()}getLimits(){return this.boomCore.getLimits()}getSwitch(){return this.boomCore.getSwitch()}syncRoom(){return this.boomCore.syncRoom()}update(e){return this.boomCore.update(e)}getUsers(){return this.userVM.userList}getTotalUsers(){return this.userVM.userList.size}sendMessage(e,t){return this.boomCore.sendMessage(e,t)}customMessage(e,t){return this.boomCore.customMessage(e,t)}getMessages(e,t){return this.boomCore.getMessages(e,t)}getLocalParticipant(){var e;let t=null===(e=this.userVM)||void 0===e?void 0:e.getLocalUser();return t||(t=this.localUser),t}getAudioOff(){return this.boomCore.getAudioOff()}getSelfOpenAudio(){return this.boomCore.getSelfOpenAudio()}getVideoOff(){return this.boomCore.getVideoOff()}getMsgOff(){return this.boomCore.getMsgOff()}getLock(){return this.boomCore.getLock()}getRoomInfo(){return this.roomInfo}setAudioOff(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.setAudioOff(e,t).catch((e=>Promise.reject(BmSetAudioOffError(`boomCore.setAudioOff error ${JSON.stringify(e)}`))))}))}updateRoom(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.boomCore.client.update(e)}))}setVideoOff(e){return this.boomCore.setVideoOff(e).catch((e=>Promise.reject(BmSetVideoOffError(`boomCore.setVideoOff error ${JSON.stringify(e)}`))))}setMsgOff(e){return this.boomCore.setMsgOff(e).catch((e=>Promise.reject(BmSetMsgOffError(`boomCore.setMsgOff error ${JSON.stringify(e)}`))))}setSwitch(e){return this.boomCore.setSwitch(e)}setLock(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.setLock(e),this.boomCore.getLock()}))}sendChatMessage(e,t,r){if(!this.chatVM)throw new BoomError$1(INVALID_OPERATION,"未初始化chatVM, 无法发送聊天信息");return this.chatVM.sendMessage(e,t,r)}getChatMessage(){if(!this.chatVM)throw new BoomError$1(INVALID_OPERATION,"未初始化chatVM, 无法获取聊天室消息");return this.chatVM.messageList}getHistoryMessage(){return __awaiter$2(this,void 0,void 0,(function*(){return this.chatVM.getHistoryMessage()}))}updateCustomStats(e){return info("updateCustomStats","","",[JSON.stringify(e)]),this.boomCore.updateCustomStats(Object.assign(Object.assign({},e),{pos:"web"})).catch((e=>Promise.reject(BmUpdateCustomStatsError(`.boomCore.updateCustomStats ${JSON.stringify(e)}`))))}getCustomStats(){return this.boomCore.getCustomStats()}getDuration(){return this.boomCore.getDuration()}checkUserHasMaster(e){return this.userVM.checkUserHasMaster(e)}changeNickName(e,t){var r;return __awaiter$2(this,void 0,void 0,(function*(){yield null===(r=this.roomVM)||void 0===r?void 0:r.changeNickName(e,t)}))}handleStreamTask(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){e.stream?1===this.conferenceMode?(yield this.handlePull(e),yield this.handleChangeStreamType(e),yield this.handlePlay(e,t)):(yield this.bmLiveVM.handlePull(e),yield this.bmLiveVM.handleChangeStreamType(e),yield this.bmLiveVM.handlePlay(e,t)):((e.isDisplay||e.isInBig)&&e.bloudStream||e.audioEnable)&&(yield this.addUser2Queue({id:e.userId,isScreen:e.isShare,isWeb:e.isWeb}))}))}handlePull(e){var t,r,i,n;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal||(e.isMixer&&(yield this.handleSubscribeSteam(e)),e.isDisplay!==e.isCurrentDisplay||e.isInBig&&e.pulledStreamType!==e.pulledStreamGoal||!e.hasPulled?(info(" 订阅流 => ","订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t)]),e.isCurrentDisplay=e.isDisplay,e.checkCount=0,e.isDisplay||e.isInBig||!e.isDisplay&&(e.audioEnable||(null===(i=e.stream)||void 0===i?void 0:i.getAudioOn()))?yield this.handleSubscribeSteam(e):yield this.handleUnsubscribeStream(e)):e.stream&&e.audioEnable&&(null===(n=this.audioPlayer)||void 0===n||n.addStream(e.stream)))}))}manualSubscribeStreamModel(e){streamPullQueue.addQueue(this.handleStreamTask.bind(this,e),e.streamId,0,e.nickname)}handleUnsubscribe(e){streamPullQueue.addQueue(this.handleUnsubscribeStream.bind(this,e),e.streamId,0,e.nickname)}handleStreamBindElement(e){streamPullQueue.addQueue(this.handlePlay.bind(this,e,!1,!1),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleStreamBindBigElement(e){streamPullQueue.addQueue(this.handlePlayInBIg.bind(this,e),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleUnsubscribeStream(e){var t,r,i,n,s;return __awaiter$2(this,void 0,void 0,(function*(){e.stream&&((null===(r=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===r?void 0:r.call(t))||e.hasPulled)&&(info("取消订阅流 => ","取消订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(n=null===(i=e.stream)||void 0===i?void 0:i.isSubscribed)||void 0===n?void 0:n.call(i)]),e.hasPulled=!1,e.pulledStreamType="small",e.isInBig=!1,yield null===(s=e.stream)||void 0===s?void 0:s.stop(),yield this.unsubscribe(e.stream).then((()=>{var t,r;e.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(e.stream)),e.isSubScribedWatcher.next(!1),info("取消订阅这股流","",e.userId,[e.nickname,e.isDisplay,e.isCurrentDisplay,null===(r=e.stream)||void 0===r?void 0:r.getStreamId()])})).catch((()=>{error$1("unsubscribe error")})))}))}handleSubscribeSteam(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){try{e.hasPulled&&e.stream.isSubscribed()?e.isDisplay?null===(t=e.stream)||void 0===t||t.unmuteVideo().then((()=>{info("stream unmute video success","unmute-video",e.userId,["streamId => ",e.streamId])})):null===(r=e.stream)||void 0===r||r.muteVideo().then((()=>{info("stream mute video success","mute-video",e.userId,["streamId => ",e.streamId])})):(e.hasPulled=!0,yield this.subscribe(e.stream,subscribeOptions).then((()=>{var t,r;e.isDisplay||null===(t=e.stream)||void 0===t||t.muteVideo(),e.stream&&e.audioEnable&&(null===(r=this.audioPlayer)||void 0===r||r.addStream(e.stream)),e.pullFailedNum=0,info("订阅流结束","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId,"display =>",e.isDisplay]),e.isSubScribedWatcher.next(!0),this.bmStreamVm.addToRecorder(e.stream),e.isDisplay&&e.videoEnable&&checkStreamIsNormal(e)})).catch((t=>{var r,i;if(error$1("订阅流失败","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId," error => ",JSON.stringify(t)]),e.hasPulled=!1,e.pulledStreamType="small",e.pullFailedNum+=1,null===(r=e.player)||void 0===r||r.destroy(),e.pullFailedNum<=3)this.handlePulledFailed(e);else{e.pullFailedNum=0;const r=e.isShare;try{null===(i=e.stream)||void 0===i||i.destroy()}catch(t){}e.updateStream(void 0,!1,this.bmStreamVm),info("subscribe stream failed, need to reQuery stream","",e.userId,["streamId =>",e.streamId,"hasStream => ",!!e.stream,"isWeb => ",e.isWeb,"isScreen => ",r,"bloudStreamState =>",JSON.stringify(e.bloudStream)]),e.bloudStream&&this.addUser2Queue({id:e.userId,isWeb:e.isWeb,isScreen:r})}})))}catch(t){e.hasPulled=!1,e.pulledStreamType="small",console.error("订阅流失败","",e.userId,e.nickname,"错误 =>",t)}}))}handleChangeStreamType(e){var t,r;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal||e.pulledStreamType!==e.pulledStreamGoal&&(null===(t=e.stream)||void 0===t?void 0:t.isSubscribed())&&((null===(r=e.stream)||void 0===r?void 0:r.isSubscribed())||e.hasPulled)&&(info("大小流切换 => ","切换大小流",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," pulledStreamType =>",e.pulledStreamType," pulledStreamGoal =>",e.pulledStreamGoal]),e.pulledStreamType=e.pulledStreamGoal,yield this.boomCore.brtcClient.setRemoteVideoStreamType(e.stream,e.pulledStreamGoal).catch((t=>{error$1("大小流切换失败","",e.userId,["error => ",JSON.stringify(t)])})),info("大小流切换结束","",e.userId,["nickname =>",e.nickname," isInBig => ",e.isInBig," pulledStreamGoal => ",e.pulledStreamGoal,"pulledStreamType => ",e.pulledStreamType]))}))}handlePlay(e,t,r=!0){var i,n,s;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal?e.isShare||t||(e.play(),e.playInBig()):(e.hasPulled||(null===(i=null==e?void 0:e.stream)||void 0===i?void 0:i.isSubscribed()))&&(t&&!e.isShare||e.play(),e.stream&&e.audioEnable&&((null===(n=this.audioPlayer)||void 0===n?void 0:n.playMap.has(e.stream))||null===(s=this.audioPlayer)||void 0===s||s.addStream(e.stream)),r&&(yield this.handlePlayInBIg(e)))}))}handlePlayInBIg(e){return __awaiter$2(this,void 0,void 0,(function*(){yield e.playInBig()}))}handlePulledFailed(e){const t=e.userId;(e.isShare?this.bmStreamVm.shareStreamModels.has(t):this.bmStreamVm.streamModels.has(t))&&streamPullQueue.addQueue(this.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}handleStreamConnectError(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){const{stream:r,isLocal:i}=e;info("handleStreamConnectError","","",["nickname =>",r.nickname,"streamId => ",r.streamId,"isShare =>",r.isShare,"isLocal => ",i]),r.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(r.stream)),i?r.stream&&(r.isShare?this.bmStreamVm.localShareError.next(BMShareStreamConnectError()):this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamConnectError()),this.netConnecting&&this.networkState.brtc&&this.networkState.bloud?r.isShare?(info("Local share stream has problem, now ,republish"),handleShareStreamFailed(this,this.bmStreamVm)):(info("brtc 网络正常,重新推流"),r.stream&&(yield this.republishLocalStream(r.stream))):(error$1("brtc 网络还没恢复,等恢复了在重新推流 ","",r.userId,["nickname =>",r.nickname,"streamId => ",r.streamId,"isShare =>",r.isShare]),this.streamConnectedErrorQueue.push(e))):this.netConnecting&&this.networkState.brtc?(r.hasPulled=!1,r.pulledStreamType="small",streamPullQueue.addQueue(this.handleQueueTask.bind(this,r),r.streamId,0,r.nickname)):(error$1("brtc 网络还没恢复,等恢复了在重新拉流 ","",r.userId,["nickname =>",r.nickname]),this.streamConnectedErrorQueue.push(e))}))}toggleAudienceSpeaking(e,t){e.permission.setAudio(t),this.updateUser(e.userId,{permission:e.permission.get()})}updateUserIsGuest(e,t){return __awaiter$2(this,void 0,void 0,(function*(){e.permission.setSubscribe(t),yield this.updateUser(e.userId,{permission:e.permission.get()})}))}managerChangeToGuest(e){this.userVM.managerChangeToGuest(e)}moveUserRoom(e,t=!1,r=!1){return this.boomCore.client.moveUserRoom(e,t,r)}getParticipantNotice(e){this.participantNotice=e}setCustomUrl(e){this.boomCore.setCustomUrl(e)}handleRePushSelf(){var e,t;return __awaiter$2(this,void 0,void 0,(function*(){const r=null===(t=null===(e=this.getLocalParticipant())||void 0===e?void 0:e.getMainStreamModel())||void 0===t?void 0:t.stream;r&&(yield this.republishLocalStream(r))}))}handleResetOtherStreamStatus(){info("brtc sync-room-completed"),this.bmStreamVm.streamModels.forEach((e=>{var t;e.isLocal||(e.hasPulled=!1,e.pulledStreamType="small",e.stream&&e.stream.stop(),null===(t=e.stream)||void 0===t||t.destroy(),e.updateStream(void 0,!1,this.bmStreamVm))})),this.bmStreamVm.shareStreamModels.forEach((e=>{var t,r;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";const i=e.getUser();null===(t=e.stream)||void 0===t||t.stop(),null===(r=e.stream)||void 0===r||r.destroy(),i.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`)}})),this.bmStreamVm.shareStreamModels.clear(),this.bmStreamVm.shareStreamModelsWatcher.next(Array.from(this.bmStreamVm.shareStreamModels.values())),this.networkState.brtc=!0,setTimeout((()=>{this.brtcNetEnableWatcher.next(!0),this.streamWSReconnectWatcher.next(!0)}),2e3),handleReconnectedStream(this)}addUser2Queue(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(e.isScreen)this.streamQueue.addUsers([e]);else{const r=this.bmStreamVm.streamModels.get(e.id);r&&!r.isLocal&&(r.stream||r&&((null===(t=r.bloudStream)||void 0===t?void 0:t.audio)||r.bloudStream&&r.isDisplay)&&this.streamQueue.addUsers([e]))}}))}queryBrtcStreams(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.brtcClient.queryUsers(e)}))}handleAddStreams(e){e.forEach((e=>{if(isShareStream(e)){const t=this.bmStreamVm.shareStreamModels.get(transShareScreen2User(e.getUserId()));(!t||t&&!t.stream)&&this.bmStreamVm.remoteStreamPublished(e)}else{const t=this.bmStreamVm.streamModels.get(e.getUserId());t&&!t.stream&&this.bmStreamVm.remoteStreamPublished(e)}}))}getForceUser(e){return __awaiter$2(this,void 0,void 0,(function*(){const{users:t}=yield this.boomCore.queryUsers([e]);this.userVM.addBcUsersMap(t,!0),this.userVM.getForceUserWatcher.next(!0)}))}getVersion(){return PackageJson.version}}return window.BoomMeeting=BMRoom,window.BoomError=BoomError,BMRoom}));
|