@realsee/live 0.5.0-alpha.6 → 0.5.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/realsee-live.cjs.development.js +4 -1
- package/dist/realsee-live.cjs.development.js.map +1 -1
- package/dist/realsee-live.cjs.production.js +1 -1
- package/dist/realsee-live.cjs.production.js.map +1 -1
- package/dist/realsee-live.esm.js +4 -1
- package/dist/realsee-live.esm.js.map +1 -1
- package/dist/realsee-live.umd.development.js +4 -1
- package/dist/realsee-live.umd.development.js.map +1 -1
- package/dist/realsee-live.umd.production.js +1 -1
- package/dist/realsee-live.umd.production.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@realsee/jsbridge-x"),t=require("trtc-js-sdk"),i=require("amazon-chime-sdk-js"),o=require("react");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=s(e),r=s(t),a=s(o);const l=Symbol("$$REALSEE_LIVE_EVENT$$");function c(e){return e[l]||(e[l]={}),e[l]}class d{hasListener(e){const t=c(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=c(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[l]||delete i[l]);var i;const o=c(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let s=0;for(;s<o[e].length&&o[e][s][0]!==t;s++);s<o[e].length&&o[e].splice(s,1)}emit(e,...t){let i=!1;const o=c(this)[e]||[];for(let s of o.slice()){const[o,n=!1]=s,r=o(...t);n&&this.off(e,o),!1===r&&(i=!0)}return i}}class u extends d{}function h(e,t,i,o){return new(i||(i=Promise))((function(s,n){function r(e){try{l(o.next(e))}catch(e){n(e)}}function a(e){try{l(o.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}l((o=o.apply(e,t||[])).next())}))}var v,g,m,p,_,f,S,C,b,E,y,T,I;function k(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function w(){return(k()+k()+"-"+k()+"-4"+k().substr(0,3)+"-"+k()+"-"+k()+k()+k()).toLowerCase()}exports.RTCType=void 0,(v=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",v.RealseeVRWebViewRTC="RealseeVRWebViewRTC",v.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(g=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",g.RealseeXChimeRTC="chime";class R extends u{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserRTC,this.joined=!1,this.micro=!1,this.voiceId="",this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this._trtc={client:null,stream:null},this.join=e=>h(this,void 0,void 0,(function*(){var t;this.emit("joinWillStart");const i=yield this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=r.default.createClient(Object.assign({mode:"rtc"},i)),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let o=yield new Promise((t=>{var i;null===(i=this._trtc.client)||void 0===i||i.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=o,!!o&&(this._trtc.stream=r.default.createStream({userId:i.userId,audio:!0,video:!1}),o=yield new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),o=yield new Promise((e=>{var t;null===(t=this._trtc.client)||void 0===t||t.publish(this._trtc.stream).then((()=>e(!0))).catch((()=>e(!1)))})),this.joined=o,this.joined&&this.emit("joined"),o)})),this._handleStreamAdded=e=>{var t;const i=e.stream;console.log("远端流增加: "+i.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(i)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const i=`rs-rtc-remote_stream-${t.getId()}`,o=document.createElement("div");o.id=i,this.$dom.appendChild(o),t.play(i)},this._getVoiceSign=e.getVoiceSign,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${w()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((e=>h(this,void 0,void 0,(function*(){var t,i;this.joined=!1,this._trtc.stream&&(yield null===(t=this._trtc.client)||void 0===t?void 0:t.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),null===(i=this._trtc.client)||void 0===i||i.leave().then((()=>this._trtc.client=null)).then((()=>e(!0))).catch((()=>e(!1)))}))))}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){console.error(t),e(!1)}}))}toggleMicro(e){var t,i,o,s;return Promise.resolve((e?null===(i=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===i?void 0:i.unmuteAudio():null===(s=null===(o=this._trtc)||void 0===o?void 0:o.stream)||void 0===s?void 0:s.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,i,o;null===(e=this._trtc.client)||void 0===e||e.on("stream-added",this._handleStreamAdded),null===(t=this._trtc.client)||void 0===t||t.on("stream-subscribed",this._handleStreamSubscribed),null===(i=this._trtc.client)||void 0===i||i.on("audio-volume",(e=>this.emit("userVolumes",[{userId:e.userId,audioVolume:e.audioVolume}]))),null===(o=this._trtc.client)||void 0===o||o.on("error",(e=>this.emit("error",e)))}}class O extends u{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserChimeRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.userId="",this.deviceChangeObserver={},this.audioVideoObserver={},this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this.$audio=document.createElement("audio"),this._initDom=()=>{this.$audio.id=`rs-rtc-${w()}`,this.$dom.id=`rs-rtc-${w()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)},this.initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{null==e||e.forEach((e=>{this.logger.info(`Device ID: ${e.deviceId} Microphone: ${e.label}`)}))},audioOutputsChanged:e=>{this.logger.info(`Audio outputs updated: ${e}`)},videoInputsChanged:e=>{this.logger.info(`Video inputs updated: ${e}`)},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`)},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect")}}},this._registerRtcEvent=()=>{var e,t,o,s,n,r;const a=(null===(o=null===(t=null===(e=this.meetingSession)||void 0===e?void 0:e.configuration)||void 0===t?void 0:t.credentials)||void 0===o?void 0:o.attendeeId)||"";if(a){const e=new Map,t=()=>{const t=[];return e.forEach(((e,i)=>{t.push({userId:e.userId,volume:e.muted||0===e.signalStrength||!Boolean(e.volume)?0:e.volume})})),t};null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToAttendeeIdPresence(((o,s,n)=>{var r;if(!s)return e.delete(o),void this.emit("userVolumes",t());null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToVolumeIndicator(o,((o,s,r,a)=>{new i.DefaultModality(o).base()===o&&(e.set(o,{userId:n||o,volume:s,muted:r,signalStrength:a}),this.emit("userVolumes",t()))}))})),null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToVolumeIndicator(a,((e,t,o,s)=>{new i.DefaultModality(e).base()===e&&null!==s&&1!==s&&this.emit("weakNetwork")})),null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=e.getVoiceSign,this._initDom(),this.logger=new i.ConsoleLogger("WebRTCLogger",e.logLevel||i.LogLevel.OFF),this.deviceController=new i.DefaultDeviceController(this.logger),this.initObservers()}join(e){return h(this,void 0,void 0,(function*(){return new Promise(((t,o)=>h(this,void 0,void 0,(function*(){var o;this.emit("joinWillStart");try{const{sdkAppId:s,userId:n,roomId:r,userSig:a}=yield this._getVoiceSign(Object.assign(Object.assign({},e),{roomId:e.roomId||0}));this.userId=n;const{attendence:l,vendor_wrapper:c}=JSON.parse(decodeURIComponent(a)),d=new i.MeetingSessionConfiguration({Meeting:c},{Attendee:{ExternalUserId:l.external_user_id,AttendeeId:l.attendee_id,JoinToken:l.join_token}});this.meetingSession=new i.DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const u={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0)},audioVideoDidStop:()=>{this.joined=!1,t(!1)}};this.meetingSession.audioVideo.addObserver(u);const h=yield this.deviceController.listAudioInputDevices(!0),v=h.find((e=>"default"===e.deviceId)),g=h.find((e=>""!==e.deviceId));this.audioInput=v||g,yield this.meetingSession.audioVideo.chooseVideoInputDevice(null),yield this.meetingSession.audioVideo.chooseAudioInputDevice((null===(o=this.audioInput)||void 0===o?void 0:o.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),t(!1)}}))))}))}quit(){return this.joined?new Promise(((e,t)=>{var o,s;this.joined=!1;const n={audioVideoDidStop:t=>{const o=t.statusCode();o===i.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${o}`),e(!0))}};null===(o=this.meetingSession)||void 0===o||o.audioVideo.addObserver(n),null===(s=this.meetingSession)||void 0===s||s.audioVideo.stop()})):Promise.resolve(!0)}detectMicro(){return h(this,void 0,void 0,(function*(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){this.logger.error(t.message),e(!1)}}))}))}toggleMicro(e){var t,i,o;return h(this,void 0,void 0,(function*(){e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeMuteLocalAudio();const s=null===(o=this.meetingSession)||void 0===o?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return void 0!==s&&e!==s}))}shock(){throw new Error("Method not implemented.")}}exports.RTCJoinedInfoCodeEnum=void 0,(m=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[m.Success=0]="Success",m[m.Failure=1]="Failure",m[m.ReJoin=2]="ReJoin",m[m.NoMicroPermission=3]="NoMicroPermission";class x extends u{constructor({jsBridge:e,getVoiceSign:t}){super(),this.type=exports.RTCType.RealseeVRWebViewRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.options={jsBridge:e,getVoiceSign:t},"WxMiniProgramWebView"!==this.jsBridge.webViewType&&this.jsBridge.callAndListen("live/userVolumes",(e=>{this.emit("userVolumes",e)})),this.jsBridge.callAndListen("live/weakNetwork",(e=>{e&&this.emit("weakNetwork")}))}get jsBridge(){return this.options.jsBridge}join(e){return h(this,void 0,void 0,(function*(){this.emit("joinWillStart");const{sdkAppId:t,userId:i,userSig:o}=yield this.options.getVoiceSign(e);this.type=e.type;const[s,n]=yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${i}&roomID=${Number(e.voiceId)}&userSig=${o}`);return s?s.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",s),this.joined=!1):(this.emit("error",n||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}))}quit(){return h(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}))}detectMicro(){return h(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}))}toggleMicro(e){return h(this,void 0,void 0,(function*(){const[t,i]=yield this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",i||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}))}shock(){this.jsBridge.shock(1)}}function L(e){switch(e){case 1001:return exports.WebSocketCloseError.Err_1001;case 1002:return exports.WebSocketCloseError.Err_1002;case 1003:return exports.WebSocketCloseError.Err_1003;case 1006:return exports.WebSocketCloseError.Err_1006;case 1007:return exports.WebSocketCloseError.Err_1007;case 1008:return exports.WebSocketCloseError.Err_1008;case 1009:return exports.WebSocketCloseError.Err_1009}return exports.WebSocketCloseError.Err_unknown}function N(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}exports.Command=void 0,(p=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",p.RoomInfo="ROOM_INFO",p.RTCInfo="RTC_INFO",p.UserList="USER_LIST",p.BuiltinMsg="BUILTIN_MSG",p.CustomEvent="CUSTOM_EVENT",p.KeyframeSync="KEYFRAME_SYNC",p.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(_=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",_.RoomChange="room_change",exports.BuiltinActionType=void 0,(f=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",f.UserMicroStatusSync="sync_micro_status",f.UserPermission="change_permission",f.UserStatus="change_status",f.UserInfo="change_info",f.RoomClose="close",exports.MicroStatus=void 0,(S=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",S.CLOSE="CLOSE",exports.LiveState=void 0,(C=exports.LiveState||(exports.LiveState={}))[C.NOTINITIALIZED=-1]="NOTINITIALIZED",C[C.CONNECTING=0]="CONNECTING",C[C.OPEN=1]="OPEN",C[C.CLOSED=3]="CLOSED",exports.UserStatus=void 0,(b=exports.UserStatus||(exports.UserStatus={}))[b.Normal=0]="Normal",b[b.Removed=1]="Removed",b[b.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(E=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",E.ONLINE="ONLINE",E.LEAVE="LEAVE",E.KICK_OUT="KICK_OUT",E.BE_REPLACE="BE_REPLACE",E.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(y=exports.WebSocketState||(exports.WebSocketState={}))[y.NOTINITIALIZED=-1]="NOTINITIALIZED",y[y.CONNECTING=0]="CONNECTING",y[y.OPEN=1]="OPEN",y[y.CLOSING=2]="CLOSING",y[y.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(T=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",T.Close="Close",T.MicroAuth="MicroAuth",T.DuplicateConnect="DuplicateConnect",T.IllegalURL="IllegalURL",T.Unknown="Unknown",T.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(I=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",I.Err_1002="CLOSE_PROTOCOL_ERROR",I.Err_1003="CLOSE_UNSUPPORTED",I.Err_1006="CLOSE_ABNORMAL",I.Err_1007="Unsupported Data",I.Err_1008="Policy Violation",I.Err_1009="CLOSE_TOO_LARGE",I.Err_unknown="unknown";var M,j,A=(M=function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0,function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(i=t.LogLevel||(t.LogLevel={})),t.default=i},M(j={exports:{}},j.exports),j.exports),V=N(A);const B=globalThis.navigator.userAgent,W=/android/gi.test(B),D=/iPhone|iPad\s+OS/gi.test(B),U=/MicroMessenger/gi.test(B)&&/miniProgram/gi.test(B),P=/realsee/gi.test(B);function $(e){return"[object Object]"===Object.prototype.toString.call(e)}function F(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function K(e,t){return!!F(e,t)||($(e)&&$(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,s=i.length;o<s;o++){const s=i[o];if(!F(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!F(e[i],t[i]))return!1;return!0}(e,t))}function G(e,t){return!!F(e,t)||($(e)&&$(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,s=i.length;o<s;o++){const s=i[o];if(!G(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!G(e[i],t[i]))return!1;return!0}(e,t))}function H(e,t,i){return i.deep?G(e,t):K(e,t)}var q;!function(e){e.info="INFO",e.log="LOG",e.error="ERROR",e.warn="WARN"}(q||(q={}));const J=(e,t=[])=>{switch(t.unshift(`Realsee Live ${(()=>{const e=new Date;return`[${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds()}]`})()} <${e}> `),e){case q.info:return console.info(...t);case q.error:return console.error(...t);case q.warn:return console.warn(...t);default:return console.log(...t)}};var Z={log:(...e)=>J(q.log,e),info:(...e)=>J(q.info,e),error:(...e)=>J(q.error,e),warn:(...e)=>J(q.warn,e)};class X extends d{constructor(e){super(),this._readyState=exports.WebSocketState.NOTINITIALIZED,this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._healthCheck=()=>h(this,void 0,void 0,(function*(){this._realWebSocket&&this._realWebSocket.readyState!==this._readyState&&(this._readyState=this._realWebSocket.readyState,this._readyState===exports.WebSocketState.CLOSING&&this.emit("closing")),yield new Promise((e=>setTimeout(e,2e3))),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)})),this._clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)},this._startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)},this._stopHealthCheck=()=>{this._clearHeathCheckIfNeed()},this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3,"offline")},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._removeWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.removeEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.removeEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.removeEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.removeEventListener("message",this._webSocketMessageHandler)},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e),this._startHealthCheck()}get attempts(){return this._attempts}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,s;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const n=null===(s=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===s?void 0:s.call(o,e,this);"number"==typeof n&&(this._pendingReconnect=setTimeout(this._createWebSocket,n))}}class Y extends d{constructor(){super(),this._ws=new X,this._state=exports.LiveState.NOTINITIALIZED,this._addWebSocketEventListeners=()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)},this._removeWebSocketEventListeners=()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)},this._handleCloseEvent=e=>{Z.info(`live room closed bacause of ${e.code}-${e.reason||L(e.code)}`),this.state=exports.LiveState.CLOSED},this._handleClosingEvent=()=>{var e;Z.info("live room is closing, onLine:",null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===e?void 0:e.onLine),this.state=exports.LiveState.CLOSED},this._handleConnectingEvent=()=>{Z.info("live room is connecting"),this.state=exports.LiveState.CONNECTING},this._handleErrorEvent=e=>{Z.error("live room error",e),this.state=exports.LiveState.CLOSED},this._handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch(t){return e.data}})();this.emit("message",t)},this._handleOpenEvent=e=>{Z.info("live room open",e.detail),this.state=exports.LiveState.OPEN,e.detail.reconnects>0&&this.emit("reconnected",e.detail)},this._handleTimeoutEvent=e=>{Z.error("live room connect timeout!",e.detail),this.state=exports.LiveState.CLOSED},this.dispose=()=>h(this,void 0,void 0,(function*(){return this._removeWebSocketEventListeners(),yield this.close("live room close by controller disposed!")})),this.open=e=>this._ws.open(e),this.close=(e,t)=>new Promise((i=>{this._ws.once("close",(()=>i(!0))),this._ws.close(e,t)})),this._addWebSocketEventListeners()}set state(e){const t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t)}get state(){return this._state}sendMessage(e=""){if(null==e||""===e)throw new Error("live message is empty!");if(this.state===exports.LiveState.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}}const z=e=>Promise.reject("unimplemented method GetVoiceSign"),Q=(e,t={},i=[])=>({command:e,front_request_id:w(),data:Object.assign(Object.assign({},t),{to_user_ids:Array.isArray(i)?i:[i]})});class ee extends d{constructor(e){var t;super(),this._options={},this.keyframes=new d,this._buildInData={keyframes:{}},this.getFramesByKey=e=>this.snapshot[e],this.sendKeyframe=(e,t)=>{if(this.state!==exports.LiveState.OPEN)return!1;this._buildInData.keyframes=Object.assign(Object.assign({},this._buildInData.keyframes),{[e]:t});const i=Q(exports.Command.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(i),!0}catch(e){return Z.error(e),!1}},this._controller=new Y,this._addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)},this._removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)},this._handleStateChange=(e,t)=>this.emit("stateChange",e,t),this._handleMessage=e=>h(this,void 0,void 0,(function*(){var t,i,o,s,n,r;if("object"==typeof e){const{command:a,data:l,frontRequestId:c,code:d,message:u}=e;if("SUCCESS"===d)switch(a){case exports.Command.SelfUserInfo:{const e=l;H(this.selfInfo,e,{deep:!0})||(this._buildInData.selfInfo=e,this.emit("selfInfoUpdate",this._buildInData.selfInfo,c));break}case exports.Command.RoomInfo:{const e=l;this._buildInData.roomInfo=Object.assign({},e),this.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:a}=l;if(this._buildInData.rtcInfo={voiceId:e,type:a},null===(t=this.$RTC)||void 0===t?void 0:t.joined)Z.warn("已加入语音房间,无需重复加入!");else{if(yield null===(i=this.$RTC)||void 0===i?void 0:i.join({voiceId:e,userId:(null===(o=this.selfInfo)||void 0===o?void 0:o.id)||"",roomId:null===(s=this.roomInfo)||void 0===s?void 0:s.info.room_code,type:a})){const e=null!==(n=this._options.initialMicroStatus)&&void 0!==n?n:exports.MicroStatus.OPEN;yield null===(r=this.$RTC)||void 0===r?void 0:r.toggleMicro(e===exports.MicroStatus.OPEN)}else Z.error("加入语音房间失败")}break}case exports.Command.UserList:{const e=l;this._buildInData.userList=e,this.emit("userListUpdate",this.userList,c);break}case exports.Command.CustomEvent:{const e=l;this.emit("broadcast",e,c);break}case exports.Command.KeyframeSync:{const e=l,t=Object.keys(e).reduce(((t,i)=>{if(H(e[i],this._buildInData.keyframes[i],{deep:!0}))return t;const o=[e[i],this._buildInData.keyframes[i],c],s=i;return this.keyframes.emit(s,...o),this._buildInData.keyframes[i]=e[i],t[i]=e[i],t}),{});this.emit("keyframes",t,c);break}case exports.Command.BuiltinMsg:{const e=l;this.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&this.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&this.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&(yield this.toggleMicro(e.data.status===exports.MicroStatus.OPEN)),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(yield this.exit());break}case exports.Command.UserKickOut:this.emit("kickOut");break;default:console.warn("unknown command: ",a)}else this.emit("error",e)}})),this._clearLiveData=()=>{this._buildInData={keyframes:{}}},this.connect=(e={})=>h(this,void 0,void 0,(function*(){var t,i,o,s;if(this._options.url=null!==(i=null!==(t=e.url)&&void 0!==t?t:this._options.url)&&void 0!==i?i:"",this._options.getTicket=null!==(o=e.getTicket)&&void 0!==o?o:this._options.getTicket,this._options.initialMicroStatus=null!==(s=e.rtcMicStatus)&&void 0!==s?s:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||"function"!=typeof this._options.getTicket)return/^ws(s):\/\//.test(this._options.url)?"function"!=typeof this._options.getTicket&&new Error("getTicket muse be function"):new Error("Illegal realsee live room link");const{force:n=!1}=e,r=this.state;if(r===exports.LiveState.CONNECTING||r===exports.LiveState.OPEN){if(!n)return new Error("已有Live实例正在连接中,请勿重复连接!");try{yield this._controller.close("force close by connect")}catch(e){console.warn(e)}}this._clearLiveData();const a=function(e,t){const i=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,o,s)=>`${e}${0!==s||i?"&":"?"}${o}=${t[o]}`),"")}(this._options.url,{ticket:yield this._options.getTicket(),force:Number(!!n)});return this._controller.open(a),!0})),this.exit=()=>h(this,void 0,void 0,(function*(){var e;this._clearLiveData();try{null===(e=this.$RTC)||void 0===e||e.quit(),yield this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})}catch(e){Z.warn(e)}return yield this._controller.close("user exit")})),this.dispose=()=>h(this,void 0,void 0,(function*(){return this._removeLiveControllerEventListeners(),this._clearLiveData(),yield this._controller.dispose()})),this.setSelfInfo=e=>h(this,void 0,void 0,(function*(){return yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)})),this.toggleMicro=e=>h(this,void 0,void 0,(function*(){var t,i,o;if(!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.control_own_micro))return!1;const s=yield null===(o=this.$RTC)||void 0===o?void 0:o.toggleMicro(e);return s&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[])),s})),this.forbidMicro=(e,t)=>h(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserMicro&&!this._options.canForbidUserMicro(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_micro)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t)))})),this.forbidSync=(e,t)=>h(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserSync&&!this._options.canForbidUserSync(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_sync)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t)))})),this.kick=e=>h(this,void 0,void 0,(function*(){var t,i;return!("function"==typeof this._options.canForbidUserKick&&!this._options.canForbidUserKick(e))&&(!!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.change_other_status)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e)))})),this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:exports.MicroStatus.OPEN},e),this._options.jsBridge=e.jsBridge?e.jsBridge:e.useBuiltInJsBridge?new n.default:void 0,this._options.getVoiceSign=null!==(t=e.getVoiceSign)&&void 0!==t?t:z,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||Z.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:return this._options.jsBridge?new x({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):void Z.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");case exports.RTCType.RealseeBrowserChimeRTC:return new O({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?V.DEBUG:V.ERROR});case exports.RTCType.RealseeBrowserRTC:return new R({getVoiceSign:this._options.getVoiceSign});default:return void Z.error("unknown built-in RTC type")}return e.useBuiltInRTC?(e.getVoiceSign||Z.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge?P&&(W||D)||U?new x({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new O({getVoiceSign:this._options.getVoiceSign}):new R({getVoiceSign:this._options.getVoiceSign}):void Z.error("jsBridge instance must be passed when using built-in RTC instances")):void 0})(),this._options.rtc||Z.warn("unused rtc"),this._options.url&&this._options.getTicket&&this.connect(),this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})}get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}updateStatus(e,t,i,o){return h(this,void 0,void 0,(function*(){if(this.state!==exports.LiveState.OPEN)return!1;const s=Object.assign({event_type:e,action:t},{data:i}),n=Q(exports.Command.BuiltinMsg,s,o);try{return this._controller.sendMessage(n),!0}catch(e){return Z.error(e),!1}}))}broadcast(e,t,i){return this.state===exports.LiveState.OPEN&&new Promise(((o,s)=>{const n=Q(exports.Command.CustomEvent,e,t),r=n.front_request_id,a=i?setTimeout((()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l)}),i):void 0,l=(e,t)=>{t===r&&(a&&clearTimeout(a),this.off("broadcast",l),o(e))};this.on("broadcast",l);try{this._controller.sendMessage(n)}catch(e){s(e)}}))}}const te=e=>{var t,i;return(null===window||void 0===window?void 0:window.__Realsee_Live__)&&(null===(i=null===(t=null===window||void 0===window?void 0:window.__Realsee_Live__)||void 0===t?void 0:t.dispose)||void 0===i||i.call(t),window.__Realsee_Live__=null),new ee(e)};exports.BrowserRTC=R,exports.BrowserRTC4Chime=O,exports.CoreRTC=u,exports.VRWebViewRTC=x,exports.createLive=te,exports.createLiveReact=function(e){const t=o.createContext(null),i=te(e),s=i.jsBridge,n=()=>{const e=a.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e},r=o.useCallback((()=>n()),[n]),l=o.useCallback((()=>n().$RTC),[n]),c=o.useCallback((()=>l()),[l]),d=o.useCallback((e=>h(this,void 0,void 0,(function*(){return yield n().connect(e)}))),[]);return{live:i,jsBridge:s,LiveProvider:e=>a.default.createElement(t.Provider,{value:i},e.children),unsafe__useLiveInstance:r,unsafe__useRTCInstance:c,useConnect:d,useKeyframe:function(e){const t=n(),[i,o]=a.default.useState(t.getFramesByKey(e));return a.default.useEffect((()=>{const i=e,s=e=>o(e);return t.keyframes.on(i,s),()=>t.keyframes.off(i,s)}),[t]),[i,a.default.useCallback((i=>t.sendKeyframe(e,i)),[t])]},useKeyframeUpdateCallback:function(e,t,i=[]){const o=n(),s=[o,name,...i],r=()=>o.keyframes.off(e,t);return a.default.useEffect((()=>(o.keyframes.on(e,t),r)),s),r},useLiveAction:function(){const e=n(),t=a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.connect(t)}))),[e]),i=a.default.useCallback((t=>e.toggleMicro(t)),[e]),o=a.default.useCallback(((t,i,o=0)=>h(this,void 0,void 0,(function*(){return yield e.broadcast(t,i,o)}))),[e]),s=a.default.useCallback((()=>h(this,void 0,void 0,(function*(){return yield e.exit()}))),[e]),r=a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.kick(t)}))),[e]),l=a.default.useCallback(((t,i=[])=>h(this,void 0,void 0,(function*(){return yield e.forbidMicro(t,i)}))),[e]),c=a.default.useCallback(((t,i=[])=>e.forbidSync(t,i)),[e]),d=a.default.useCallback((t=>e.getFramesByKey(t)),[e]);return{connect:t,broadcast:o,exit:s,kick:r,toggleMicro:i,forbidMicro:l,forbidSync:c,sendKeyframe:a.default.useCallback(((t,i)=>e.sendKeyframe(t,i)),[e]),getFramesByKey:d,setSelfInfo:a.default.useCallback((t=>e.setSelfInfo(t)),[e]),updateStatus:a.default.useCallback(((t,i,o,s)=>e.updateStatus(t,i,o,s)),[e])}},useLiveEventCallback:function(e,t,i=[]){const o=n(),s=()=>o.off(e,t),r=[o,e,...i];return a.default.useEffect((()=>(o.on(e,t),s)),r),s},useLiveState:function(){const e=n(),[t,i]=a.default.useState(e.state);return a.default.useEffect((()=>{const t=e=>i(e);return e.on("stateChange",t),()=>e.off("stateChange",t)}),[e]),t},useRTCAction:function(){const e=n(),t=a.default.useCallback((t=>e.$RTC.join(t)),[e]);return{join:t,quit:a.default.useCallback((()=>e.$RTC.quit()),[e]),shock:a.default.useCallback((()=>{var t,i;return null===(i=(t=e.$RTC).shock)||void 0===i?void 0:i.call(t)}),[e]),toggleMicro:a.default.useCallback((t=>e.$RTC.toggleMicro(t)),[e]),detectMicro:a.default.useCallback((()=>e.$RTC.detectMicro()),[e])}},useRTCEventCallback:function(e,t,i=[]){const o=n(),s=()=>o.$RTC.off(e,t),r=[o,e,...i];return a.default.useEffect((()=>(o.$RTC.on(e,t),s)),r),s},useSelfInfo:function(){const e=n(),[t,i]=a.default.useState(e.selfInfo||{}),o=e=>i(e);return a.default.useEffect((()=>(e.on("selfInfoUpdate",o),()=>e.off("selfInfoUpdate",o))),[e]),[t,a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.setSelfInfo(t)}))),[e])]},useKeyframesSnapshot:function(){const e=n(),[t,i]=a.default.useState(e.snapshot);return a.default.useEffect((()=>{const t=e=>i(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=n(),[t,i]=a.default.useState(e.userList),o=e=>i(e);return a.default.useEffect((()=>(e.on("userListUpdate",o),()=>e.off("userListUpdate",o))),[e]),t}}},exports.parseLiveMsg=function(e){try{const t=JSON.parse(e),i={code:t.code,message:t.message,command:t.command,roomCode:t.room_code,appID:t.app_id,requestId:t.request_id,frontRequestId:t.front_request_id,triggerUserID:t.trigger_user_id,data:t.data||{}},o=Object.keys(i).filter((e=>void 0===i[e]));return o.length>0&&console.warn(`推送数据格式异常:${o.join(" ")} 值不存在!`),i}catch(e){return!1}},exports.parseWSClsErr=L;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@realsee/jsbridge-x"),t=require("trtc-js-sdk"),i=require("amazon-chime-sdk-js"),o=require("react");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=s(e),r=s(t),a=s(o);const l=Symbol("$$REALSEE_LIVE_EVENT$$");function c(e){return e[l]||(e[l]={}),e[l]}class d{hasListener(e){const t=c(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=c(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[l]||delete i[l]);var i;const o=c(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let s=0;for(;s<o[e].length&&o[e][s][0]!==t;s++);s<o[e].length&&o[e].splice(s,1)}emit(e,...t){let i=!1;const o=c(this)[e]||[];for(let s of o.slice()){const[o,n=!1]=s,r=o(...t);n&&this.off(e,o),!1===r&&(i=!0)}return i}}class u extends d{}function h(e,t,i,o){return new(i||(i=Promise))((function(s,n){function r(e){try{l(o.next(e))}catch(e){n(e)}}function a(e){try{l(o.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}l((o=o.apply(e,t||[])).next())}))}var v,g,m,p,_,f,S,C,b,E,y,T,I;function k(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function w(){return(k()+k()+"-"+k()+"-4"+k().substr(0,3)+"-"+k()+"-"+k()+k()+k()).toLowerCase()}exports.RTCType=void 0,(v=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",v.RealseeVRWebViewRTC="RealseeVRWebViewRTC",v.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(g=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",g.RealseeXChimeRTC="chime";class R extends u{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserRTC,this.joined=!1,this.micro=!1,this.voiceId="",this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this._trtc={client:null,stream:null},this.join=e=>h(this,void 0,void 0,(function*(){var t;this.emit("joinWillStart");const i=yield this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=r.default.createClient(Object.assign({mode:"rtc"},i)),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let o=yield new Promise((t=>{var i;null===(i=this._trtc.client)||void 0===i||i.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=o,!!o&&(this._trtc.stream=r.default.createStream({userId:i.userId,audio:!0,video:!1}),o=yield new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),o=yield new Promise((e=>{var t;null===(t=this._trtc.client)||void 0===t||t.publish(this._trtc.stream).then((()=>e(!0))).catch((()=>e(!1)))})),this.joined=o,this.joined&&this.emit("joined"),o)})),this._handleStreamAdded=e=>{var t;const i=e.stream;console.log("远端流增加: "+i.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(i)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const i=`rs-rtc-remote_stream-${t.getId()}`,o=document.createElement("div");o.id=i,this.$dom.appendChild(o),t.play(i)},this._getVoiceSign=e.getVoiceSign,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${w()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((e=>h(this,void 0,void 0,(function*(){var t,i;this.joined=!1,this._trtc.stream&&(yield null===(t=this._trtc.client)||void 0===t?void 0:t.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),null===(i=this._trtc.client)||void 0===i||i.leave().then((()=>this._trtc.client=null)).then((()=>e(!0))).catch((()=>e(!1)))}))))}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){console.error(t),e(!1)}}))}toggleMicro(e){var t,i,o,s;return Promise.resolve((e?null===(i=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===i?void 0:i.unmuteAudio():null===(s=null===(o=this._trtc)||void 0===o?void 0:o.stream)||void 0===s?void 0:s.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,i,o;null===(e=this._trtc.client)||void 0===e||e.on("stream-added",this._handleStreamAdded),null===(t=this._trtc.client)||void 0===t||t.on("stream-subscribed",this._handleStreamSubscribed),null===(i=this._trtc.client)||void 0===i||i.on("audio-volume",(e=>this.emit("userVolumes",[{userId:e.userId,audioVolume:e.audioVolume}]))),null===(o=this._trtc.client)||void 0===o||o.on("error",(e=>this.emit("error",e)))}}class O extends u{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserChimeRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.userId="",this.deviceChangeObserver={},this.audioVideoObserver={},this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this.$audio=document.createElement("audio"),this._initDom=()=>{this.$audio.id=`rs-rtc-${w()}`,this.$dom.id=`rs-rtc-${w()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)},this.initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{null==e||e.forEach((e=>{this.logger.info(`Device ID: ${e.deviceId} Microphone: ${e.label}`)}))},audioOutputsChanged:e=>{this.logger.info(`Audio outputs updated: ${e}`)},videoInputsChanged:e=>{this.logger.info(`Video inputs updated: ${e}`)},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`)},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect")}}},this._registerRtcEvent=()=>{var e,t,o,s,n,r;const a=(null===(o=null===(t=null===(e=this.meetingSession)||void 0===e?void 0:e.configuration)||void 0===t?void 0:t.credentials)||void 0===o?void 0:o.attendeeId)||"";if(a){const e=new Map,t=()=>{const t=[];return e.forEach(((e,i)=>{t.push({userId:e.userId,volume:e.muted||0===e.signalStrength||!Boolean(e.volume)?0:e.volume})})),t};null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToAttendeeIdPresence(((o,s,n)=>{var r;if(!s)return e.delete(o),void this.emit("userVolumes",t());null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToVolumeIndicator(o,((o,s,r,a)=>{new i.DefaultModality(o).base()===o&&(e.set(o,{userId:n||o,volume:s,muted:r,signalStrength:a}),this.emit("userVolumes",t()))}))})),null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToVolumeIndicator(a,((e,t,o,s)=>{new i.DefaultModality(e).base()===e&&null!==s&&1!==s&&this.emit("weakNetwork")})),null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=e.getVoiceSign,this._initDom(),this.logger=new i.ConsoleLogger("WebRTCLogger",e.logLevel||i.LogLevel.OFF),this.deviceController=new i.DefaultDeviceController(this.logger),this.initObservers()}join(e){return h(this,void 0,void 0,(function*(){return new Promise(((t,o)=>h(this,void 0,void 0,(function*(){var o;this.emit("joinWillStart");try{const{sdkAppId:s,userId:n,roomId:r,userSig:a}=yield this._getVoiceSign(Object.assign(Object.assign({},e),{roomId:e.roomId||0}));this.userId=n;const{attendence:l,vendor_wrapper:c}=JSON.parse(decodeURIComponent(a)),d=new i.MeetingSessionConfiguration({Meeting:c},{Attendee:{ExternalUserId:l.external_user_id,AttendeeId:l.attendee_id,JoinToken:l.join_token}});this.meetingSession=new i.DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const u={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0)},audioVideoDidStop:()=>{this.joined=!1,t(!1)}};this.meetingSession.audioVideo.addObserver(u);const h=yield this.deviceController.listAudioInputDevices(!0),v=h.find((e=>"default"===e.deviceId)),g=h.find((e=>""!==e.deviceId));this.audioInput=v||g,yield this.meetingSession.audioVideo.chooseVideoInputDevice(null),yield this.meetingSession.audioVideo.chooseAudioInputDevice((null===(o=this.audioInput)||void 0===o?void 0:o.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),t(!1)}}))))}))}quit(){return this.joined?new Promise(((e,t)=>{var o,s;this.joined=!1;const n={audioVideoDidStop:t=>{const o=t.statusCode();o===i.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${o}`),e(!0))}};null===(o=this.meetingSession)||void 0===o||o.audioVideo.addObserver(n),null===(s=this.meetingSession)||void 0===s||s.audioVideo.stop()})):Promise.resolve(!0)}detectMicro(){return h(this,void 0,void 0,(function*(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){this.logger.error(t.message),e(!1)}}))}))}toggleMicro(e){var t,i,o;return h(this,void 0,void 0,(function*(){e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeMuteLocalAudio();const s=null===(o=this.meetingSession)||void 0===o?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return void 0!==s&&e!==s}))}shock(){throw new Error("Method not implemented.")}}exports.RTCJoinedInfoCodeEnum=void 0,(m=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[m.Success=0]="Success",m[m.Failure=1]="Failure",m[m.ReJoin=2]="ReJoin",m[m.NoMicroPermission=3]="NoMicroPermission";class x extends u{constructor({jsBridge:e,getVoiceSign:t}){super(),this.type=exports.RTCType.RealseeVRWebViewRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.options={jsBridge:e,getVoiceSign:t},"WxMiniProgramWebView"!==this.jsBridge.webViewType&&this.jsBridge.callAndListen("live/userVolumes",(e=>{this.emit("userVolumes",e)})),this.jsBridge.callAndListen("live/weakNetwork",(e=>{e&&this.emit("weakNetwork")}))}get jsBridge(){return this.options.jsBridge}join(e){return h(this,void 0,void 0,(function*(){this.emit("joinWillStart");const{sdkAppId:t,userId:i,userSig:o}=yield this.options.getVoiceSign(e);this.type=e.type;const[s,n]=yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${i}&roomID=${Number(e.voiceId)}&userSig=${o}`);return s?s.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",s),this.joined=!1):(this.emit("error",n||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}))}quit(){return h(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}))}detectMicro(){return h(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}))}toggleMicro(e){return h(this,void 0,void 0,(function*(){const[t,i]=yield this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",i||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}))}shock(){this.jsBridge.shock(1)}}function L(e){switch(e){case 1001:return exports.WebSocketCloseError.Err_1001;case 1002:return exports.WebSocketCloseError.Err_1002;case 1003:return exports.WebSocketCloseError.Err_1003;case 1006:return exports.WebSocketCloseError.Err_1006;case 1007:return exports.WebSocketCloseError.Err_1007;case 1008:return exports.WebSocketCloseError.Err_1008;case 1009:return exports.WebSocketCloseError.Err_1009}return exports.WebSocketCloseError.Err_unknown}function N(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}exports.Command=void 0,(p=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",p.RoomInfo="ROOM_INFO",p.RTCInfo="RTC_INFO",p.UserList="USER_LIST",p.BuiltinMsg="BUILTIN_MSG",p.CustomEvent="CUSTOM_EVENT",p.KeyframeSync="KEYFRAME_SYNC",p.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(_=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",_.RoomChange="room_change",exports.BuiltinActionType=void 0,(f=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",f.UserMicroStatusSync="sync_micro_status",f.UserPermission="change_permission",f.UserStatus="change_status",f.UserInfo="change_info",f.RoomClose="close",exports.MicroStatus=void 0,(S=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",S.CLOSE="CLOSE",exports.LiveState=void 0,(C=exports.LiveState||(exports.LiveState={}))[C.NOTINITIALIZED=-1]="NOTINITIALIZED",C[C.CONNECTING=0]="CONNECTING",C[C.OPEN=1]="OPEN",C[C.CLOSED=3]="CLOSED",exports.UserStatus=void 0,(b=exports.UserStatus||(exports.UserStatus={}))[b.Normal=0]="Normal",b[b.Removed=1]="Removed",b[b.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(E=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",E.ONLINE="ONLINE",E.LEAVE="LEAVE",E.KICK_OUT="KICK_OUT",E.BE_REPLACE="BE_REPLACE",E.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(y=exports.WebSocketState||(exports.WebSocketState={}))[y.NOTINITIALIZED=-1]="NOTINITIALIZED",y[y.CONNECTING=0]="CONNECTING",y[y.OPEN=1]="OPEN",y[y.CLOSING=2]="CLOSING",y[y.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(T=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",T.Close="Close",T.MicroAuth="MicroAuth",T.DuplicateConnect="DuplicateConnect",T.IllegalURL="IllegalURL",T.Unknown="Unknown",T.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(I=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",I.Err_1002="CLOSE_PROTOCOL_ERROR",I.Err_1003="CLOSE_UNSUPPORTED",I.Err_1006="CLOSE_ABNORMAL",I.Err_1007="Unsupported Data",I.Err_1008="Policy Violation",I.Err_1009="CLOSE_TOO_LARGE",I.Err_unknown="unknown";var M,j,A=(M=function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0,function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(i=t.LogLevel||(t.LogLevel={})),t.default=i},M(j={exports:{}},j.exports),j.exports),V=N(A);const B=globalThis.navigator.userAgent,W=/android/gi.test(B),D=/iPhone|iPad\s+OS/gi.test(B),U=/MicroMessenger/gi.test(B)&&/miniProgram/gi.test(B),P=/realsee/gi.test(B);function $(e){return"[object Object]"===Object.prototype.toString.call(e)}function F(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function K(e,t){return!!F(e,t)||($(e)&&$(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,s=i.length;o<s;o++){const s=i[o];if(!F(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!F(e[i],t[i]))return!1;return!0}(e,t))}function G(e,t){return!!F(e,t)||($(e)&&$(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,s=i.length;o<s;o++){const s=i[o];if(!G(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!G(e[i],t[i]))return!1;return!0}(e,t))}function H(e,t,i){return i.deep?G(e,t):K(e,t)}var q;!function(e){e.info="INFO",e.log="LOG",e.error="ERROR",e.warn="WARN"}(q||(q={}));const J=(e,t=[])=>{switch(t.unshift(`Realsee Live ${(()=>{const e=new Date;return`[${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds()}]`})()} <${e}> `),e){case q.info:return console.info(...t);case q.error:return console.error(...t);case q.warn:return console.warn(...t);default:return console.log(...t)}};var Z={log:(...e)=>J(q.log,e),info:(...e)=>J(q.info,e),error:(...e)=>J(q.error,e),warn:(...e)=>J(q.warn,e)};class X extends d{constructor(e){super(),this._readyState=exports.WebSocketState.NOTINITIALIZED,this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._healthCheck=()=>h(this,void 0,void 0,(function*(){this._realWebSocket&&this._realWebSocket.readyState!==this._readyState&&(this._readyState=this._realWebSocket.readyState,this._readyState===exports.WebSocketState.CLOSING&&this.emit("closing")),yield new Promise((e=>setTimeout(e,2e3))),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)})),this._clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)},this._startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)},this._stopHealthCheck=()=>{this._clearHeathCheckIfNeed()},this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3,"offline")},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._removeWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.removeEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.removeEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.removeEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.removeEventListener("message",this._webSocketMessageHandler)},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e),this._startHealthCheck()}get attempts(){return this._attempts}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,s;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const n=null===(s=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===s?void 0:s.call(o,e,this);"number"==typeof n&&(this._pendingReconnect=setTimeout(this._createWebSocket,n))}}class Y extends d{constructor(){super(),this._ws=new X({url:"",robustOptions:{timeout:18e4}}),this._state=exports.LiveState.NOTINITIALIZED,this._addWebSocketEventListeners=()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)},this._removeWebSocketEventListeners=()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)},this._handleCloseEvent=e=>{Z.info(`live room closed bacause of ${e.code}-${e.reason||L(e.code)}`),this.state=exports.LiveState.CLOSED},this._handleClosingEvent=()=>{var e;Z.info("live room is closing, onLine:",null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===e?void 0:e.onLine),this.state=exports.LiveState.CLOSED},this._handleConnectingEvent=()=>{Z.info("live room is connecting"),this.state=exports.LiveState.CONNECTING},this._handleErrorEvent=e=>{Z.error("live room error",e),this.state=exports.LiveState.CLOSED},this._handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch(t){return e.data}})();this.emit("message",t)},this._handleOpenEvent=e=>{Z.info("live room open",e.detail),this.state=exports.LiveState.OPEN,e.detail.reconnects>0&&this.emit("reconnected",e.detail)},this._handleTimeoutEvent=e=>{Z.error("live room connect timeout!",e.detail),this.state=exports.LiveState.CLOSED},this.dispose=()=>h(this,void 0,void 0,(function*(){return this._removeWebSocketEventListeners(),yield this.close("live room close by controller disposed!")})),this.open=e=>this._ws.open(e),this.close=(e,t)=>new Promise((i=>{this._ws.once("close",(()=>i(!0))),this._ws.close(e,t)})),this._addWebSocketEventListeners()}set state(e){const t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t)}get state(){return this._state}sendMessage(e=""){if(null==e||""===e)throw new Error("live message is empty!");if(this.state===exports.LiveState.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}}const z=e=>Promise.reject("unimplemented method GetVoiceSign"),Q=(e,t={},i=[])=>({command:e,front_request_id:w(),data:Object.assign(Object.assign({},t),{to_user_ids:Array.isArray(i)?i:[i]})});class ee extends d{constructor(e){var t;super(),this._options={},this.keyframes=new d,this._buildInData={keyframes:{}},this.getFramesByKey=e=>this.snapshot[e],this.sendKeyframe=(e,t)=>{if(this.state!==exports.LiveState.OPEN)return!1;this._buildInData.keyframes=Object.assign(Object.assign({},this._buildInData.keyframes),{[e]:t});const i=Q(exports.Command.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(i),!0}catch(e){return Z.error(e),!1}},this._controller=new Y,this._addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)},this._removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)},this._handleStateChange=(e,t)=>this.emit("stateChange",e,t),this._handleMessage=e=>h(this,void 0,void 0,(function*(){var t,i,o,s,n,r;if("object"==typeof e){const{command:a,data:l,frontRequestId:c,code:d,message:u}=e;if("SUCCESS"===d)switch(a){case exports.Command.SelfUserInfo:{const e=l;H(this.selfInfo,e,{deep:!0})||(this._buildInData.selfInfo=e,this.emit("selfInfoUpdate",this._buildInData.selfInfo,c));break}case exports.Command.RoomInfo:{const e=l;this._buildInData.roomInfo=Object.assign({},e),this.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:a}=l;if(this._buildInData.rtcInfo={voiceId:e,type:a},null===(t=this.$RTC)||void 0===t?void 0:t.joined)Z.warn("已加入语音房间,无需重复加入!");else{if(yield null===(i=this.$RTC)||void 0===i?void 0:i.join({voiceId:e,userId:(null===(o=this.selfInfo)||void 0===o?void 0:o.id)||"",roomId:null===(s=this.roomInfo)||void 0===s?void 0:s.info.room_code,type:a})){const e=null!==(n=this._options.initialMicroStatus)&&void 0!==n?n:exports.MicroStatus.OPEN;yield null===(r=this.$RTC)||void 0===r?void 0:r.toggleMicro(e===exports.MicroStatus.OPEN)}else Z.error("加入语音房间失败")}break}case exports.Command.UserList:{const e=l;this._buildInData.userList=e,this.emit("userListUpdate",this.userList,c);break}case exports.Command.CustomEvent:{const e=l;this.emit("broadcast",e,c);break}case exports.Command.KeyframeSync:{const e=l,t=Object.keys(e).reduce(((t,i)=>{if(H(e[i],this._buildInData.keyframes[i],{deep:!0}))return t;const o=[e[i],this._buildInData.keyframes[i],c],s=i;return this.keyframes.emit(s,...o),this._buildInData.keyframes[i]=e[i],t[i]=e[i],t}),{});this.emit("keyframes",t,c);break}case exports.Command.BuiltinMsg:{const e=l;this.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&this.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&this.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&(yield this.toggleMicro(e.data.status===exports.MicroStatus.OPEN)),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(yield this.exit());break}case exports.Command.UserKickOut:this.emit("kickOut");break;default:console.warn("unknown command: ",a)}else this.emit("error",e)}})),this._clearLiveData=()=>{this._buildInData={keyframes:{}}},this.connect=(e={})=>h(this,void 0,void 0,(function*(){var t,i,o,s;if(this._options.url=null!==(i=null!==(t=e.url)&&void 0!==t?t:this._options.url)&&void 0!==i?i:"",this._options.getTicket=null!==(o=e.getTicket)&&void 0!==o?o:this._options.getTicket,this._options.initialMicroStatus=null!==(s=e.rtcMicStatus)&&void 0!==s?s:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||"function"!=typeof this._options.getTicket)return/^ws(s):\/\//.test(this._options.url)?"function"!=typeof this._options.getTicket&&new Error("getTicket muse be function"):new Error("Illegal realsee live room link");const{force:n=!1}=e,r=this.state;if(r===exports.LiveState.CONNECTING||r===exports.LiveState.OPEN){if(!n)return new Error("已有Live实例正在连接中,请勿重复连接!");try{yield this._controller.close("force close by connect")}catch(e){console.warn(e)}}this._clearLiveData();const a=function(e,t){const i=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,o,s)=>`${e}${0!==s||i?"&":"?"}${o}=${t[o]}`),"")}(this._options.url,{ticket:yield this._options.getTicket(),force:Number(!!n)});return this._controller.open(a),!0})),this.exit=()=>h(this,void 0,void 0,(function*(){var e;this._clearLiveData();try{null===(e=this.$RTC)||void 0===e||e.quit(),yield this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})}catch(e){Z.warn(e)}return yield this._controller.close("user exit")})),this.dispose=()=>h(this,void 0,void 0,(function*(){return this._removeLiveControllerEventListeners(),this._clearLiveData(),yield this._controller.dispose()})),this.setSelfInfo=e=>h(this,void 0,void 0,(function*(){return yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)})),this.toggleMicro=e=>h(this,void 0,void 0,(function*(){var t,i,o;if(!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.control_own_micro))return!1;const s=yield null===(o=this.$RTC)||void 0===o?void 0:o.toggleMicro(e);return s&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[])),s})),this.forbidMicro=(e,t)=>h(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserMicro&&!this._options.canForbidUserMicro(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_micro)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t)))})),this.forbidSync=(e,t)=>h(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserSync&&!this._options.canForbidUserSync(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_sync)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t)))})),this.kick=e=>h(this,void 0,void 0,(function*(){var t,i;return!("function"==typeof this._options.canForbidUserKick&&!this._options.canForbidUserKick(e))&&(!!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.change_other_status)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e)))})),this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:exports.MicroStatus.OPEN},e),this._options.jsBridge=e.jsBridge?e.jsBridge:e.useBuiltInJsBridge?new n.default:void 0,this._options.getVoiceSign=null!==(t=e.getVoiceSign)&&void 0!==t?t:z,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||Z.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:return this._options.jsBridge?new x({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):void Z.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");case exports.RTCType.RealseeBrowserChimeRTC:return new O({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?V.DEBUG:V.ERROR});case exports.RTCType.RealseeBrowserRTC:return new R({getVoiceSign:this._options.getVoiceSign});default:return void Z.error("unknown built-in RTC type")}return e.useBuiltInRTC?(e.getVoiceSign||Z.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge?P&&(W||D)||U?new x({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new O({getVoiceSign:this._options.getVoiceSign}):new R({getVoiceSign:this._options.getVoiceSign}):void Z.error("jsBridge instance must be passed when using built-in RTC instances")):void 0})(),this._options.rtc||Z.warn("unused rtc"),this._options.url&&this._options.getTicket&&this.connect(),this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})}get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}updateStatus(e,t,i,o){return h(this,void 0,void 0,(function*(){if(this.state!==exports.LiveState.OPEN)return!1;const s=Object.assign({event_type:e,action:t},{data:i}),n=Q(exports.Command.BuiltinMsg,s,o);try{return this._controller.sendMessage(n),!0}catch(e){return Z.error(e),!1}}))}broadcast(e,t,i){return this.state===exports.LiveState.OPEN&&new Promise(((o,s)=>{const n=Q(exports.Command.CustomEvent,e,t),r=n.front_request_id,a=i?setTimeout((()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l)}),i):void 0,l=(e,t)=>{t===r&&(a&&clearTimeout(a),this.off("broadcast",l),o(e))};this.on("broadcast",l);try{this._controller.sendMessage(n)}catch(e){s(e)}}))}}const te=e=>{var t,i;return(null===window||void 0===window?void 0:window.__Realsee_Live__)&&(null===(i=null===(t=null===window||void 0===window?void 0:window.__Realsee_Live__)||void 0===t?void 0:t.dispose)||void 0===i||i.call(t),window.__Realsee_Live__=null),new ee(e)};exports.BrowserRTC=R,exports.BrowserRTC4Chime=O,exports.CoreRTC=u,exports.VRWebViewRTC=x,exports.createLive=te,exports.createLiveReact=function(e){const t=o.createContext(null),i=te(e),s=i.jsBridge,n=()=>{const e=a.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e},r=o.useCallback((()=>n()),[n]),l=o.useCallback((()=>n().$RTC),[n]),c=o.useCallback((()=>l()),[l]),d=o.useCallback((e=>h(this,void 0,void 0,(function*(){return yield n().connect(e)}))),[]);return{live:i,jsBridge:s,LiveProvider:e=>a.default.createElement(t.Provider,{value:i},e.children),unsafe__useLiveInstance:r,unsafe__useRTCInstance:c,useConnect:d,useKeyframe:function(e){const t=n(),[i,o]=a.default.useState(t.getFramesByKey(e));return a.default.useEffect((()=>{const i=e,s=e=>o(e);return t.keyframes.on(i,s),()=>t.keyframes.off(i,s)}),[t]),[i,a.default.useCallback((i=>t.sendKeyframe(e,i)),[t])]},useKeyframeUpdateCallback:function(e,t,i=[]){const o=n(),s=[o,name,...i],r=()=>o.keyframes.off(e,t);return a.default.useEffect((()=>(o.keyframes.on(e,t),r)),s),r},useLiveAction:function(){const e=n(),t=a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.connect(t)}))),[e]),i=a.default.useCallback((t=>e.toggleMicro(t)),[e]),o=a.default.useCallback(((t,i,o=0)=>h(this,void 0,void 0,(function*(){return yield e.broadcast(t,i,o)}))),[e]),s=a.default.useCallback((()=>h(this,void 0,void 0,(function*(){return yield e.exit()}))),[e]),r=a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.kick(t)}))),[e]),l=a.default.useCallback(((t,i=[])=>h(this,void 0,void 0,(function*(){return yield e.forbidMicro(t,i)}))),[e]),c=a.default.useCallback(((t,i=[])=>e.forbidSync(t,i)),[e]),d=a.default.useCallback((t=>e.getFramesByKey(t)),[e]);return{connect:t,broadcast:o,exit:s,kick:r,toggleMicro:i,forbidMicro:l,forbidSync:c,sendKeyframe:a.default.useCallback(((t,i)=>e.sendKeyframe(t,i)),[e]),getFramesByKey:d,setSelfInfo:a.default.useCallback((t=>e.setSelfInfo(t)),[e]),updateStatus:a.default.useCallback(((t,i,o,s)=>e.updateStatus(t,i,o,s)),[e])}},useLiveEventCallback:function(e,t,i=[]){const o=n(),s=()=>o.off(e,t),r=[o,e,...i];return a.default.useEffect((()=>(o.on(e,t),s)),r),s},useLiveState:function(){const e=n(),[t,i]=a.default.useState(e.state);return a.default.useEffect((()=>{const t=e=>i(e);return e.on("stateChange",t),()=>e.off("stateChange",t)}),[e]),t},useRTCAction:function(){const e=n(),t=a.default.useCallback((t=>e.$RTC.join(t)),[e]);return{join:t,quit:a.default.useCallback((()=>e.$RTC.quit()),[e]),shock:a.default.useCallback((()=>{var t,i;return null===(i=(t=e.$RTC).shock)||void 0===i?void 0:i.call(t)}),[e]),toggleMicro:a.default.useCallback((t=>e.$RTC.toggleMicro(t)),[e]),detectMicro:a.default.useCallback((()=>e.$RTC.detectMicro()),[e])}},useRTCEventCallback:function(e,t,i=[]){const o=n(),s=()=>o.$RTC.off(e,t),r=[o,e,...i];return a.default.useEffect((()=>(o.$RTC.on(e,t),s)),r),s},useSelfInfo:function(){const e=n(),[t,i]=a.default.useState(e.selfInfo||{}),o=e=>i(e);return a.default.useEffect((()=>(e.on("selfInfoUpdate",o),()=>e.off("selfInfoUpdate",o))),[e]),[t,a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.setSelfInfo(t)}))),[e])]},useKeyframesSnapshot:function(){const e=n(),[t,i]=a.default.useState(e.snapshot);return a.default.useEffect((()=>{const t=e=>i(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=n(),[t,i]=a.default.useState(e.userList),o=e=>i(e);return a.default.useEffect((()=>(e.on("userListUpdate",o),()=>e.off("userListUpdate",o))),[e]),t}}},exports.parseLiveMsg=function(e){try{const t=JSON.parse(e),i={code:t.code,message:t.message,command:t.command,roomCode:t.room_code,appID:t.app_id,requestId:t.request_id,frontRequestId:t.front_request_id,triggerUserID:t.trigger_user_id,data:t.data||{}},o=Object.keys(i).filter((e=>void 0===i[e]));return o.length>0&&console.warn(`推送数据格式异常:${o.join(" ")} 值不存在!`),i}catch(e){return!1}},exports.parseWSClsErr=L;
|
|
2
2
|
//# sourceMappingURL=realsee-live.cjs.production.js.map
|