@realsee/live 0.4.0-alpha.3 → 0.4.0-beta.1
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/README.md +74 -54
- package/dist/realsee-live.cjs.development.js +51 -5
- 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 +51 -6
- package/dist/realsee-live.esm.js.map +1 -1
- package/dist/realsee-live.umd.development.js +1803 -36
- 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/dist/typings/live/Live.d.ts +6 -1
- package/dist/typings/live/LiveOptions.d.ts +14 -1
- package/dist/typings/react/LiveReact.d.ts +2 -0
- package/dist/typings/rtc/type.d.ts +4 -0
- package/package.json +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("amazon-chime-sdk-js"),t=require("trtc-js-sdk"),o=require("react");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=r(t),s=r(o);const n=Symbol("$$REALSEE_LIVE_EVENT$$");function a(e){return e[n]||(e[n]={}),e[n]}class c{hasListener(e){const t=a(this);return t&&t[e]&&t[e].length>0}on(e,t,o){const r=a(this);return r[e]||(r[e]=[]),r[e].push([t,o||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((o=this)[n]||delete o[n]);var o;const r=a(this);if(r[e]||(r[e]=[]),void 0===t)return void(r[e].length=0);let i=0;for(;i<r[e].length&&r[e][i][0]!==t;i++);i<r[e].length&&r[e].splice(i,1)}emit(e,...t){let o=!1;const r=a(this)[e]||[];for(let i of r.slice()){const[r,s=!1]=i,n=r(...t);s&&this.off(e,r),!1===n&&(o=!0)}return o}}class u extends c{}var d,l,h,p,m,f,g,v,S,E,C;function y(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function b(){return(y()+y()+"-"+y()+"-4"+y().substr(0,3)+"-"+y()+"-"+y()+y()+y()).toLowerCase()}exports.RTCType=void 0,(d=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",d.RealseeVRWebViewRTC="RealseeVRWebViewRTC",d.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC";class k 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=async e=>{var t;this.emit("joinWillStart");const o=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=i.default.createClient({mode:"rtc",...o}),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let r=await new Promise((t=>{var o;null===(o=this._trtc.client)||void 0===o||o.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=r,!!r&&(this._trtc.stream=i.default.createStream({userId:o.userId,audio:!0,video:!1}),r=await new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),r=await 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=r,this.joined&&this.emit("joined"),r)},this._handleStreamAdded=e=>{var t;const o=e.stream;console.log("远端流增加: "+o.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(o)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const o=`rs-rtc-remote_stream-${t.getId()}`,r=document.createElement("div");r.id=o,this.$dom.appendChild(r),t.play(o)},this._getVoiceSign=e.getVoiceSign,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${b()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((async e=>{var t,o;this.joined=!1,this._trtc.stream&&(await(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===(o=this._trtc.client)||void 0===o||o.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,o,r,i;return Promise.resolve((e?null===(o=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===o?void 0:o.unmuteAudio():null===(i=null===(r=this._trtc)||void 0===r?void 0:r.stream)||void 0===i?void 0:i.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,o,r;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===(o=this._trtc.client)||void 0===o||o.on("audio-volume",(e=>this.emit("userVolumes",[{userId:e.userId,audioVolume:e.audioVolume}]))),null===(r=this._trtc.client)||void 0===r||r.on("error",(e=>this.emit("error",e)))}}class w extends u{constructor(t){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-${b()}`,this.$dom.id=`rs-rtc-${b()}`,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 t,o,r,i,s,n;const a=(null===(r=null===(o=null===(t=this.meetingSession)||void 0===t?void 0:t.configuration)||void 0===o?void 0:o.credentials)||void 0===r?void 0:r.attendeeId)||"";if(a){const t=new Map,o=()=>{const e=[];return t.forEach(((t,o)=>{e.push({userId:t.userId,volume:t.muted||0===t.signalStrength||!Boolean(t.volume)?0:t.volume})})),e};null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeSubscribeToAttendeeIdPresence(((r,i,s)=>{var n;if(!i)return t.delete(r),void this.emit("userVolumes",o());null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToVolumeIndicator(r,((r,i,n,a)=>{new e.DefaultModality(r).base()===r&&(t.set(r,{userId:s||r,volume:i,muted:n,signalStrength:a}),this.emit("userVolumes",o()))}))})),null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToVolumeIndicator(a,((t,o,r,i)=>{new e.DefaultModality(t).base()===t&&null!==i&&1!==i&&this.emit("weakNetwork")})),null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=t.getVoiceSign,this._initDom(),this.logger=new e.ConsoleLogger("WebRTCLogger",t.logLevel||e.LogLevel.OFF),this.deviceController=new e.DefaultDeviceController(this.logger),this.initObservers()}async join(t){return new Promise((async(o,r)=>{var i;this.emit("joinWillStart");try{const{sdkAppId:r,userId:s,roomId:n,userSig:a}=await this._getVoiceSign({...t,roomId:t.roomId||0});this.userId=s;const{attendence:c,vendor_wrapper:u}=JSON.parse(decodeURIComponent(a)),d=new e.MeetingSessionConfiguration({Meeting:u},{Attendee:{ExternalUserId:c.external_user_id,AttendeeId:c.attendee_id,JoinToken:c.join_token}});this.meetingSession=new e.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 l={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),o(!0)},audioVideoDidStop:()=>{this.joined=!1,o(!1)}};this.meetingSession.audioVideo.addObserver(l);const h=await this.deviceController.listAudioInputDevices(!0),p=h.find((e=>"default"===e.deviceId)),m=h.find((e=>""!==e.deviceId));this.audioInput=p||m,await this.meetingSession.audioVideo.chooseVideoInputDevice(null),await this.meetingSession.audioVideo.chooseAudioInputDevice((null===(i=this.audioInput)||void 0===i?void 0:i.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),o(!1)}}))}quit(){return new Promise(((t,o)=>{var r,i;this.joined=!1;const s={audioVideoDidStop:o=>{const r=o.statusCode();r===e.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),t(!0)):(this.logger.info(`Stopped with a session status code: ${r}`),t(!0))}};null===(r=this.meetingSession)||void 0===r||r.audioVideo.addObserver(s),null===(i=this.meetingSession)||void 0===i||i.audioVideo.stop()}))}async detectMicro(){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)}}))}async toggleMicro(e){var t,o,r;e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(o=this.meetingSession)||void 0===o||o.audioVideo.realtimeMuteLocalAudio();const i=null===(r=this.meetingSession)||void 0===r?void 0:r.audioVideo.realtimeIsLocalAudioMuted();return void 0!==i&&e!==i}shock(){throw new Error("Method not implemented.")}}exports.RTCJoinedInfoCodeEnum=void 0,(l=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[l.Success=0]="Success",l[l.Failure=1]="Failure",l[l.ReJoin=2]="ReJoin",l[l.NoMicroPermission=3]="NoMicroPermission";class I 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},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}async join(e){this.emit("joinWillStart");const{sdkAppId:t,userId:o,userSig:r}=await this.options.getVoiceSign(e);this.type=e.type;const[i,s]=await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${o}&roomID=${Number(e.voiceId)}&userSig=${r}`);return i?i.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",i),this.joined=!1):(this.emit("error",s||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}async quit(){const[e,t]=await this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}async detectMicro(){const[e,t]=await this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}async toggleMicro(e){const[t,o]=await this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",o||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}shock(){this.jsBridge.shock(1)}}function T(e){try{const t=JSON.parse(e),o={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||{}},r=Object.keys(o).filter((e=>void 0===o[e]));return r.length>0&&console.warn(`推送数据格式异常:${r.join(" ")} 值不存在!`),o}catch(e){return!1}}function _(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 R(e){return"[object Object]"===Object.prototype.toString.call(e)}function x(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function L(e,t){return!!x(e,t)||(R(e)&&R(t)?function(e,t){const o=Object.getOwnPropertyNames(e),r=Object.getOwnPropertyNames(t);if(o.length!==r.length)return!1;for(let r=0,i=o.length;r<i;r++){const i=o[r];if(!x(e[i],t[i]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let o=0,r=e.length;o<r;o++)if(!x(e[o],t[o]))return!1;return!0}(e,t))}function O(e,t){return!!x(e,t)||(R(e)&&R(t)?function(e,t){const o=Object.getOwnPropertyNames(e),r=Object.getOwnPropertyNames(t);if(o.length!==r.length)return!1;for(let r=0,i=o.length;r<i;r++){const i=o[r];if(!O(e[i],t[i]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let o=0,r=e.length;o<r;o++)if(!O(e[o],t[o]))return!1;return!0}(e,t))}function U(e,t,o){return o.deep?O(e,t):L(e,t)}exports.Command=void 0,(h=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",h.RoomInfo="ROOM_INFO",h.RTCInfo="RTC_INFO",h.UserList="USER_LIST",h.BuiltinMsg="BUILTIN_MSG",h.CustomEvent="CUSTOM_EVENT",h.KeyframeSync="KEYFRAME_SYNC",h.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(p=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",p.RoomChange="room_change",exports.BuiltinActionType=void 0,(m=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",m.UserMicroStatusSync="sync_micro_status",m.UserPermission="change_permission",m.UserStatus="change_status",m.UserInfo="change_info",m.RoomClose="close",exports.MicroStatus=void 0,(f=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",f.CLOSE="CLOSE",exports.UserStatus=void 0,(g=exports.UserStatus||(exports.UserStatus={}))[g.Normal=0]="Normal",g[g.Removed=1]="Removed",g[g.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(v=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",v.ONLINE="ONLINE",v.LEAVE="LEAVE",v.KICK_OUT="KICK_OUT",v.BE_REPLACE="BE_REPLACE",v.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(S=exports.WebSocketState||(exports.WebSocketState={}))[S.NOTINITIALIZED=-1]="NOTINITIALIZED",S[S.CONNECTING=0]="CONNECTING",S[S.OPEN=1]="OPEN",S[S.CLOSING=2]="CLOSING",S[S.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(E=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",E.Close="Close",E.MicroAuth="MicroAuth",E.DuplicateConnect="DuplicateConnect",E.IllegalURL="IllegalURL",E.Unknown="Unknown",E.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(C=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",C.Err_1002="CLOSE_PROTOCOL_ERROR",C.Err_1003="CLOSE_UNSUPPORTED",C.Err_1006="CLOSE_ABNORMAL",C.Err_1007="Unsupported Data",C.Err_1008="Policy Violation",C.Err_1009="CLOSE_TOO_LARGE",C.Err_unknown="unknown";class M{constructor(e){this.readyState=exports.WebSocketState.NOTINITIALIZED,this.canSync=!0,this.connecting=!1,this.keyframes={},this.checkReadyState=e=>{do{if(!this.webSocket){this.readyState!==exports.WebSocketState.NOTINITIALIZED&&(this.readyState=exports.WebSocketState.NOTINITIALIZED,e.emit("ws.readyStateUpdate",this.readyState));break}const t=this.webSocket.readyState;t!==this.readyState&&(this.readyState=t,e.emit("ws.readyStateUpdate",this.readyState))}while(0);return this.readyState},this.dispose=()=>{this.disposeWebSocket(),this.connecting=!1,this.healthCheckId&&(clearInterval(this.healthCheckId),this.healthCheckId=void 0)},this.disposeWebSocket=()=>{this.webSocket&&(this.onEvtOpnListener&&(this.webSocket.removeEventListener("open",this.onEvtOpnListener),this.onEvtOpnListener=void 0),this.onEvtMsgListener&&(this.webSocket.removeEventListener("message",this.onEvtMsgListener),this.onEvtMsgListener=void 0),this.onEvtErrListener&&(this.webSocket.removeEventListener("error",this.onEvtErrListener),this.onEvtErrListener=void 0),this.onEvtCLEListener&&(this.webSocket.removeEventListener("close",this.onEvtCLEListener),this.onEvtCLEListener=void 0),this.webSocket.close(),this.webSocket=void 0)},this.options=Object.assign({autoConnect:!0,healthCheck:3e3},e)}handleMessage(e,t){var o,r,i;const{command:s,data:n,frontRequestId:a,code:c,message:u}=e;if("SUCCESS"===c)switch(s){case exports.Command.SelfUserInfo:{const e=n;if(U(this.selfUserInfo,e,{deep:!0}))return;this.selfUserInfo=e,t.emit("selfInfoUpdate",this.selfUserInfo,a);break}case exports.Command.RoomInfo:{const e=n;this.roomInfo=Object.assign({},e),t.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:i}=n;if(t.$RTC.joined)break;t.$RTC.join({voiceId:e,userId:(null===(o=this.selfUserInfo)||void 0===o?void 0:o.id)||"",roomId:null===(r=this.roomInfo)||void 0===r?void 0:r.info.room_code,type:i}),t.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:exports.MicroStatus.OPEN});break}case exports.Command.UserList:{const e=n;this.userList=e,t.emit("userListUpdate",this.userList,a);break}case exports.Command.CustomEvent:{const e=n;t.emit("broadcast",e,a);break}case exports.Command.KeyframeSync:{const e=n,o=Object.keys(e).reduce(((o,r)=>{if(U(e[r],this.keyframes[r],{deep:!0}))return o;const i=[e[r],this.keyframes[r],a],s=r;return t.keyframes.emit(s,...i),this.keyframes[r]=e[r],o[r]=e[r],o}),{});t.emit("keyframes",o,a);break}case exports.Command.BuiltinMsg:{const e=n;t.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&t.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&t.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&t.toggleMicro(e.data.status===exports.MicroStatus.OPEN),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(null===(i=this.options.rtc)||void 0===i||i.quit(),this.disposeWebSocket());break}case exports.Command.UserKickOut:t.emit("kickOut");break;default:console.warn("unknown command: ",s)}else t.emit("error",e)}sendMessage(e){return this.webSocket?e?void this.webSocket.send(JSON.stringify(e)):console.warn("WebSocket messages is empty!"):console.warn("WebSocket has not yet been initialized!")}}const N=e=>Promise.reject("unimplemented method GetVoiceSign");function V(t){const o=new M(t),r=(e,t={},o)=>((o=o?Array.isArray(o)?o:[o]:[])&&(t.to_user_ids=o),{command:e,front_request_id:b(),data:t});const i=new class extends c{constructor(){var r;if(super(),this.keyframes=new c,!t.rtc&&t.rtcType){if(!t.getVoiceSign)throw new Error("GetVoiceSign method must be passed when using built-in RTC instances");const i=null!==(r=t.getVoiceSign)&&void 0!==r?r:N;switch(t.rtcType){case exports.RTCType.RealseeVRWebViewRTC:if(!t.jsBridge)throw new Error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");o.options.rtc=new I({jsBridge:t.jsBridge,getVoiceSign:i});break;case exports.RTCType.RealseeBrowserChimeRTC:o.options.rtc=new w({getVoiceSign:i,logLevel:t.__debug__?e.LogLevel.DEBUG:e.LogLevel.ERROR});break;case exports.RTCType.RealseeBrowserRTC:o.options.rtc=new k({getVoiceSign:i});break;default:throw new Error("unknown built-in RTC type")}}o.options.rtc||console.warn("unused rtc"),o.options.url&&o.options.getTicket&&this.connect();const i=(e=>{if(!e)return 0;if(!0===e)return 3e3;const t=Number(e);return t>0?t:3e3})(o.options.healthCheck);i&&(o.healthCheckId=setInterval((()=>o.checkReadyState(this)),i))}get options(){return Object.freeze(Object.assign({},o.options))}get readyState(){return o.checkReadyState(this),o.readyState}get url(){var e;return(null===(e=o.webSocket)||void 0===e?void 0:e.url)||""}get selfInfo(){return o.selfUserInfo}get userList(){return o.userList||[]}get snapshot(){return o.keyframes||{}}get $RTC(){return o.options.rtc}async setSelfInfo(e){if(this.readyState!==exports.WebSocketState.OPEN)return new Error("The connection is not open and ready to communicate.");try{return await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)}catch(e){return e}}getFramesByKey(e){return o.keyframes[e]}sendKeyframe(e,t){if(this.readyState!==exports.WebSocketState.OPEN)return new Error("The connection is not open and ready to communicate.");o.keyframes[e]=t;const i=r(exports.Command.KeyframeSync,this.snapshot);return o.sendMessage(i),!0}broadcast(e,t,i){return this.readyState!==exports.WebSocketState.OPEN?new Error("The connection is not open and ready to communicate."):new Promise(((s,n)=>{const a=r(exports.Command.CustomEvent,e,t),c=a.front_request_id;o.sendMessage(a);const u=i?setTimeout((()=>{n(new Error("RESPONSE TIMEOUT")),this.off("broadcast",d)}),i):void 0,d=(e,t)=>{t===c&&(this.off("broadcast",d),s(e),u&&clearInterval(u))};this.on("broadcast",d)}))}async updateStatus(e,t,i,s){if(this.readyState!==exports.WebSocketState.OPEN)return!1;const n=Object.assign({event_type:e,action:t},{data:i}),a=r(exports.Command.BuiltinMsg,n,s);return o.sendMessage(a),!0}async toggleMicro(e){var t,o;return!!(null===(o=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===o?void 0:o.control_own_micro)&&(await this.$RTC.toggleMicro(e),await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[]))}async forbidMicro(e,t){var r,i;return!(o.options.canForbidUserMicro&&!o.options.canForbidUserMicro(t))&&(!!(null===(i=null===(r=this.selfInfo)||void 0===r?void 0:r.permission)||void 0===i?void 0:i.control_other_micro)&&await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t))}async forbidSync(e,t){var r,i;return!(o.options.canForbidUserSync&&!o.options.canForbidUserSync(t))&&(!!(null===(i=null===(r=this.selfInfo)||void 0===r?void 0:r.permission)||void 0===i?void 0:i.control_other_sync)&&await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t))}async kick(e){var t,r;return!(o.options.canForbidUserKick&&!o.options.canForbidUserKick(e))&&(!!(null===(r=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===r?void 0:r.change_other_status)&&await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e))}async exit(){return await this.$RTC.quit(),await this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})}async connect(e={}){if(!await this.$RTC.detectMicro()){const e=new Error("系统监测麦克风未授权~");return this.emit("ws.error",{type:exports.WebSocketErrorType.MicroAuth,error:e}),e}if(o.connecting){const e=new Error("WebSocket 正在连接中,请勿重复连接 ...");return this.emit("ws.error",{type:exports.WebSocketErrorType.DuplicateConnect,error:e}),e}const{force:t}=e;if(!t&&(this.readyState===exports.WebSocketState.CONNECTING||this.readyState===exports.WebSocketState.OPEN))return!0;if(e.url&&(o.options.url=e.url),e.getTicket&&(o.options.getTicket=e.getTicket),!o.options.url||!o.options.url.startsWith("ws")){const e=new Error(`WebSocket URL 未配置或格式不合法:"${o.options.url}"`);return this.emit("ws.error",{type:exports.WebSocketErrorType.IllegalURL,error:e}),e}if(!o.options.getTicket){const e=new Error("getTicket() 未配置!");return this.emit("ws.error",{type:exports.WebSocketErrorType.IllegalArgs,error:e}),e}o.connecting=!0,o.disposeWebSocket(),this.emit("ws.beforeConnect");const r=t||e.url||!this.url?function(e,t){const o=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,r,i)=>`${e}${0!==i||o?"&":"?"}${r}=${t[r]}`),"")}(o.options.url,{ticket:await o.options.getTicket(),force:Number(!!t)}):this.url;return o.webSocket=new WebSocket(r),o.onEvtOpnListener=()=>{o.checkReadyState(this),this.emit("ws.afterConnect")},o.onEvtMsgListener=e=>{o.checkReadyState(this);try{const t=T(e.data);if(!1===t)return;o.handleMessage(t,this)}catch(t){this.emit("ws.error",{type:exports.WebSocketErrorType.Unknown,error:t,target:e})}},o.onEvtErrListener=e=>{i.emit("ws.error",{type:exports.WebSocketErrorType.Error,target:e}),o.checkReadyState(this)},o.onEvtCLEListener=e=>{o.checkReadyState(this);const t=Number(e.code);if(1e3===t)return;const r=_(t);i.emit("ws.error",{target:e,type:exports.WebSocketErrorType.Close,closeError:r})},o.webSocket.addEventListener("open",o.onEvtOpnListener),o.webSocket.addEventListener("message",o.onEvtMsgListener),o.webSocket.addEventListener("error",o.onEvtErrListener),o.webSocket.addEventListener("close",o.onEvtCLEListener),await new Promise(((e,t)=>{const r=()=>{e(!0),o.connecting=!1,this.off("ws.error",i)},i=e=>{t(e.error?e.error:new Error("WebSocket connection failed!")),o.connecting=!1,this.off("ws.afterConnect",r)};this.once("ws.afterConnect",r),this.once("ws.error",i)}))}async revoke(){return!0}};return t.__debug__&&(Object.assign(i,{__controller__:o}),Object.assign(window,{$live:i})),i}exports.BrowserRTC=k,exports.BrowserRTC4Chime=w,exports.CoreRTC=u,exports.VRWebViewRTC=I,exports.createLive=V,exports.createLiveReact=function(e){const t=s.default.createContext(null),o=V(e);function r(){const e=s.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e}return{live:o,LiveProvider:function(e){return s.default.createElement(t.Provider,{value:e.live||o},e.children)},unsafe__useLiveInstance:function(){return r()},unsafe__useRTCInstance:function(){return r().$RTC},useCurrentWebSocketUrl:function(){const e=r(),[t,o]=s.default.useState(void 0);return s.default.useEffect((()=>{const t=()=>o(e.url);return e.on("ws.beforeConnect",t),()=>e.off("ws.beforeConnect",t)}),[e]),t},useConnect:function(){const e=r();return async t=>await e.connect(t)},useKeyframe:function(e){const t=r(),[o,i]=s.default.useState(t.getFramesByKey(e));return s.default.useEffect((()=>{const o=e,r=e=>i(e);return t.keyframes.on(o,r),()=>t.keyframes.off(o,r)}),[t]),[o,s.default.useCallback((o=>t.sendKeyframe(e,o)),[t])]},useKeyframeUpdateCallback:function(e,t,o=[]){const i=r(),n=[i,e,...o],a=()=>i.keyframes.off(e,t);return s.default.useEffect((()=>(i.keyframes.on(e,t),a)),n),a},useLiveAction:function(){const e=r(),t=s.default.useCallback((t=>e.toggleMicro(t)),[e]),o=s.default.useCallback(((t,o,r=0)=>e.broadcast(t,o,r)),[e]),i=s.default.useCallback((()=>e.exit()),[e]),n=s.default.useCallback((t=>e.kick(t)),[e]),a=s.default.useCallback(((t,o)=>e.forbidMicro(t,o)),[e]),c=s.default.useCallback((t=>e.getFramesByKey(t)),[e]);return{broadcast:o,exit:i,kick:n,toggleMicro:t,forbidMicro:a,sendKeyframe:s.default.useCallback(((t,o)=>e.sendKeyframe(t,o)),[e]),getFramesByKey:c,setSelfInfo:s.default.useCallback((t=>e.setSelfInfo(t)),[e]),updateStatus:s.default.useCallback(((t,o,r,i)=>e.updateStatus(t,o,r,i)),[e])}},useLiveEventCallback:function(e,t,o=[]){const i=r(),n=()=>i.off(e,t),a=[i,e,...o];return s.default.useEffect((()=>(i.on(e,t),n)),a),n},useReadyState:function(){const e=r(),[t,o]=s.default.useState(e.readyState);return s.default.useEffect((()=>{const t=e=>o(e);return e.on("ws.readyStateUpdate",t),()=>e.off("ws.readyStateUpdate",t)}),[e]),t},useRTCAction:function(){const e=r(),t=s.default.useCallback((t=>e.$RTC.join(t)),[e]);return{join:t,quit:s.default.useCallback((()=>e.$RTC.quit()),[e]),shock:s.default.useCallback((()=>{var t,o;return null===(o=(t=e.$RTC).shock)||void 0===o?void 0:o.call(t)}),[e]),toggleMicro:s.default.useCallback((t=>e.$RTC.toggleMicro(t)),[e]),detectMicro:s.default.useCallback((()=>e.$RTC.detectMicro()),[e])}},useRTCEventCallback:function(e,t,o=[]){const i=r(),n=()=>i.$RTC.off(e,t),a=[i,e,...o];return s.default.useEffect((()=>(i.$RTC.on(e,t),n)),a),n},useSelfInfo:function(){const e=r(),[t,o]=s.default.useState(e.selfInfo||{}),i=e=>o(e);return s.default.useEffect((()=>(e.on("selfInfoUpdate",i),()=>e.off("selfInfoUpdate",i))),[e]),[t,s.default.useCallback((async t=>await e.setSelfInfo(t)),[e])]},useSnapshot:function(){const e=r(),[t,o]=s.default.useState(e.snapshot);return s.default.useEffect((()=>{const t=e=>o(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=r(),[t,o]=s.default.useState(e.userList),i=e=>o(e);return s.default.useEffect((()=>(e.on("userListUpdate",i),()=>e.off("userListUpdate",i))),[e]),t},useWebSocketEventCallback:function(e,t,o=[]){const i=r(),n=()=>i.off(e,t),a=[i,e,...o];return s.default.useEffect((()=>(i.on(e,t),n)),a),n}}},exports.parseLiveMsg=T,exports.parseWSClsErr=_;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@realsee/jsbridge-x"),t=require("amazon-chime-sdk-js"),o=require("trtc-js-sdk"),r=require("react");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=i(e),n=i(o),a=i(r);const c=Symbol("$$REALSEE_LIVE_EVENT$$");function u(e){return e[c]||(e[c]={}),e[c]}class d{hasListener(e){const t=u(this);return t&&t[e]&&t[e].length>0}on(e,t,o){const r=u(this);return r[e]||(r[e]=[]),r[e].push([t,o||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((o=this)[c]||delete o[c]);var o;const r=u(this);if(r[e]||(r[e]=[]),void 0===t)return void(r[e].length=0);let i=0;for(;i<r[e].length&&r[e][i][0]!==t;i++);i<r[e].length&&r[e].splice(i,1)}emit(e,...t){let o=!1;const r=u(this)[e]||[];for(let i of r.slice()){const[r,s=!1]=i,n=r(...t);s&&this.off(e,r),!1===n&&(o=!0)}return o}}class l extends d{}var h,p,m,g,f,v,S,C,E,y,b,w;function k(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function T(){return(k()+k()+"-"+k()+"-4"+k().substr(0,3)+"-"+k()+"-"+k()+k()+k()).toLowerCase()}exports.RTCType=void 0,(h=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",h.RealseeVRWebViewRTC="RealseeVRWebViewRTC",h.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(p=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",p.RealseeXChimeRTC="chime";class I extends l{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=async e=>{var t;this.emit("joinWillStart");const o=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=n.default.createClient({mode:"rtc",...o}),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let r=await new Promise((t=>{var o;null===(o=this._trtc.client)||void 0===o||o.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=r,!!r&&(this._trtc.stream=n.default.createStream({userId:o.userId,audio:!0,video:!1}),r=await new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),r=await 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=r,this.joined&&this.emit("joined"),r)},this._handleStreamAdded=e=>{var t;const o=e.stream;console.log("远端流增加: "+o.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(o)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const o=`rs-rtc-remote_stream-${t.getId()}`,r=document.createElement("div");r.id=o,this.$dom.appendChild(r),t.play(o)},this._getVoiceSign=e.getVoiceSign,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${T()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((async e=>{var t,o;this.joined=!1,this._trtc.stream&&(await(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===(o=this._trtc.client)||void 0===o||o.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,o,r,i;return Promise.resolve((e?null===(o=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===o?void 0:o.unmuteAudio():null===(i=null===(r=this._trtc)||void 0===r?void 0:r.stream)||void 0===i?void 0:i.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,o,r;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===(o=this._trtc.client)||void 0===o||o.on("audio-volume",(e=>this.emit("userVolumes",[{userId:e.userId,audioVolume:e.audioVolume}]))),null===(r=this._trtc.client)||void 0===r||r.on("error",(e=>this.emit("error",e)))}}class _ extends l{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-${T()}`,this.$dom.id=`rs-rtc-${T()}`,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,o,r,i,s,n;const a=(null===(r=null===(o=null===(e=this.meetingSession)||void 0===e?void 0:e.configuration)||void 0===o?void 0:o.credentials)||void 0===r?void 0:r.attendeeId)||"";if(a){const e=new Map,o=()=>{const t=[];return e.forEach(((e,o)=>{t.push({userId:e.userId,volume:e.muted||0===e.signalStrength||!Boolean(e.volume)?0:e.volume})})),t};null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeSubscribeToAttendeeIdPresence(((r,i,s)=>{var n;if(!i)return e.delete(r),void this.emit("userVolumes",o());null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToVolumeIndicator(r,((r,i,n,a)=>{new t.DefaultModality(r).base()===r&&(e.set(r,{userId:s||r,volume:i,muted:n,signalStrength:a}),this.emit("userVolumes",o()))}))})),null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToVolumeIndicator(a,((e,o,r,i)=>{new t.DefaultModality(e).base()===e&&null!==i&&1!==i&&this.emit("weakNetwork")})),null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=e.getVoiceSign,this._initDom(),this.logger=new t.ConsoleLogger("WebRTCLogger",e.logLevel||t.LogLevel.OFF),this.deviceController=new t.DefaultDeviceController(this.logger),this.initObservers()}async join(e){return new Promise((async(o,r)=>{var i;this.emit("joinWillStart");try{const{sdkAppId:r,userId:s,roomId:n,userSig:a}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=s;const{attendence:c,vendor_wrapper:u}=JSON.parse(decodeURIComponent(a)),d=new t.MeetingSessionConfiguration({Meeting:u},{Attendee:{ExternalUserId:c.external_user_id,AttendeeId:c.attendee_id,JoinToken:c.join_token}});this.meetingSession=new t.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 l={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),o(!0)},audioVideoDidStop:()=>{this.joined=!1,o(!1)}};this.meetingSession.audioVideo.addObserver(l);const h=await this.deviceController.listAudioInputDevices(!0),p=h.find((e=>"default"===e.deviceId)),m=h.find((e=>""!==e.deviceId));this.audioInput=p||m,await this.meetingSession.audioVideo.chooseVideoInputDevice(null),await this.meetingSession.audioVideo.chooseAudioInputDevice((null===(i=this.audioInput)||void 0===i?void 0:i.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),o(!1)}}))}quit(){return new Promise(((e,o)=>{var r,i;this.joined=!1;const s={audioVideoDidStop:o=>{const r=o.statusCode();r===t.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${r}`),e(!0))}};null===(r=this.meetingSession)||void 0===r||r.audioVideo.addObserver(s),null===(i=this.meetingSession)||void 0===i||i.audioVideo.stop()}))}async detectMicro(){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)}}))}async toggleMicro(e){var t,o,r;e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(o=this.meetingSession)||void 0===o||o.audioVideo.realtimeMuteLocalAudio();const i=null===(r=this.meetingSession)||void 0===r?void 0:r.audioVideo.realtimeIsLocalAudioMuted();return void 0!==i&&e!==i}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 R extends l{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},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}async join(e){this.emit("joinWillStart");const{sdkAppId:t,userId:o,userSig:r}=await this.options.getVoiceSign(e);this.type=e.type;const[i,s]=await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${o}&roomID=${Number(e.voiceId)}&userSig=${r}`);return i?i.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",i),this.joined=!1):(this.emit("error",s||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}async quit(){const[e,t]=await this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}async detectMicro(){const[e,t]=await this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}async toggleMicro(e){const[t,o]=await this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",o||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}shock(){this.jsBridge.shock(1)}}function x(e){try{const t=JSON.parse(e),o={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||{}},r=Object.keys(o).filter((e=>void 0===o[e]));return r.length>0&&console.warn(`推送数据格式异常:${r.join(" ")} 值不存在!`),o}catch(e){return!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}exports.Command=void 0,(g=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",g.RoomInfo="ROOM_INFO",g.RTCInfo="RTC_INFO",g.UserList="USER_LIST",g.BuiltinMsg="BUILTIN_MSG",g.CustomEvent="CUSTOM_EVENT",g.KeyframeSync="KEYFRAME_SYNC",g.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(f=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",f.RoomChange="room_change",exports.BuiltinActionType=void 0,(v=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",v.UserMicroStatusSync="sync_micro_status",v.UserPermission="change_permission",v.UserStatus="change_status",v.UserInfo="change_info",v.RoomClose="close",exports.MicroStatus=void 0,(S=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",S.CLOSE="CLOSE",exports.UserStatus=void 0,(C=exports.UserStatus||(exports.UserStatus={}))[C.Normal=0]="Normal",C[C.Removed=1]="Removed",C[C.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,(b=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",b.Close="Close",b.MicroAuth="MicroAuth",b.DuplicateConnect="DuplicateConnect",b.IllegalURL="IllegalURL",b.Unknown="Unknown",b.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(w=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",w.Err_1002="CLOSE_PROTOCOL_ERROR",w.Err_1003="CLOSE_UNSUPPORTED",w.Err_1006="CLOSE_ABNORMAL",w.Err_1007="Unsupported Data",w.Err_1008="Policy Violation",w.Err_1009="CLOSE_TOO_LARGE",w.Err_unknown="unknown";const O=globalThis.navigator.userAgent,M=/android/gi.test(O),U=/iPhone|iPad\s+OS/gi.test(O),V=/MicroMessenger/gi.test(O)&&/miniProgram/gi.test(O),B=/realsee/gi.test(O);function N(e){return"[object Object]"===Object.prototype.toString.call(e)}function j(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function A(e,t){return!!j(e,t)||(N(e)&&N(t)?function(e,t){const o=Object.getOwnPropertyNames(e),r=Object.getOwnPropertyNames(t);if(o.length!==r.length)return!1;for(let r=0,i=o.length;r<i;r++){const i=o[r];if(!j(e[i],t[i]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let o=0,r=e.length;o<r;o++)if(!j(e[o],t[o]))return!1;return!0}(e,t))}function W(e,t){return!!j(e,t)||(N(e)&&N(t)?function(e,t){const o=Object.getOwnPropertyNames(e),r=Object.getOwnPropertyNames(t);if(o.length!==r.length)return!1;for(let r=0,i=o.length;r<i;r++){const i=o[r];if(!W(e[i],t[i]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let o=0,r=e.length;o<r;o++)if(!W(e[o],t[o]))return!1;return!0}(e,t))}function $(e,t,o){return o.deep?W(e,t):A(e,t)}class P{constructor(e){this.readyState=exports.WebSocketState.NOTINITIALIZED,this.canSync=!0,this.connecting=!1,this.keyframes={},this.checkReadyState=e=>{do{if(!this.webSocket){this.readyState!==exports.WebSocketState.NOTINITIALIZED&&(this.readyState=exports.WebSocketState.NOTINITIALIZED,e.emit("ws.readyStateUpdate",this.readyState));break}const t=this.webSocket.readyState;t!==this.readyState&&(this.readyState=t,e.emit("ws.readyStateUpdate",this.readyState))}while(0);return this.readyState},this.dispose=()=>{this.disposeWebSocket(),this.connecting=!1,this.healthCheckId&&(clearInterval(this.healthCheckId),this.healthCheckId=void 0)},this.disposeWebSocket=()=>{this.webSocket&&(this.onEvtOpnListener&&(this.webSocket.removeEventListener("open",this.onEvtOpnListener),this.onEvtOpnListener=void 0),this.onEvtMsgListener&&(this.webSocket.removeEventListener("message",this.onEvtMsgListener),this.onEvtMsgListener=void 0),this.onEvtErrListener&&(this.webSocket.removeEventListener("error",this.onEvtErrListener),this.onEvtErrListener=void 0),this.onEvtCLEListener&&(this.webSocket.removeEventListener("close",this.onEvtCLEListener),this.onEvtCLEListener=void 0),this.webSocket.close(),this.webSocket=void 0)},this.options=Object.assign({autoConnect:!0,healthCheck:3e3},e)}handleMessage(e,t){var o,r,i;const{command:s,data:n,frontRequestId:a,code:c,message:u}=e;if("SUCCESS"===c)switch(s){case exports.Command.SelfUserInfo:{const e=n;if($(this.selfUserInfo,e,{deep:!0}))return;this.selfUserInfo=e,t.emit("selfInfoUpdate",this.selfUserInfo,a);break}case exports.Command.RoomInfo:{const e=n;this.roomInfo=Object.assign({},e),t.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:i}=n;if(t.$RTC.joined)break;t.$RTC.join({voiceId:e,userId:(null===(o=this.selfUserInfo)||void 0===o?void 0:o.id)||"",roomId:null===(r=this.roomInfo)||void 0===r?void 0:r.info.room_code,type:i}),t.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:exports.MicroStatus.OPEN});break}case exports.Command.UserList:{const e=n;this.userList=e,t.emit("userListUpdate",this.userList,a);break}case exports.Command.CustomEvent:{const e=n;t.emit("broadcast",e,a);break}case exports.Command.KeyframeSync:{const e=n,o=Object.keys(e).reduce(((o,r)=>{if($(e[r],this.keyframes[r],{deep:!0}))return o;const i=[e[r],this.keyframes[r],a],s=r;return t.keyframes.emit(s,...i),this.keyframes[r]=e[r],o[r]=e[r],o}),{});t.emit("keyframes",o,a);break}case exports.Command.BuiltinMsg:{const e=n;t.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&t.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&t.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&t.toggleMicro(e.data.status===exports.MicroStatus.OPEN),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(null===(i=this.options.rtc)||void 0===i||i.quit(),this.disposeWebSocket());break}case exports.Command.UserKickOut:t.emit("kickOut");break;default:console.warn("unknown command: ",s)}else t.emit("error",e)}sendMessage(e){return this.webSocket?e?void this.webSocket.send(JSON.stringify(e)):console.warn("WebSocket messages is empty!"):console.warn("WebSocket has not yet been initialized!")}}const D=e=>Promise.reject("unimplemented method GetVoiceSign");function K(e){const o=new P(e),r=(e,t={},o)=>((o=o?Array.isArray(o)?o:[o]:[])&&(t.to_user_ids=o),{command:e,front_request_id:T(),data:t});const i=new class extends d{constructor(){var r,i,n;super(),this.keyframes=new d;const a=(null!==(r=e.jsBridge)&&void 0!==r?r:e.useBuiltInJsBridge)?new s.default:void 0;if(o.options.jsBridge=a,!e.rtc){if(e.rtcType){if(!e.getVoiceSign)throw new Error("GetVoiceSign method must be passed when using built-in RTC instances");const r=null!==(i=e.getVoiceSign)&&void 0!==i?i:D;switch(e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:if(!a)throw new Error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");o.options.rtc=new R({jsBridge:a,getVoiceSign:r});break;case exports.RTCType.RealseeBrowserChimeRTC:o.options.rtc=new _({getVoiceSign:r,logLevel:e.__debug__?t.LogLevel.DEBUG:t.LogLevel.ERROR});break;case exports.RTCType.RealseeBrowserRTC:o.options.rtc=new I({getVoiceSign:r});break;default:throw new Error("unknown built-in RTC type")}}if(e.useBuiltInRTC){if(!e.getVoiceSign)throw new Error("GetVoiceSign method must be passed when using built-in RTC instances");const t=null!==(n=e.getVoiceSign)&&void 0!==n?n:D;if(!a)throw new Error("jsBridge instance must be passed when using built-in RTC instances");o.options.rtc=B&&(M||U)||V?new R({jsBridge:a,getVoiceSign:t}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new _({getVoiceSign:t}):new I({getVoiceSign:t})}}o.options.rtc||console.warn("unused rtc"),o.options.url&&o.options.getTicket&&this.connect();const c=(e=>{if(!e)return 0;if(!0===e)return 3e3;const t=Number(e);return t>0?t:3e3})(o.options.healthCheck);c&&(o.healthCheckId=setInterval((()=>o.checkReadyState(this)),c))}get options(){return Object.freeze(Object.assign({},o.options))}get readyState(){return o.checkReadyState(this),o.readyState}get url(){var e;return(null===(e=o.webSocket)||void 0===e?void 0:e.url)||""}get selfInfo(){return o.selfUserInfo}get userList(){return o.userList||[]}get snapshot(){return o.keyframes||{}}get $RTC(){return o.options.rtc}get jsBridge(){return o.options.jsBridge}async setSelfInfo(e){if(this.readyState!==exports.WebSocketState.OPEN)return new Error("The connection is not open and ready to communicate.");try{return await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)}catch(e){return e}}getFramesByKey(e){return o.keyframes[e]}sendKeyframe(e,t){if(this.readyState!==exports.WebSocketState.OPEN)return new Error("The connection is not open and ready to communicate.");o.keyframes[e]=t;const i=r(exports.Command.KeyframeSync,this.snapshot);return o.sendMessage(i),!0}broadcast(e,t,i){return this.readyState!==exports.WebSocketState.OPEN?new Error("The connection is not open and ready to communicate."):new Promise(((s,n)=>{const a=r(exports.Command.CustomEvent,e,t),c=a.front_request_id;o.sendMessage(a);const u=i?setTimeout((()=>{n(new Error("RESPONSE TIMEOUT")),this.off("broadcast",d)}),i):void 0,d=(e,t)=>{t===c&&(this.off("broadcast",d),s(e),u&&clearInterval(u))};this.on("broadcast",d)}))}async updateStatus(e,t,i,s){if(this.readyState!==exports.WebSocketState.OPEN)return!1;const n=Object.assign({event_type:e,action:t},{data:i}),a=r(exports.Command.BuiltinMsg,n,s);return o.sendMessage(a),!0}async toggleMicro(e){var t,o;return!!(null===(o=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===o?void 0:o.control_own_micro)&&(await this.$RTC.toggleMicro(e),await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[]))}async forbidMicro(e,t){var r,i;return!(o.options.canForbidUserMicro&&!o.options.canForbidUserMicro(t))&&(!!(null===(i=null===(r=this.selfInfo)||void 0===r?void 0:r.permission)||void 0===i?void 0:i.control_other_micro)&&await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t))}async forbidSync(e,t){var r,i;return!(o.options.canForbidUserSync&&!o.options.canForbidUserSync(t))&&(!!(null===(i=null===(r=this.selfInfo)||void 0===r?void 0:r.permission)||void 0===i?void 0:i.control_other_sync)&&await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t))}async kick(e){var t,r;return!(o.options.canForbidUserKick&&!o.options.canForbidUserKick(e))&&(!!(null===(r=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===r?void 0:r.change_other_status)&&await this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e))}async exit(){return await this.$RTC.quit(),await this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})}async connect(e={}){if(!await this.$RTC.detectMicro()){const e=new Error("系统监测麦克风未授权~");return this.emit("ws.error",{type:exports.WebSocketErrorType.MicroAuth,error:e}),e}if(o.connecting){const e=new Error("WebSocket 正在连接中,请勿重复连接 ...");return this.emit("ws.error",{type:exports.WebSocketErrorType.DuplicateConnect,error:e}),e}const{force:t}=e;if(!t&&(this.readyState===exports.WebSocketState.CONNECTING||this.readyState===exports.WebSocketState.OPEN))return!0;if(e.url&&(o.options.url=e.url),e.getTicket&&(o.options.getTicket=e.getTicket),!o.options.url||!o.options.url.startsWith("ws")){const e=new Error(`WebSocket URL 未配置或格式不合法:"${o.options.url}"`);return this.emit("ws.error",{type:exports.WebSocketErrorType.IllegalURL,error:e}),e}if(!o.options.getTicket){const e=new Error("getTicket() 未配置!");return this.emit("ws.error",{type:exports.WebSocketErrorType.IllegalArgs,error:e}),e}o.connecting=!0,o.disposeWebSocket(),this.emit("ws.beforeConnect");const r=t||e.url||!this.url?function(e,t){const o=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,r,i)=>`${e}${0!==i||o?"&":"?"}${r}=${t[r]}`),"")}(o.options.url,{ticket:await o.options.getTicket(),force:Number(!!t)}):this.url;return o.webSocket=new WebSocket(r),o.onEvtOpnListener=()=>{o.checkReadyState(this),this.emit("ws.afterConnect")},o.onEvtMsgListener=e=>{o.checkReadyState(this);try{const t=x(e.data);if(!1===t)return;o.handleMessage(t,this)}catch(t){this.emit("ws.error",{type:exports.WebSocketErrorType.Unknown,error:t,target:e})}},o.onEvtErrListener=e=>{i.emit("ws.error",{type:exports.WebSocketErrorType.Error,target:e}),o.checkReadyState(this)},o.onEvtCLEListener=e=>{o.checkReadyState(this);const t=Number(e.code);if(1e3===t)return;const r=L(t);i.emit("ws.error",{target:e,type:exports.WebSocketErrorType.Close,closeError:r})},o.webSocket.addEventListener("open",o.onEvtOpnListener),o.webSocket.addEventListener("message",o.onEvtMsgListener),o.webSocket.addEventListener("error",o.onEvtErrListener),o.webSocket.addEventListener("close",o.onEvtCLEListener),await new Promise(((e,t)=>{const r=()=>{e(!0),o.connecting=!1,this.off("ws.error",i)},i=e=>{t(e.error?e.error:new Error("WebSocket connection failed!")),o.connecting=!1,this.off("ws.afterConnect",r)};this.once("ws.afterConnect",r),this.once("ws.error",i)}))}async revoke(){return!0}};return e.__debug__&&(Object.assign(i,{__controller__:o}),Object.assign(window,{$live:i})),i}exports.BrowserRTC=I,exports.BrowserRTC4Chime=_,exports.CoreRTC=l,exports.VRWebViewRTC=R,exports.createLive=K,exports.createLiveReact=function(e){const t=a.default.createContext(null),o=K(e),r=o.jsBridge;function i(){const e=a.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e}return{live:o,jsBridge:r,LiveProvider:function(e){return a.default.createElement(t.Provider,{value:e.live||o},e.children)},unsafe__useLiveInstance:function(){return i()},unsafe__useRTCInstance:function(){return i().$RTC},useCurrentWebSocketUrl:function(){const e=i(),[t,o]=a.default.useState(void 0);return a.default.useEffect((()=>{const t=()=>o(e.url);return e.on("ws.beforeConnect",t),()=>e.off("ws.beforeConnect",t)}),[e]),t},useConnect:function(){const e=i();return async t=>await e.connect(t)},useKeyframe:function(e){const t=i(),[o,r]=a.default.useState(t.getFramesByKey(e));return a.default.useEffect((()=>{const o=e,i=e=>r(e);return t.keyframes.on(o,i),()=>t.keyframes.off(o,i)}),[t]),[o,a.default.useCallback((o=>t.sendKeyframe(e,o)),[t])]},useKeyframeUpdateCallback:function(e,t,o=[]){const r=i(),s=[r,e,...o],n=()=>r.keyframes.off(e,t);return a.default.useEffect((()=>(r.keyframes.on(e,t),n)),s),n},useLiveAction:function(){const e=i(),t=a.default.useCallback((t=>e.toggleMicro(t)),[e]),o=a.default.useCallback(((t,o,r=0)=>e.broadcast(t,o,r)),[e]),r=a.default.useCallback((()=>e.exit()),[e]),s=a.default.useCallback((t=>e.kick(t)),[e]),n=a.default.useCallback(((t,o)=>e.forbidMicro(t,o)),[e]),c=a.default.useCallback((t=>e.getFramesByKey(t)),[e]);return{broadcast:o,exit:r,kick:s,toggleMicro:t,forbidMicro:n,sendKeyframe:a.default.useCallback(((t,o)=>e.sendKeyframe(t,o)),[e]),getFramesByKey:c,setSelfInfo:a.default.useCallback((t=>e.setSelfInfo(t)),[e]),updateStatus:a.default.useCallback(((t,o,r,i)=>e.updateStatus(t,o,r,i)),[e])}},useLiveEventCallback:function(e,t,o=[]){const r=i(),s=()=>r.off(e,t),n=[r,e,...o];return a.default.useEffect((()=>(r.on(e,t),s)),n),s},useReadyState:function(){const e=i(),[t,o]=a.default.useState(e.readyState);return a.default.useEffect((()=>{const t=e=>o(e);return e.on("ws.readyStateUpdate",t),()=>e.off("ws.readyStateUpdate",t)}),[e]),t},useRTCAction:function(){const e=i(),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,o;return null===(o=(t=e.$RTC).shock)||void 0===o?void 0:o.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,o=[]){const r=i(),s=()=>r.$RTC.off(e,t),n=[r,e,...o];return a.default.useEffect((()=>(r.$RTC.on(e,t),s)),n),s},useSelfInfo:function(){const e=i(),[t,o]=a.default.useState(e.selfInfo||{}),r=e=>o(e);return a.default.useEffect((()=>(e.on("selfInfoUpdate",r),()=>e.off("selfInfoUpdate",r))),[e]),[t,a.default.useCallback((async t=>await e.setSelfInfo(t)),[e])]},useSnapshot:function(){const e=i(),[t,o]=a.default.useState(e.snapshot);return a.default.useEffect((()=>{const t=e=>o(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=i(),[t,o]=a.default.useState(e.userList),r=e=>o(e);return a.default.useEffect((()=>(e.on("userListUpdate",r),()=>e.off("userListUpdate",r))),[e]),t},useWebSocketEventCallback:function(e,t,o=[]){const r=i(),s=()=>r.off(e,t),n=[r,e,...o];return a.default.useEffect((()=>(r.on(e,t),s)),n),s}}},exports.parseLiveMsg=x,exports.parseWSClsErr=L;
|
|
2
2
|
//# sourceMappingURL=realsee-live.cjs.production.js.map
|