@rongcloud/plugin-wechat-rtc
Version:
@rongcloud/plugin-wechat-rtc
1 lines • 72.3 kB
JavaScript
"use strict";var e,t,s,o,i=require("@rongcloud/engine");function n(e,t,s,o){return new(s||(s=Promise))(function(i,n){function r(e){try{a(o.next(e))}catch(e){n(e)}}function u(e){try{a(o.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(r,u)}a((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,exports.RCRTCCode=void 0,(e=exports.RCRTCCode||(exports.RCRTCCode={}))[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.PERMISSION_DENIED=53012]="PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.INVALID_MEDIATYPE=53028]="INVALID_MEDIATYPE",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53029]="SIGNAL_JOIN_RTC_ROOM_REFUSED",function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(t||(t={})),exports.RCMediaType=void 0,(s=exports.RCMediaType||(exports.RCMediaType={}))[s.AUDIO_ONLY=0]="AUDIO_ONLY",s[s.VIDEO_ONLY=1]="VIDEO_ONLY",s[s.AUDIO_VIDEO=2]="AUDIO_VIDEO",function(e){e.T="_",e.L_INIT_RTC_O="L_INIT_RTC_O",e.L_APP_CALLBACK_O="L_APP_CALLBACK_O",e.L_APP_CALLBACK_E="L_APP_CALLBACK_E",e.L_CORE_CTX_CALLBACK_E="L_CORE_CTX_CALLBACK_E",e.L_PUSHER_CTX_CALLBACK_E="L_PUSHER_CTX_CALLBACK_E",e.L_PLAYER_CTX_CALLBACK_E="L_PLAYER_CTX_CALLBACK_E",e.A_SEND_MSG_R="A_SEND_MSG_R",e.A_SET_ROOM_ATTRS_R="A_SET_ROOM_ATTRS_R",e.A_DEL_ROOM_ATTRS_R="A_DEL_ROOM_ATTRS_R",e.A_GET_ROOM_ATTRS_R="A_GET_ROOM_ATTRS_R",e.L_INVOKER_EXECUTE_T="L_INVOKER_EXECUTE_T",e.L_INVOKER_EXECUTE_R="L_INVOKER_EXECUTE_R",e.L_INVOKER_PUSH_O="L_INVOKER_PUSH_O",e.L_INVOKER_DESTROY_O="L_INVOKER_DESTROY_O",e.L_PINGER_START_O="L_PINGER_START_O",e.L_PINGER_SEND_RTCPING_R="L_PINGER_SEND_RTCPING_R",e.L_PINGER_STOP_O="L_PINGER_STOP_O"}(o||(o={}));class r{constructor(e,t,s="https://rtc-miniapp-wctgw-prod-bdcbj.ronghub.com/wechat",o=5e3,i){this._runtime=e,this._logger=t,this._msUrl=s,this._timeout=o,this._store=i}_request(e,t){return n(this,void 0,void 0,function*(){const s={"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:"WeChat-MiniProgram",ClientVersion:"5.4.0","Request-Id":Date.now().toString()},n=`${this._msUrl}${e}`;this._logger.info(o.T,`request -> Request-Id: ${s["Request-Id"]}, url: ${n}`);const{status:r,data:u}=yield this._runtime.httpReq({url:n,body:JSON.stringify(t),headers:Object.assign(Object.assign({},s),this._store.getHttpHeaders()),method:i.HttpMethod.POST,timeout:this._timeout});return 200===r&&1e4===u.resultCode?(this._logger.info(o.T,`request success -> Request-Id: ${s["Request-Id"]}`),{code:exports.RCRTCCode.SUCCESS,data:u}):(this._logger.warn(o.T,`request failed -> Request-Id: ${s["Request-Id"]}, status: ${r}, resultCode: ${JSON.stringify(u)}, url: ${n}`),{code:exports.RCRTCCode.REQUEST_FAILED})})}exchange(e){return n(this,void 0,void 0,function*(){return this._request("/exchange",e)})}exit(){return n(this,void 0,void 0,function*(){return this._request("/exit",{})})}}const u=(e,t)=>{const s={},o=Object.keys(e.users);return o.length&&o.forEach(o=>{const i=[],n=e.users[o];if(n.uris)try{i.push(...JSON.parse(n.uris))}catch(e){t.warn(`invalid user data -> userId: ${o}, userData: ${n}`)}s[o]=i}),s},a=e=>`${e.msid}_${e.mediaType}`,d=(e,t,s=!1)=>{e=e.slice();const o=[],i=[],n=[];return t.forEach(t=>{const i=a(t);let r=e.findIndex(e=>a(e)===i);if(s&&(r=e.findIndex(e=>e.uri===t.uri)),-1===r)return void o.push(t);const u=e[r];u.uri!==t.uri?o.push(t):u.state!==t.state&&n.push(t),e.splice(r,1)}),i.push(...e),{publishedList:o,unpublishedList:i,modifiedList:n}},c=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),R=e=>JSON.stringify(e),_=e=>e.map(e=>Object.assign({},e)),p=e=>{if(!i.isObject(e)||void 0===e.low||void 0===e.high)return e;let{low:t}=e;t<0&&(t+=4294967296),t=t.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp(`0{${t.length}}$`),t),16)},h=(e,t,s)=>{s.dispatch("showComponent"),e===exports.RCMediaType.AUDIO_ONLY?s.dispatch(t?"openMicphone":"closeMicphone"):s.dispatch(t?"openCamera":"closeCamera")};var l,C,I,m,T,S,g,E,O,f,v,y,A;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline"}(l||(l={})),function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(C||(C={})),exports.ORIENTATION=void 0,(I=exports.ORIENTATION||(exports.ORIENTATION={})).VERTICAL="vertical",I.HORIZONTAL="horizontal",exports.ASPECT=void 0,(m=exports.ASPECT||(exports.ASPECT={}))[m.THREEDIVIDEFOUR=.75]="THREEDIVIDEFOUR",m[m.NINEDIVIDESIXTEEN=.5625]="NINEDIVIDESIXTEEN",exports.LOCALMIRROR=void 0,(T=exports.LOCALMIRROR||(exports.LOCALMIRROR={})).AUTO="auto",T.ENABLE="enable",T.DISABLE="disable",exports.AUDIOREVERBTYPE=void 0,(S=exports.AUDIOREVERBTYPE||(exports.AUDIOREVERBTYPE={}))[S.CLOSE=0]="CLOSE",S[S.KTV=1]="KTV",S[S.LITTLEROOM=2]="LITTLEROOM",S[S.GREATHALL=3]="GREATHALL",S[S.LOW=4]="LOW",S[S.LOUD=5]="LOUD",S[S.METALLIC=6]="METALLIC",S[S.MAGNETIC=7]="MAGNETIC",exports.BEAUTYSTYLE=void 0,(g=exports.BEAUTYSTYLE||(exports.BEAUTYSTYLE={})).SMOOTH="smooth",g.NATURE="nature",exports.FILTER=void 0,(E=exports.FILTER||(exports.FILTER={})).STANDARD="standard",E.PINK="pink",E.NOSTALGIA="nostalgia",E.BLUES="blues",E.ROMANTIC="romantic",E.COOL="cool",E.FRESHER="fresher",E.SOLOR="solor",E.AESTHETICISM="aestheticism",E.WHITENING="whitening",E.CERISERED="cerisered",exports.OBJECTFIT=void 0,(O=exports.OBJECTFIT||(exports.OBJECTFIT={})).CONTAIN="contain",O.FILLCROP="fillCrop",exports.REFERRERPOLICY=void 0,(f=exports.REFERRERPOLICY||(exports.REFERRERPOLICY={})).ORIGIN="origin",f.NOREFERRER="no-referrer",exports.RCAudioOutputDevice=void 0,(v=exports.RCAudioOutputDevice||(exports.RCAudioOutputDevice={})).SPEAKER="speaker",v.EAR="ear",exports.RCAudioVolumeType=void 0,(y=exports.RCAudioVolumeType||(exports.RCAudioVolumeType={})).AUTO="auto",y.MEDIA="media",y.VOICECALL="voicecall",exports.RCDevicePosition=void 0,(A=exports.RCDevicePosition||(exports.RCDevicePosition={})).FRONT="front",A.BACK="back";class N{constructor(){this._listeners=[]}addEventListener(e){this._listeners.push(e)}dispatch(e,...t){this._listeners.forEach(s=>{const o=s[e];if(o)try{o(...t)}catch(t){console.error(e,t)}})}}class L extends i.EventEmitter{setNetStatusListener(e){this.removeAll("netStatus"),e&&this.on("netStatus",e)}setLocalAudioLevelListener(e){this.removeAll("audioVolumeNotify"),e&&this.on("audioVolumeNotify",e)}}class U extends i.EventEmitter{setNetStatusListener(e){this.removeAll("netStatus"),e&&this.on("netStatus",e)}setRemoteAudioLevelListener(e){this.removeAll("audioVolumeNotify"),e&&this.on("audioVolumeNotify",e)}}const D=new class extends N{constructor(){super(...arguments),this._soundMode=exports.RCAudioOutputDevice.SPEAKER}setSoundMode(e){this._soundMode!==e&&(this._soundMode=e,this.dispatch("setSoundMode",e))}getSoundMode(){return this._soundMode}},b=new L,P=new U,x=()=>D,M=()=>b,V=()=>P;globalThis.coreContext=D,globalThis.pusherContext=b,globalThis.playerContext=P;const k=x();class w extends i.EventEmitter{constructor(e,t,s,o){super(),this._logger=e,this._userId=t,this._tag=s,this._mediaType=o,this._ownerDisableVideo=!0,this._ownerMuteAudio=!0,this._isSubscribed=!1,this._listener=null}registerStreamEventListener(e){this._logger.warn(o.T,"registerStreamEventListener is deprecated"),this._listener=e}__innerSetMediaType(e){const t=this._mediaType;if(this._mediaType=e,e!==t){const s=t>=exports.RCMediaType.VIDEO_ONLY,o=t!==exports.RCMediaType.VIDEO_ONLY,i=e>=exports.RCMediaType.VIDEO_ONLY,n=e!==exports.RCMediaType.VIDEO_ONLY;s!==i&&(s?this._callListener("onVideoUnpublish"):this._callListener("onVideoPublish")),o!==n&&(o?this._callListener("onAudioUnpublish"):this._callListener("onAudioPublish"))}}_callListener(e){var t;try{null===(t=this._listener)||void 0===t||t[e]()}catch(t){this._logger.error(o.L_APP_CALLBACK_E,`method: ${e}, stack: ${null==t?void 0:t.stack}`)}}__innerSetRtmpUrl(e){k.dispatch("setPlayerSrc",`${this._userId}_${this._tag}`,e),this._rtmpUrl=e}__innerSetOwnerMuteAudio(e){const t=this._ownerMuteAudio!==e;return this._ownerMuteAudio=e,t}__innerSetOwnerDisableVideo(e){const t=this._ownerDisableVideo!==e;return this._ownerDisableVideo=e,t}__innerSetIsSubscribed(e){this._isSubscribed=e}isOwnerMuteAudio(){return this._ownerMuteAudio}isOwnerDisableVideo(){return this._ownerDisableVideo}isSubscribed(){return this._isSubscribed}hasVideo(){return this._mediaType>exports.RCMediaType.AUDIO_ONLY}hasAudio(){return this._mediaType===exports.RCMediaType.AUDIO_ONLY||this._mediaType===exports.RCMediaType.AUDIO_VIDEO}getRTMPUrl(){return this._rtmpUrl}getTag(){return this._tag}getUserId(){return this._userId}getMsid(){return`${this._userId}_${this._tag}`}getMediaType(){return this._mediaType}mute(){k.dispatch("mute",`${this._userId}_${this._tag}`)}unmute(){k.dispatch("unmute",`${this._userId}_${this._tag}`)}setAudioOutputDevice(e){this._logger.warn(o.T,"'setAudioOutputDevice has beem deprecated, please use 'room.setAudioOutputDevice(mode)' instead"),k.setSoundMode(e)}}var B,$,K;!function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(B||(B={})),function(e){e[e.Destroy=40400]="Destroy"}($||($={}));class q{get priority(){return B.LOW}}!function(e){e.UNKNOWN="UNKNOWN",e.ChangeEnableCommand="ChangeEnableCommand",e.JoinRTCRoomCommand="JoinRTCRoomCommand",e.RemoteUserCommand="RemoteUserCommand",e.UnsubCommand="UnsubCommand",e.PubCommand="PubCommand",e.ReconnectCommand="ReconnectCommand",e.UnpubCommand="UnpubCommand",e.SubscribeCommand="SubscribeCommand",e.RemoteResourceCommand="RemoteResourceCommand",e.PullRTCRoomStatusCommand="PullRTCRoomStatusCommand"}(K||(K={}));class F extends q{constructor(e,t=!1){super(),this._subParams=e,this._forceSub=t,this._transSubParams=[];const s={};this._subParams.forEach(e=>{const t=e instanceof w?{stream:e,subTiny:!0}:e,o=t.stream.getMsid();s[o]=t}),this._transSubParams=Object.values(s)}get kind(){return K.SubscribeCommand}_filterNewSubParams(e){const t=[...e.getSubscribedParams()],s=this._transSubParams.filter(e=>J(e,t)),o=t.filter(e=>G(e,s));return{newSubParams:s,restSubParams:o}}_updateStoreData(e,t,s){t.forEach(t=>{const{stream:s}=t,o=((e,t)=>{let s="";return t.forEach(t=>{t.msid===e&&(s=t.uri)}),s})(s.getMsid(),e);s.__innerSetRtmpUrl(o),s.__innerSetIsSubscribed(!0)}),s.setSubscribeParams(t)}_exchange(e,t){return n(this,void 0,void 0,function*(){const{logger:s,store:i,service:n}=t,r=yield X(i,n,e);return r.code!==exports.RCRTCCode.SUCCESS?(s.warn(o.T,`subscribe failed -> roomId: ${i.getRoomId()}, code: ${r.code}`),r):(s.info(o.T,`exchange subscribe success, subscribeList: ${JSON.stringify(e.map(e=>({subTiny:!!e.subTiny,msid:e.stream.getMsid()})))}`),r)})}execute(e){return n(this,void 0,void 0,function*(){const{newSubParams:t,restSubParams:s}=this._filterNewSubParams(e.store);if(!t.length&&!this._forceSub)return{code:exports.RCRTCCode.SUCCESS};const o=[...t,...s],i=yield this._exchange(o,e),{code:n}=i;if(n===exports.RCRTCCode.SUCCESS){const{rtmpSubscribeList:t}=i.data;this._updateStoreData(t,o,e.store)}return{code:n}})}}class Y extends q{constructor(e){super(),this._unsubStreams=e,this._unsubStreams=[...new Set(this._unsubStreams)]}get kind(){return K.UnsubCommand}_exchange(e,t){return n(this,void 0,void 0,function*(){const{store:s,service:i,logger:n}=t,r=yield X(s,i,e);return r.code!==exports.RCRTCCode.SUCCESS?(n.warn(o.T,`unsubscribe failed -> roomId: ${s.getRoomId()}, code: ${r.code}`),r):(n.info(o.T,`exchange subscribe success, subscribeList: ${JSON.stringify(e.map(e=>({subTiny:!!e.subTiny,msid:e.stream.getMsid()})))}`),r)})}execute(e){return n(this,void 0,void 0,function*(){const{store:t}=e,s=t.getSubscribedParams();if(!s.length)return{code:exports.RCRTCCode.SUCCESS};const o=this._unsubStreams.filter(e=>s.some(({stream:t},s)=>e.getMsid()===t.getMsid())),i=s.filter(({stream:e})=>o.some(t=>t.getMsid()!==e.getMsid())),{code:n}=yield this._exchange(i,e);return n!==exports.RCRTCCode.SUCCESS?{code:n}:(o.length&&t.deleteSubscribeParams(o),o.forEach(e=>{e.__innerSetRtmpUrl(""),e.__innerSetIsSubscribed(!1)}),e.emit(Te.DEL_RECV_NET_STAT,o),{code:exports.RCRTCCode.SUCCESS})})}}const J=(e,t)=>{const s=t.some(t=>{const s=e.stream.getMsid()===t.stream.getMsid(),o=e.subTiny===t.subTiny;return s&&o});return!t.length||!s},G=(e,t)=>t.every(t=>!(e.stream.getMsid()===t.stream.getMsid())),H=(e,t,s)=>n(void 0,void 0,void 0,function*(){const{store:i}=e,r=[],u=new Set,d=new Set,c=new Set,R=i.getResourceByUserId(s),_=R.map(a);t.forEach(t=>n(void 0,void 0,void 0,function*(){const s=a(t),o=_.indexOf(s),{userId:n,tag:p,mediaType:h}=(e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}})(s),l=`${n}_${p}`;o>-1?R[o]=t:R.push(t);let C=i.getRemoteStream(l);if(!C)return C=new w(e.logger,n,p,t.mediaType),h===exports.RCMediaType.AUDIO_ONLY?C.__innerSetOwnerMuteAudio(0===t.state):C.__innerSetOwnerDisableVideo(0===t.state),i.setRemoteStream(l,C),void r.push(C);if(r.indexOf(C)>=0)return C.__innerSetMediaType(exports.RCMediaType.AUDIO_VIDEO),void(h===exports.RCMediaType.AUDIO_ONLY?C.__innerSetOwnerMuteAudio(0===t.state):C.__innerSetOwnerDisableVideo(0===t.state));C.isSubscribed()&&u.add(C);const I=C.getMediaType();I!==exports.RCMediaType.AUDIO_VIDEO&&I!==h?(C.__innerSetMediaType(exports.RCMediaType.AUDIO_VIDEO),h===exports.RCMediaType.AUDIO_ONLY?C.__innerSetOwnerMuteAudio(0===t.state)&&d.add(C):C.__innerSetOwnerDisableVideo(0===t.state)&&c.add(C)):h===exports.RCMediaType.AUDIO_ONLY?C.__innerSetOwnerMuteAudio(0===t.state)&&d.add(C):C.__innerSetOwnerDisableVideo(0===t.state)&&c.add(C)})),i.setResourcesByUserId(s,R),u.size&&(yield((e,t)=>n(void 0,void 0,void 0,function*(){const s=e.map(e=>({msid:e.getMsid(),mediaType:e.getMediaType()}));t.logger.info(o.T,`resub stream -> ${JSON.stringify(s)}`);const i=new F(e,!0);yield i.execute(t)}))([...u],e)),r.length&&e.emit(Te.ON_STREAM_PUBLISH,r),d.size&&d.forEach(t=>{e.emit(Te.ON_AUDIO_MUTE_CHANGE,t)}),c.size&&c.forEach(t=>{e.emit(Te.ON_VIDEO_MUTE_CHANGE,t)})}),j=(e,t,s)=>n(void 0,void 0,void 0,function*(){const{store:o}=e,i=o.getResourceByUserId(s),n=t.map(a);for(let e=i.length-1;e>=0;e-=1){const t=i[e];n.includes(a(t))&&o.updateResourceByUserId(s,e,null)}const{unpubStreams:r,restStreams:u}=((e,t)=>{const s=t.getRemoteStreams(),o={},i={};return e.forEach(e=>{const{mediaType:t,msid:n}=e,r=s[n];t===exports.RCMediaType.AUDIO_ONLY&&(r.hasVideo()?(r.__innerSetMediaType(exports.RCMediaType.VIDEO_ONLY),i[n]=r):(delete i[n],o[n]=r)),t===exports.RCMediaType.VIDEO_ONLY&&(r.hasAudio()?(i[n]=r,r.__innerSetMediaType(exports.RCMediaType.AUDIO_ONLY)):(delete i[n],o[n]=r))}),{unpubStreams:Object.values(o),restStreams:Object.values(i)}})(t,o);if(r.length&&(yield new Y(r).execute(e),o.deleteRemoteStreams(r),e.emit(Te.ON_STREAM_UNPUBLISH,r)),u.length){const t=new Set,s=new Set;u.forEach(e=>{e.getMediaType()===exports.RCMediaType.AUDIO_ONLY&&e.__innerSetOwnerDisableVideo(!0)&&s.add(e),e.getMediaType()===exports.RCMediaType.VIDEO_ONLY&&e.__innerSetOwnerMuteAudio(!0)&&t.add(e)}),t.size&&t.forEach(t=>{e.emit(Te.ON_AUDIO_MUTE_CHANGE,t)}),s.size&&s.forEach(t=>{e.emit(Te.ON_VIDEO_MUTE_CHANGE,t)})}}),Q=(e,t,s)=>{const{store:o}=e,i=o.getResourceByUserId(s).map(a),n=new Set,r=new Set;for(let e=0;e<t.length;e+=1){const u=t[e],{msid:d,mediaType:c}=u,R=a(u),_=i.indexOf(R);o.updateResourceByUserId(s,_,u);const p=o.getRemoteStream(d);p?c===exports.RCMediaType.AUDIO_ONLY?p.__innerSetOwnerMuteAudio(0===u.state)&&n.add(p):p.__innerSetOwnerDisableVideo(0===u.state)&&r.add(p):console.warn(`!!! stream is not found: ${d} !!!`)}n.size&&n.forEach(t=>{e.emit(Te.ON_AUDIO_MUTE_CHANGE,t)}),r.size&&r.forEach(t=>{e.emit(Te.ON_VIDEO_MUTE_CHANGE,t)})},X=(e,t,s,o=!1)=>n(void 0,void 0,void 0,function*(){const i=((e,t)=>{const s=[];return t.forEach(t=>{const{stream:o,subTiny:i}=t instanceof w?{stream:t,subTiny:!0}:t,n=o.getUserId(),r=o.hasVideo(),u=o.hasAudio(),a=o.getTag();r&&s.push({uri:e.getUriByResourceId(n,a,exports.RCMediaType.VIDEO_ONLY),simulcast:i?C.TINY:C.NORMAL}),u&&s.push({uri:e.getUriByResourceId(n,a,exports.RCMediaType.AUDIO_ONLY)})}),s})(e,s),n=o?null:e.getPublishParams();if(!(i&&i.length||n))return t.exit();const r={rtmp:n?[{msid:`${e.getCrtUserId()}_${n.tag}`,mediaType:n.mediaType,resolution:"640X480"}]:[],subscribeList:i||[]};return t.exchange(r)});function W(e,t,s,o,i,r){return n(this,void 0,void 0,function*(){const{logger:o}=s,i=[],r={},a={},c={},R=u(e,o),p=Object.keys(R),h=t.getAllUserIds();for(let e=p.length-1;e>=0;e-=1){const s=p[e],o=h.indexOf(s);if(-1===o){i.push(s),r[s]=_(R[s]);continue}const n=t.getResourceByUserId(s),u=R[s],{publishedList:l,modifiedList:C,unpublishedList:I}=d(n,u,!0);r[s]=_(l),a[s]=_(I),c[s]=_(C),h.splice(o,1)}h.length&&h.forEach(e=>{t.deleteResourceByUserId(e)}),t.assignRoomData(R),h.length&&(yield((e,t,s)=>n(void 0,void 0,void 0,function*(){const o=[];e.forEach(e=>{o.push(...t.getRemoteStreamByUserId(e))}),o.length&&(yield new Y(o).execute(s)),e.forEach(e=>{t.deleteRemoteStreamByUserId(e),t.deleteResourceByUserId(e)})}))(h,t,s),s.emit(Te.ON_USER_LEAVE,h)),i.length&&s.emit(Te.ON_USER_JOIN,i);for(const e in a)e!==t.getCrtUserId()&&(yield j(s,a[e],e));for(const e in r){const t=r[e];t.length&&H(s,t,e)}for(const e in c)Q(s,c[e],e)})}function z(e){var t,s;const{userId:o,userData:i}=e,n=(e=>e.some(e=>"uris"===e.key||"cdn_uris"===e.key))(i);if(!n)return;const r=null===(t=i.filter(e=>"uris"===e.key)[0])||void 0===t?void 0:t.value,u=null===(s=i.filter(e=>"cdn_uris"===e.key)[0])||void 0===s?void 0:s.value;return{userId:o,content:{uris:r?JSON.parse(r):[],cdn_uris:u&&JSON.parse(u)}}}function Z(e){var t;const{userId:s,userData:o,event:i,switchRoleType:n}=e;return{users:[{userId:s,extra:null===(t=o.filter(e=>"extra"===e.key)[0])||void 0===t?void 0:t.value,state:i,switchRoleType:n}]}}class ee extends q{constructor(e,t,s){super(),this._tag=e,this._mediaType=t,this._room=s,this._coreContext=x()}get kind(){return K.PubCommand}_getResourceState(e,t){let s;return s=e===exports.RCMediaType.AUDIO_ONLY?this._room.isMicphoneOpen()?1:0:this._room.isCameraOpen()?1:0,s}_sendTotalUris(e,t){return n(this,void 0,void 0,function*(){const{store:s,context:o}=t,{publishList:i,rtmpPublishList:n,rtmpSubscribeList:r}=e,u=n[0].uri,a=s.getRoomResource()[s.getCrtUserId()],_=i.map(e=>Object.assign(Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(e.mediaType,s)},e),{rtmpUri:u})),{publishedList:p}=d(a,_);return{code:yield o.setRTCTotalRes(s.getRoomId(),[c(l.PUBLISH,p)],R(_),l.TOTAL_CONTENT_RESOURCE),publishList:_}})}_updateStore(e,t){e.setResourcesByUserId(e.getCrtUserId(),t),e.setPubMediaType(this._mediaType),this._mediaType===exports.RCMediaType.AUDIO_VIDEO?(e.setIsPubVideo(!0),e.setIsPubAudio(!0)):this._mediaType===exports.RCMediaType.AUDIO_ONLY?e.setIsPubAudio(!0):e.setIsPubVideo(!0)}execute(e){return n(this,void 0,void 0,function*(){if(t=this._tag,!/^[a-zA-Z\d-=]+$/g.test(t))return{code:exports.RCRTCCode.INVALID_TAGS};var t,s;if(s=this._mediaType,!exports.RCMediaType[s])return{code:exports.RCRTCCode.INVALID_MEDIATYPE};const{store:n,logger:r,service:u}=e;this._coreContext.dispatch("showComponent"),n.setPublishParams(this._tag,this._mediaType),e.emit(Te.OPERATE_DEVICE_BY_MEDIA_TYPE,this._mediaType);const a=yield X(n,u,n.getSubscribedParams());if(a.code!==exports.RCRTCCode.SUCCESS)return n.setPublishParams(""),r.warn(o.T,`publish failed -> roomId: ${n.getRoomId()}, code: ${a.code}`),{code:a.code};const{rtmpPublishList:d}=a.data,{code:c,publishList:R}=yield this._sendTotalUris(a.data,e);if(c!==i.ErrorCode.SUCCESS)return r.warn(o.T,`send publish streams notification failed: ${c}`),n.setPublishParams(""),{code:c};r.info(o.T,`publish success, tag: ${this._tag}, mediaType: ${this._mediaType}`),this._updateStore(n,R);const _=d[0].uri;return this._coreContext.dispatch("setPusherUrl",_),{code:exports.RCRTCCode.SUCCESS}})}}class te{constructor(e,t,s,o){this._logger=e,this._context=t,this._store=s,this.abortCode=o,this._queue=[],this._busy=!1,this._isDestroyed=!1}_next(){this._busy=!1,this._execute()}_execute(){return n(this,void 0,void 0,function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t}=this._queue.shift();let s;const n=this._logger.createTraceId();try{this._logger.info(o.L_INVOKER_EXECUTE_T,`kind: ${e.kind}, length: ${this._queue.length}`,n),s=yield e.execute(this._context,this._store,this)}catch(t){return console.error(t),this._logger.error(o.L_INVOKER_EXECUTE_R,e.kind,n),void this._next()}const{code:r}=s;r!==exports.RCRTCCode.SUCCESS&&r!==i.ErrorCode.SUCCESS?this._logger.warn(o.L_INVOKER_EXECUTE_R,`code: ${r}, kind: ${e.kind}`,n):this._logger.info(o.L_INVOKER_EXECUTE_R,`kind: ${e.kind}, Done`,n),t(s),this._next()})}push(e){return new Promise(t=>{if(this._logger.info(o.L_INVOKER_PUSH_O,JSON.stringify({isDestroyed:this._isDestroyed,kind:e.kind,length:this._queue.length})),this._isDestroyed)return void t({code:exports.RCRTCCode.NOT_IN_ROOM});const{priority:s}=e;if(s===B.LOW||0===this._queue.length)this._queue.push({command:e,resolve:t});else{const o=this._queue.findIndex(e=>e.command.priority<s),i=-1===o?this._queue.length:o;this._queue.splice(i,0,{command:e,resolve:t})}setTimeout(()=>{this._execute()},0)})}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._logger.info(o.L_INVOKER_DESTROY_O),this._isDestroyed=!0,this._queue.forEach(e=>{e.resolve({code:this.abortCode})}),this._queue.length=0)}}class se extends te{constructor(e,t){super(e.logger,e,t,exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}}class oe extends q{constructor(e){super(),this._msgContent=e,this._userId=""}get kind(){return K.RemoteUserCommand}get priority(){return B.NORMAL}execute(e){return n(this,void 0,void 0,function*(){const{users:t}=this._msgContent;if(0===t.length)return{code:exports.RCRTCCode.SUCCESS};const{logger:s,store:i}=e,n=i.getRoomResource(),r=[],u=[];if(t.forEach(e=>{0===+e.state?(s.info(o.T,`user joined -> ${e.userId}`),n[e.userId]||r.push(e.userId),i.setResourcesByUserId(e.userId,[])):(s.info(o.T,`user left -> ${e.userId}`),u.push(e.userId))}),u.length){const t=[];u.forEach(e=>{t.push(...i.getRemoteStreamByUserId(e))}),t.length&&(yield new Y(t).execute(e)),u.forEach(e=>{i.deleteRemoteStreamByUserId(e),i.deleteResourceByUserId(e)})}return r.length&&e.emit(Te.ON_USER_JOIN,r),u.length&&e.emit(Te.ON_USER_LEAVE,u),{code:exports.RCRTCCode.SUCCESS}})}}class ie extends q{constructor(e,t,s){super(),this._content=e,this._messageType=t,this._userId=s}get kind(){return K.RemoteResourceCommand}get priority(){return B.NORMAL}_parseRemoteResource(e){const{uris:t}=this._content,s=[],o=[],i=[];let n;switch(this._messageType){case l.MODIFY:i.push(...t);break;case l.PUBLISH:s.push(...t);break;case l.UNPUBLISH:o.push(...t);break;case l.TOTAL_CONTENT_RESOURCE:n=d(e,t),s.push(...n.publishedList),o.push(...n.unpublishedList),i.push(...n.modifiedList)}return{publishedList:s,unpublishedList:o,modifiedList:i}}execute(e){return n(this,void 0,void 0,function*(){if(this._content.ignore)return{code:exports.RCRTCCode.SUCCESS};const{store:t}=e,s=t.getResourceByUserId(this._userId),o=this._parseRemoteResource(s),{publishedList:i,unpublishedList:n,modifiedList:r}=o;return i.length&&(yield H(e,i,this._userId)),n.length&&(yield j(e,n,this._userId)),r.length&&Q(e,r,this._userId),{code:exports.RCRTCCode.SUCCESS}})}}var ne,re,ue;!function(e){e[e.enable=1]="enable",e[e.disable=0]="disable"}(ne||(ne={}));class ae extends q{constructor(e,t){super(),this._mediaType=e,this._enable=t}get kind(){return K.ChangeEnableCommand}execute(e){return n(this,void 0,void 0,function*(){const{logger:t,context:s,store:n}=e,r=n.getCrtUserId(),u=n.getResourceByUserId(r),a=u.filter(e=>e.mediaType===this._mediaType)[0];a.state=this._enable?ne.enable:ne.disable;const d=yield s.setRTCTotalRes(n.getRoomId(),[c(l.MODIFY,[a])],R(u),l.TOTAL_CONTENT_RESOURCE);return d!==i.ErrorCode.SUCCESS?(t.warn(o.T,"notice `video.enabled` change failed -> code: "+d),{code:exports.RCRTCCode.SIGNAL_ERROR}):(n.setResourcesByUserId(r,u),{code:exports.RCRTCCode.SUCCESS})})}}class de extends q{constructor(){super(...arguments),this._coreContext=x()}get kind(){return K.UnpubCommand}_sendTotalUris(e){return n(this,void 0,void 0,function*(){const{store:t}=e,s=t.getRoomResource()[t.getCrtUserId()];return{code:yield e.context.setRTCTotalRes(t.getRoomId(),[c(l.UNPUBLISH,s)],R([]),l.TOTAL_CONTENT_RESOURCE)}})}execute(e){return n(this,void 0,void 0,function*(){const{store:t,logger:s}=e;if(!t.getPublishParams())return s.warn(o.T,"You have not published resource, please execute the method of publish"),{code:exports.RCRTCCode.SUCCESS};const{code:n}=yield this._sendTotalUris(e);if(n!==i.ErrorCode.SUCCESS)return s.warn(o.T,`send publish streams notification failed: ${n}`),{code:exports.RCRTCCode.SIGNAL_ERROR};const r=t.getSubscribedParams(),u=yield X(t,e.service,r,!0);return u.code!==exports.RCRTCCode.SUCCESS?(s.warn(o.T,`unpublish failed -> roomId: ${t.getRoomId()}, code: ${u.code}`),{code:u.code}):(s.info(o.T,"unpublish success"),e.emit(Te.DEL_SEND_NET_STAT),t.setResourcesByUserId(t.getCrtUserId(),[]),t.setPublishParams(""),t.setIsPubVideo(!1),t.setIsPubAudio(!1),this._coreContext.dispatch("setPusherUrl",""),{code:exports.RCRTCCode.SUCCESS})})}}!function(e){e.SUCCESS="Success",e.FAIL="Fail"}(re||(re={})),function(e){e[e.RTC=0]="RTC",e[e.LIVE=2]="LIVE",e[e.CROSS_MUTI=7]="CROSS_MUTI",e[e.SIP=4]="SIP",e[e.CALL=5]="CALL"}(ue||(ue={}));class ce{constructor(e,t,s,o=5e3){this._context=e,this._roomId=t,this._logger=s,this._gap=o,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(e){this._started||(e<15e3&&(e=15e3),this._logger.info(o.L_PINGER_START_O,JSON.stringify({interval:this._gap,offlineKickTime:e})),this._started=!0,this._checkAlive(e))}_sendPing(e){return n(this,void 0,void 0,function*(){return new Promise(e=>{this._context.rtcPing(this._roomId,ue.RTC).then(e),setTimeout(e,5e3,i.ErrorCode.TIMEOUT)})})}_checkAlive(e){var t,s;return n(this,void 0,void 0,function*(){const n=this._logger.createTraceId(),{code:r,data:u}=yield this._sendPing(n),a=Date.now();return r===i.ErrorCode.SUCCESS?(this._latestTimestamp=a,null===(t=this.onPingResult)||void 0===t||t.call(this,re.SUCCESS,u.version),void(this._timer=setTimeout(()=>this._checkAlive(e),this._gap))):(this._logger.warn(o.L_PINGER_SEND_RTCPING_R,`roomId: ${this._roomId}, code: ${r}`,n),null===(s=this.onPingResult)||void 0===s||s.call(this,re.FAIL),40003===r||a-this._latestTimestamp>e?(this.stop(),void this.onFailed(40003===r)):void(this._timer=setTimeout(()=>this._checkAlive(e),500)))})}stop(){this._started&&(this._logger.info(o.L_PINGER_STOP_O),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}class Re extends q{get kind(){return K.ReconnectCommand}get priority(){return B.HIGH}execute(e){return n(this,void 0,void 0,function*(){const{context:t,store:s,logger:n}=e,{code:r,data:a}=yield t.joinRTCRoom(s.getRoomId(),s.mode);if(r!==i.ErrorCode.SUCCESS)return n.warn(o.T,`__onReconnected getRTCRoomInfo failed: ${r}`),{code:exports.RCRTCCode.SIGNAL_ERROR};n.info(o.T,`__onReconnected getRTCRoomInfo success: ${JSON.stringify(a)}`);const c=[],R={},p={},h={},l=u(a,n),C=s.getRoomResource(),I=Object.keys(l),m=Object.keys(C);for(let e=I.length-1;e>=0;e-=1){const t=I[e],s=m.indexOf(t);if(-1===s){c.push(t),R[t]=_(l[t]);continue}const o=C[t],i=l[t],{publishedList:n,modifiedList:r,unpublishedList:u}=d(o,i,!0);R[t]=_(n),p[t]=_(u),h[t]=_(r),m.splice(s,1)}s.setRoomResource(l),m.length&&e.emit(Te.ON_USER_LEAVE,m),c.length&&e.emit(Te.ON_USER_JOIN,c);for(const t in R){const s=R[t];s.length&&H(e,s,t)}for(const t in p){const s=p[t];s.length&&j(e,s,t)}for(const t in h){const s=h[t];s.length&&Q(e,s,t)}return{code:exports.RCRTCCode.SUCCESS}})}}class _e extends i.EventEmitter{constructor(e,t,s,o,i){super(),this.logger=e,this.context=t,this.runtime=s,this.store=o,this.service=i}}class pe{constructor(e,t,s){this._appkey=e,this._crtRoomId=t,this._crtUserId=s,this._roomResource={},this._subscribeParams=[],this._roomIsDestroyed=!0,this._remoteStreams={},this._publishParams=null,this._crtRoomToken="",this._crtSeesionId="",this._isPubVideo=!1,this._isPubAudio=!1,this._pubMediaType=exports.RCMediaType.AUDIO_VIDEO,this._isOpenCamera=!1,this._isOpenMic=!1,this._roomStatusVersion=0,this._supportNtf=!0}getRoomResource(){return this._roomResource}getResourceByUserId(e){return this._roomResource[e]||[]}getUriByResourceId(e,t,s){return this._roomResource[e].filter(e=>e.tag===t&&e.mediaType===s)[0].uri}getPublishParams(){return this._publishParams}getSubscribedParams(){return this._subscribeParams}getSubscribeStreams(){const e={};return this._subscribeParams.forEach(t=>{const{stream:s}=t,o=s.getMsid();e[o]=s}),e}getRemoteStreams(){return this._remoteStreams}getRemoteStream(e){return this._remoteStreams[e]}getAllUserIds(){return Object.keys(this._roomResource)}getRemoteUserIds(e){return Object.keys(this._roomResource).filter(t=>t!==e)}getRemoteStreamByUserId(e){const t=[];for(const s in this._remoteStreams){const o=s.split("_")[0],i=this._remoteStreams[s];e===o&&t.push(i)}return t}getCrtRoomToken(){return this._crtRoomToken}getCrtSessionId(){return this._crtSeesionId}getRoomId(){return this._crtRoomId}get mode(){return ue.RTC}getIsPubVideo(){return this._isPubVideo}getIsPubAudio(){return this._isPubAudio}getPubMediaType(){return this._pubMediaType}getCrtUserId(){return this._crtUserId}getHttpHeaders(){return{"App-Key":this._appkey,UserId:this._crtUserId,Token:this._crtRoomToken,RoomId:this._crtRoomId,RoomType:ue.RTC}}getRoomStatusVersion(){return this._roomStatusVersion}getSupportNtf(){return this._supportNtf}}class he extends pe{setRoomResource(e){this._roomResource=e}assignRoomData(e){Object.assign(this._roomResource,e)}setResourcesByUserId(e,t){this._roomResource[e]=t}deleteResourceByUserId(e){delete this._roomResource[e]}updateResourceByUserId(e,t,s){s?this._roomResource[e][t]=s:this._roomResource[e].splice(t,1)}setPublishParams(e="",t=exports.RCMediaType.AUDIO_VIDEO){this._publishParams=e?{tag:e,mediaType:t}:null}setSubscribeParams(e){this._subscribeParams=e}addSubscribeParams(e){this._subscribeParams.push(...e)}deleteSubscribeParams(e){this._subscribeParams=this._subscribeParams.filter(t=>{const{stream:s}=t;return e.every(e=>e.getMsid()!==s.getMsid())})}setRemoteStream(e,t){this._remoteStreams[e]=t}deleteRemoteStreams(e){e.map(e=>e.getMsid()).forEach(e=>{delete this._remoteStreams[e]})}deleteRemoteStreamByUserId(e){for(const t in this._remoteStreams){e===t.split("_")[0]&&delete this._remoteStreams[t]}}setCrtRoomToken(e){this._crtRoomToken=e}setCrtSessionId(e){this._crtSeesionId=e}setIsPubVideo(e){this._isPubVideo=e}setIsPubAudio(e){this._isPubAudio=e}setPubMediaType(e){this._pubMediaType=e}setRoomStatusVersion(e){this._roomStatusVersion=p(e)}}class le extends q{constructor(e){super(),this._joinType=e}get kind(){return K.JoinRTCRoomCommand}_updateStore(e,t,s,o,i){e.setRoomResource(t);const n=e.getRemoteStreams();Object.keys(t).forEach(s=>{t[s].forEach(t=>{const{msid:o,mediaType:r,rtmpUri:u,state:a}=t,d=o.split("_").pop();let c=n[o];c?c.__innerSetMediaType(exports.RCMediaType.AUDIO_VIDEO):c=new w(i,s,d,r),r===exports.RCMediaType.AUDIO_ONLY?c.__innerSetOwnerMuteAudio(0===a):c.__innerSetOwnerDisableVideo(0===a),e.setRemoteStream(o,c)})}),e.setCrtRoomToken(s),e.setCrtSessionId(o)}_unPubPrevResource(e,t){return n(this,void 0,void 0,function*(){const{logger:s,context:n,store:r}=t;s.info(o.T,`unpublish uris prev login: ${JSON.stringify(e)}`);const u=yield n.setRTCTotalRes(r.getRoomId(),[c(l.UNPUBLISH,e)],R([]),l.TOTAL_CONTENT_RESOURCE,R([]));e.length=0,u!==i.ErrorCode.SUCCESS?s.warn(o.T,`unpublish prev uris failed -> code: ${u}`):s.info(o.T,"unpublish uris prev login succeed")})}execute(e){return n(this,void 0,void 0,function*(){const{store:s,context:n,logger:r}=e,a=s.getRoomId(),d=s.getCrtUserId();if(!i.validate("roomId",s.getRoomId(),i.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(n.getConnectionStatus()!==i.RCConnectionStatus.CONNECTED)return{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};r.info(o.T,`joinRoom -> roomId: ${a}; joinType: ${this._joinType||i.RTCJoinType.KICK}`);const c=s.getSupportNtf(),{code:R,data:_}=yield n.joinRTCRoom(a,ue.RTC,void 0,this._joinType,void 0,void 0,c);if(R!==i.ErrorCode.SUCCESS){r.warn(o.T,`joinRoom failed -> code: ${R}`);return{code:R===t.JOIN_REFUSED?exports.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:R}}r.info(o.T,`joinRoom success -> userId: ${d}, roomId: ${a}, data: ${JSON.stringify(_)}`);const p=u(_,r),h=p[d]||[];return h.length&&(yield this._unPubPrevResource(h,e)),this._updateStore(s,p,_.token,_.sessionId,r),{code:exports.RCRTCCode.SUCCESS}})}}var Ce,Ie;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline",e.ROOM_TASK_FINISH="RCRTC:roomTaskFinish"}(Ce||(Ce={})),function(e){e[e.JOIN=0]="JOIN",e[e.LEAVE=1]="LEAVE",e[e.OFFLINE=2]="OFFLINE",e[e.RESOURCECHANGE=3]="RESOURCECHANGE"}(Ie||(Ie={}));class me extends q{constructor(e,t,s,o){super(),this._roomId=e,this._traceId=t,this._context=s,this._targetPullVersion=o}get kind(){return K.PullRTCRoomStatusCommand}execute(e,t,s){return n(this,void 0,void 0,function*(){const{logger:s}=e,n=t.getRoomStatusVersion();if(s.info(o.T,JSON.stringify({roomId:this._roomId,localVersion:n}),this._traceId),this._targetPullVersion&&this._targetPullVersion<=n)return s.info(o.T,JSON.stringify({status:"success",msg:"the roomData has been pulled",localVersion:n,targetPullVersion:this._targetPullVersion}),this._traceId),{code:i.ErrorCode.SUCCESS};const{code:r,data:u}=yield this._context.pullRTCRoomStatus(this._roomId,n);if(r!==i.ErrorCode.SUCCESS)return s.info(o.T,JSON.stringify({status:"failed",code:r}),this._traceId),{code:r};const{bFullStatus:a,version:d,usersData:c,roomStatus:R}=u;if(s.info(o.T,JSON.stringify({bFullStatus:a,version:p(d),usersData:c,roomStatus:R}),this._traceId),t.setRoomStatusVersion(d),a){const{urisData:s,CDNUris:o}=function(e){const t={users:{}};let s="";return e.forEach(e=>{var o,i;const{userId:n,userData:r}=e;t.users[n]={};const u=null===(o=r.filter(e=>"uris"===e.key)[0])||void 0===o?void 0:o.value,a=null===(i=r.filter(e=>"cdn_uris"===e.key)[0])||void 0===i?void 0:i.value;s=a||s,t.users[n]={uris:u}}),{urisData:t,CDNUris:s&&JSON.stringify(JSON.parse(s)[0])}}(c);return yield W(s,t,e,0,0,this._traceId),{code:r}}for(const s of R)if(s.event===Ie.RESOURCECHANGE){const o=z(s);if(!o)continue;const{content:i,userId:n}=o;if(n===t.getCrtUserId())continue;yield new ie(i,Ce.TOTAL_CONTENT_RESOURCE,n).execute(e)}else{const t=Z(s);yield new oe(t).execute(e)}return{code:r}})}}const Te={LEAVE:"leave",DEL_RECV_NET_STAT:"delete_recv_net_status",DEL_SEND_NET_STAT:"delete_sender_net_status",ON_USER_JOIN:"on_user_join",ON_USER_LEAVE:"on_user_leave",ON_STREAM_PUBLISH:"on_stream_publish",ON_STREAM_UNPUBLISH:"on_stream_unpublish",ON_AUDIO_MUTE_CHANGE:"on_audio_mute_change",ON_VIDEO_MUTE_CHANGE:"on_video_mute_change",OPERATE_DEVICE_BY_MEDIA_TYPE:"OPERATE_DEVICE_BY_MEDIA_TYPE"};class Se extends i.EventEmitter{constructor(e,t,s,i,u){super(),this._context=e,this._logger=t,this._runtime=s,this._initOptions=i,this._roomId=u,this._isOpenCamera=!0,this._isOpenMic=!0,this._resourceListener=null,this._reportListener=null,this._netStatusData={};const a=e.getCurrentId(),d=new he(e.getAppkey(),u,a);this._mediaServer=new r(this._runtime,this._logger,this._initOptions.mediaServer,this._initOptions.timeout,d);const c=this._commandCtx=new _e(this._logger,this._context,this._runtime,d,this._mediaServer);this._invoker=new se(c,d),this._store=this._invoker.store,this._pinger=new ce(e,u,t,i.pingGap),this._pinger.onFailed=this._kickOff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),x().setSoundMode(exports.RCAudioOutputDevice.SPEAKER),this._bindRoomEvent(),this._context.registerRTCSignalListener(e=>n(this,void 0,void 0,function*(){const{time:t,type:s,roomId:i}=this._context.decodeRtcNotify(e);if(this._invoker.isDestroyed())this._logger.info(o.T,JSON.stringify({isDestroyed:!0,type:s,time:t,roomId:i}));else if(2===s&&i===this._roomId){const e=this._logger.createTraceId();this._logger.info(o.T,null,e),this._startPullRTCRoomStatus(i,e,t)}}))}_startPullRTCRoomStatus(e,t,s){return n(this,void 0,void 0,function*(){yield this._invoker.push(new me(e,t,this._context,s))})}_handlePingResult(e,t){if(e===re.SUCCESS){if(t>this._store.getRoomStatusVersion()&&this._store.getSupportNtf()){const e=this._logger.createTraceId();this._logger.info(o.T,JSON.stringify({dataVersion:t}),e),this._startPullRTCRoomStatus(this._roomId,e,t)}}}__innerInitialize(e){return n(this,void 0,void 0,function*(){const{code:t}=yield this._invoker.push(new le(e));return t===exports.RCRTCCode.SUCCESS&&this._pinger.start(3e4),t})}_callAppListener(e,...t){var s;const i=null===(s=this._resourceListener)||void 0===s?void 0:s[e];if(this._logger.info(o.L_APP_CALLBACK_O,`method: ${e}`),i)try{i(...t)}catch(t){this._logger.error(o.L_APP_CALLBACK_E,`event: ${e}, error: ${null==t?void 0:t.stack}`)}else this._logger.warn(o.L_APP_CALLBACK_E,`No listener: ${e}`)}_bindRoomEvent(){this._commandCtx.on(Te.DEL_RECV_NET_STAT,this._deleteReceiverNetStatus,this),this._commandCtx.on(Te.DEL_SEND_NET_STAT,this._deleteSerderNetStatus,this),this._commandCtx.on(Te.ON_STREAM_PUBLISH,this._onStreamPublish,this),this._commandCtx.on(Te.ON_STREAM_UNPUBLISH,this._onStreamUnpublish,this),this._commandCtx.on(Te.ON_AUDIO_MUTE_CHANGE,this._onAudioMuteChange,this),this._commandCtx.on(Te.ON_VIDEO_MUTE_CHANGE,this._onVideoMuteChange,this),this._commandCtx.on(Te.ON_USER_LEAVE,this._onUserLeave,this),this._commandCtx.on(Te.ON_USER_JOIN,this._onUserJoin,this),this._commandCtx.on(Te.OPERATE_DEVICE_BY_MEDIA_TYPE,this._operateDeviceByMediaType,this)}_operateDeviceByMediaType(e){switch(e){case exports.RCMediaType.AUDIO_VIDEO:this.openCamera(),this.openMicphone();break;case exports.RCMediaType.AUDIO_ONLY:this.openMicphone(),this.closeCamera();break;case exports.RCMediaType.VIDEO_ONLY:this.openCamera(),this.closeMicphone()}}_onStreamPublish(e){this._callAppListener("onStreamPublish",e)}_onStreamUnpublish(e){this._callAppListener("onStreamUnpublish",e)}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_onUserJoin(e){this._callAppListener("onUserJoin",e)}_onUserLeave(e){this._callAppListener("onUserLeave",e)}_kickOff(e,t){return n(this,void 0,void 0,function*(){const s=this._store.getCrtUserId();let o;if(t){const e=t.users.find(e=>e.userId===s);o=null==e?void 0:e.type}this._callAppListener("onKickOff",e,o),this.__leaveHandle(!e)})}__parseInnerMessage(e){const{targetId:t}=e;if(t!==this._store.getRoomId())return;if(this.isDestroyed())return;this._logger.info(o.T,`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._store.getRoomId()}`);const s=e.content;switch(e.messageType){case l.KICK:this._kickOff(!0,s);break;case l.STATE:this._invoker.push(new oe(s));break;case l.MODIFY:case l.PUBLISH:case l.UNPUBLISH:if(s.ignore)return;this._invoker.push(new ie(s,e.messageType,e.senderUserId));break;case l.TOTAL_CONTENT_RESOURCE:this._invoker.push(new ie(s,e.messageType,e.senderUserId));break;case l.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case l.USER_NOTIFY:this._logger.warn(o.T,`TODO: ${l.USER_NOTIFY}`);break;default:this._callAppListener("onMessageReceive",e.messageType,e.content,e.senderUserId,e.messageUId)}}registerRoomEventListener(e){this._resourceListener=e}registerReportListener(e){this._reportListener=e;const t=M(),s=e?this._pusherNetStatusListener.bind(this):null;t.setNetStatusListener(s);const o=V(),i=e?this._playerNetStatusListener.bind(this):null;o.setNetStatusListener(i)}_pusherNetStatusListener(e){this._netStatusData.sender=e,this._reportListener&&this._reportListener(this._netStatusData)}_playerNetStatusListener(e,t){this._netStatusData.receiver=this._netStatusData.receiver||{},this._netStatusData.receiver[e]=t,this._reportListener&&this._reportListener(this._netStatusData)}onLocalAudioLevelChange(e){M().setLocalAudioLevelListener(e)}onRemoteAudioLevelChange(e){V().setRemoteAudioLevelListener(e)}startPreview(){const e=x();e.dispatch("showComponent"),e.dispatch("startPreview")}stopPreview(){const e=x();e.dispatch("showComponent"),e.dispatch("stopPreview")}openCamera(){return n(this,void 0,void 0,function*(){return this._isOpenCamera?{code:exports.RCRTCCode.SUCCESS}:(h(exports.RCMediaType.VIDEO_ONLY,!0,x()),this._isOpenCamera=!0,this._store.getIsPubVideo()?this._invoker.push(new ae(exports.RCMediaType.VIDEO_ONLY,!0)):{code:exports.RCRTCCode.SUCCESS})})}closeCamera(){return n(this,void 0,void 0,function*(){return this._isOpenCamera?(h(exports.RCMediaType.VIDEO_ONLY,!1,x()),this._isOpenCamera=!1,this._store.getIsPubVideo()?this._invoker.push(new ae(exports.RCMediaType.VIDEO_ONLY,!1)):{code:exports.RCRTCCode.SUCCESS}):{code:exports.RCRTCCode.SUCCESS}})}switchCamera(){x().dispatch("switchCamera")}openMicphone(){return n(this,void 0,void 0,function*(){return this._isOpenMic?{code:exports.RCRTCCode.SUCCESS}:(h(exports.RCMediaType.AUDIO_ONLY,!0,x()),this._isOpenMic=!0,this._store.getIsPubAudio()?this._invoker.push(new ae(exports.RCMediaType.AUDIO_ONLY,!0)):{code:exports.RCRTCCode.SUCCESS})})}closeMicphone(){return n(this,void 0,void 0,function*(){return this._isOpenMic?(h(exports.RCMediaType.AUDIO_ONLY,!1,x()),this._isOpenMic=!1,this._store.getIsPubAudio()?this._invoker.push(new ae(exports.RCMediaType.AUDIO_ONLY,!1)):{code:exports.RCRTCCode.SUCCESS}):{code:exports.RCRTCCode.SUCCESS}})}publishStream(e="RongCloudRTC",t=exports.RCMediaType.AUDIO_VIDEO){return n(this,void 0,void 0,function*(){return this._invoker.push(new ee(e,t,this))})}unpublishStream(){return n(this,void 0,void 0,function*(){return this._invoker.push(new de)})}subscribe(e){return n(this,void 0,void 0,function*(){return this._invoker.push(new F(e))})}unsubscribe(e){return n(this,void 0,void 0,function*(){return this._invoker.push(new Y(e))})}_deleteReceiverNetStatus(e){e.map(e=>e.getMsid()).forEach(e=>{this._netStatusData.receiver&&delete this._netStatusData.receiver[e]})}_deleteSerderNetStatus(){delete this._netStatusData.sender}__onReconnected(){this._invoker.push(new Re)}__leaveHandle(e){return n(this,void 0,void 0,function*(){this.isDestroyed()||(this.emit(Te.LEAVE),this._invoker.destroy(),this._pinger.stop(),e&&(yield this._context.quitRTCRoom(this._roomId)),yield this._mediaServer.exit(),this.registerReportListener(null),this.onLocalAudioLevelChange(null),this.onRemoteAudioLevelChange(null),this._resourceListener=null,this._netStatusData=null)})}isCameraOpen(){return this._isOpenCamera}isMicphoneOpen(){return this._isOpenMic}isDestroyed(){return this._invoker.isDestroyed()}getRoomId(){return this._store.getRoomId()}getSessionId(){return this._store.getCrtSessionId()}getCrtUserId(){return this._context.getCurrentId()}getRemoteUserIds(){const e=this._context.getCurrentId();return this._store.getRemoteUserIds(e)}getRemoteStreams(){return Object.values(this._store.getRemoteStreams())}getRemoteStreamsByUserId(e){return this._store.getRemoteStreamByUserId(e)}sendMessage(e,t){return n(this,void 0,void 0,function*(){const{code:s}=yield this._context.sendMessage(i.ConversationType.RTC_ROOM,this._store.getRoomId(),{messageType:e,content:t,isStatusMessage:!0});return s!==i.ErrorCode.SUCCESS?(this._logger.warn(o.A_SEND_MSG_R,`send message failed -> code: ${s}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}})}setRoomAttribute(e,t,s,r=!1){return n(this,void 0,void 0,function*(){const n=yield this._context.setRTCData(this._store.getRoomId(),e,t,r,i.RTCApiType.ROOM,s);return n!==i.ErrorCode.SUCCESS?(this._logger.warn(o.A_SET_ROOM_ATTRS_R,`SetRoomAttributeValue Failed: ${n}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}})}deleteRoomAttributes(e,t,s=!1){return n(this,void 0,void 0,function*(){const n=yield this._context.removeRTCData(this._store.getRoomId(),e,s,i.RTCApiType.ROOM,t);return n!==i.ErrorCode.SUCCESS?(this._logger.warn(o.A_DEL_ROOM_ATTRS_R,`DeleteRoomAttribute Failed: ${n}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}})}getRoomAttributes(e=[],t=!1){return n(this,void 0,void 0,function*(){const{code:s,data:n}=yield this._context.getRTCData(this._store.getRoomId(),e,t,i.RTCApiType.ROOM);return s!==i.ErrorCode.SUCCESS?(this._logger.warn(o.A_GET_ROOM_ATTRS_R,`GetRoomAttributes Failed: ${s}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS,data:n}})}setAudioOutputDevice(e){x().setSoundMode(e)}getAudioOutputDevice(){return x().getSoundMode()}}class ge{constructor(e,t,s,o){this._context=e,this._logger=t,this._runtime=s,this._options=o,this._crtRoom=null,this._context.registerConnectionStateChangeListener(this._onIMStatusChange.bind(this)),this._context.registerDestroyListener(this._onIMUninit.bind(this)),this._context.registerMessageListener(this._handleMessage.bind(this))}_onIMStatusChange(e){this._logger.info(o.T,`signal server connection state change: ${e}`),e===i.RCConnectionStatus.CONNECTED&&this._crtRoom&&this._crtRoom.__onReconnected()}_onIMDisconnect(){this._logger.info(o.T,"IM disconnect")}_onIMUninit(){this._logger.info(o.T,"TODO -> on IM client ondestroy")}_handleMessage(e){var t;return e.conversationType===i.ConversationType.RTC_ROOM&&(null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),!0)}joinRTCRoom(e,t,s){return n(this,void 0,void 0,function*(){if(this._logger.info(o.T,`join room -> ${e}`),this._crtRoom)return this._logger.warn(o.T,"Repeat join!"),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=this._crtRoom=new Se(this._context,this._logger,this._runtime,this._options,e),i=yield t.__innerInitialize(s);return i!==exports.RCRTCCode.SUCCESS?(this._logger.warn(o.T,`join room failed: ${i}`),this._crtRoom=null,{code:i}):(this._logger.info(o.T,`join room success: ${e}`),t.once(Te.LEAVE,()=>{this._crtRoom=null}),{code:i,data:{room:t,userIds:t.getRemoteUserIds(),streams:t.getRemoteStreams()}})})}leaveRoom(e){return n(this,void 0,void 0,function*(){this._crtRoom===e&&(this._crtRoom.removeAll(Te.LEAVE),this._crtRoom=null),yield e.__leaveHandle(!0)})}}var Ee;exports.RCKickReason=void 0,(Ee=exports.RCKickReason||(exports.RCKickReason={}))[Ee.SERVER_KICK=1]="SERVER_KICK",Ee[Ee.OTHER_KICK=2]="OTHER_KICK";const Oe="rtcRJoin_data",fe="rtcRExit",ve="rtcRInfo",ye="rtcUDel",Ae="rtcSetData",Ne="userSetData",Le="rtcQryData",Ue="rtcDelData",De="rtcToken",be="rtcUserState",Pe="rtcUList",xe="rtcQueryJoined",Me="rtcPullRoomStatus",Ve="reportsdk",ke="rtcPing";var we;!function(e){e.RtcInput="RtcInput",e.RtcOutput="RtcOutput",e.RtcUserListOutput="RtcUserListOutput",e.SetUserStatusInput="SetUserStatusInput",e.RtcSetDataInput="RtcSetDataInput",e.RtcUserSetDataInput="RtcUserSetDataInput",e.RtcDataInput="RtcDataInput",e.RtcSetOutDataInput="RtcSetOutDataInput",e.MCFollowInput="MCFollowInput",e.RtcTokenOutput="RtcTokenOutput",e.RtcQryOutput="RtcQryOutput",e.RtcQryUserOutDataInput="RtcQryUserOutDataInput",e.RtcUserOutDataOutput="RtcUserOutDataOutput",e.RtcQueryListInput="RtcQueryListInput",e.RtcRoomInfoOutput="RtcRoomInfoOutput",e.RtcValueInfo="RtcValueInfo",e.RtcKeyDeleteInput="RtcKeyDeleteInput",e.RtcNotifyMsg="RtcNotifyMsg",e.RtcPullKV="RtcPullKV",e.RtcKVOutput="RtcKVOutput",e.RtcQueryUserJoinedInput="RtcQueryUserJoinedInput",e.RtcQueryUserJoinedOutput="RtcQueryUserJoinedOutput",e.RtcViewerJoinedOutput="RtcViewerJoinedOutput",e.RtcInviteInput="RtcInviteInput",e.RtcCancelInviteInput="RtcCancelInviteInput",e.RtcInviteAnswerInput="RtcInviteAnswerInput",e.RtcEndInv