agora-rdc-core
Version:
2 lines (1 loc) • 26.2 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRemoteDesktopControlCore={})}(this,(function(e){"use strict";var t;e.LogLevel=void 0,(t=e.LogLevel||(e.LogLevel={}))[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARNING=2]="WARNING",t[t.ERROR=3]="ERROR",t[t.FATAL=4]="FATAL";const o=new class{constructor(){this.logLevel=e.LogLevel.DEBUG}debug(...t){const o=[e.LogLevel.DEBUG].concat(t);this.log.apply(this,o)}info(...t){const o=[e.LogLevel.INFO].concat(t);this.log.apply(this,o)}warning(...t){const o=[e.LogLevel.WARNING].concat(t);this.log.apply(this,o)}error(...t){const o=[e.LogLevel.ERROR].concat(t);this.log.apply(this,o)}setLogLevel(e){this.logLevel=Math.min(Math.max(0,e),4)}log(...t){const o=Math.max(0,Math.min(4,t[0]));if(o<this.logLevel)return;const s=`${(new Date).toISOString()} %cagora-rdc [${e.LogLevel[o]}]:`;let n=[];switch(o){case e.LogLevel.DEBUG:n=[s,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,n);break;case e.LogLevel.INFO:n=[s,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,n);break;case e.LogLevel.WARNING:n=[s,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,n);break;case e.LogLevel.ERROR:n=[s,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,n)}}};var s=require("../build/Release/agora-rc-extension").RemoteControlEngine;class n{constructor(){this.addon=new s}static create(){return this.instance||(this.instance=new n),this.instance}initialize(t,o){const{logPath:s,mouseEventsThreshold:n,keyboardEventsThreshold:r,logLevel:i=e.LogLevel.DEBUG}=o;let a={log_path:s,mouse_buff_ms:n,kb_buff_ms:r};i===e.LogLevel.DEBUG&&(a.log_level=0),i===e.LogLevel.INFO&&(a.log_level=2),i===e.LogLevel.WARNING&&(a.log_level=3),i===e.LogLevel.ERROR&&(a.log_level=4),i===e.LogLevel.FATAL&&(a.log_level=6),this.addon.initialize(t,JSON.stringify(a))}join(e,t){this.addon.login(e,t)}leave(){this.addon.logout()}emit(e,t){const o=t.userId;switch(e){case"keyboard-event":const{keyCode:e,isCompoundAlt:s,isCompoundCtrl:n,isCompoundShift:r}=t;this.addon.keyEvent(o,e,n?1:0,s?1:0,r?1:0);break;case"mouse-event":const{type:i,x:a,y:d,delta:l}=t;this.addon.mouseEvent(o,i,a,d,null!=l?l:0)}}onEvent(e){this.addon.handleEvent(e)}sendMessage(e,t){this.addon.sendCustomMessage(e,JSON.stringify(t))}requestControl(e){this.addon.requestControl(e)}authorizeControl(e,t){this.addon.answerRequestControl(e,t)}quitControl(e){this.addon.quitControl(e)}authorizeQuitControl(e,t){this.addon.answerQuitControl(e,t)}updateControlRect(e,t){this.addon.updateView(e,t)}focus(e){this.addon.holdControl(e)}pasteRemotely(e=!1,t){e||t||this.addon.remotePasteOp(e),e&&t&&this.addon.remotePasteOp(e,t)}getClipboardContentType(){return this.addon.getClipboardType()}requestRemoteEndInfo(e){return this.addon.requestRemoteInfo(e)}joinChannel(e){return this.addon.joinChannel(e)}leaveChannel(){return this.addon.leaveChannel()}dispose(){this.addon.release()}}const r={Home:63273,End:63275,Help:63302,Delete:63272,Backspace:127,PageUp:63276,PageDown:63277,Enter:13,ShiftLeft:160,ShiftRight:160,CapsLock:20,Tab:9,F1:63236,F2:63237,F3:63238,F4:63239,F5:63240,F6:63241,F7:63242,F8:63243,F9:63244,F10:63245,F11:63246,F12:63247,ArrowLeft:63234,ArrowUp:63232,ArrowRight:63235,ArrowDown:63233,Backquote:96,Minus:45,Equal:61,BracketLeft:91,BracketRight:93,Backslash:92,Semicolon:59,Quote:39,Comma:44,Period:46,Slash:47},i={0:"default",1:"text",2:"wait",3:"crosshair",4:"default",5:"nwse-resize",6:"nesw-resize",7:"ew-resize",8:"ns-resize",9:"all-scroll",10:"not-allowed",11:"pointer",12:"progress",13:"help"};var a,d,l,h,c,u,E,C,p;e.RDCAddonEvents=void 0,(a=e.RDCAddonEvents||(e.RDCAddonEvents={})).LOGIN="login",a.STATE="state",a.SEND_RESULT="send_result",a.MSG="msg",a.CTRL_REQ="ctrl_req",a.QUIT_REQ="quit_req",a.GETTING_FOCUS="hold_control",a.MOUSE_STATUS="mouse_status",a.UPLOAD_RESULT="upload_result",a.PASTED="pasted",a.REMOTE_PASTED="remote_pasted",a.OBSERVATION="bc_data",a.REMOTE_END_INFO="remote_info",e.RDCClipboardContentType=void 0,(d=e.RDCClipboardContentType||(e.RDCClipboardContentType={}))[d.UNKNOWN=0]="UNKNOWN",d[d.TEXT=2]="TEXT",d[d.FILE=1]="FILE",e.RDCMouseEventType=void 0,(l=e.RDCMouseEventType||(e.RDCMouseEventType={}))[l.LEFT_CLICK=1]="LEFT_CLICK",l[l.LEFT_DBL_CLICK=2]="LEFT_DBL_CLICK",l[l.RIGHT_CLICK=3]="RIGHT_CLICK",l[l.RIGHT_DBL_CLICK=4]="RIGHT_DBL_CLICK",l[l.MID_CLICK=5]="MID_CLICK",l[l.WHEEL=6]="WHEEL",l[l.MOVE=7]="MOVE",l[l.DRAG_BEGIN=8]="DRAG_BEGIN",l[l.DRAG_MOVE=9]="DRAG_MOVE",l[l.DRAG_END=10]="DRAG_END",e.RDCJoinErrorCode=void 0,(h=e.RDCJoinErrorCode||(e.RDCJoinErrorCode={}))[h.UNKNOWN_ERROR=1]="UNKNOWN_ERROR",h[h.SERVER_REJECTED=2]="SERVER_REJECTED",h[h.INVALID_LOGIN_ARGUMENT=3]="INVALID_LOGIN_ARGUMENT",h[h.INVALID_APP_ID=4]="INVALID_APP_ID",h[h.INVALID_TOKEN=5]="INVALID_TOKEN",h[h.TOKEN_EXPIRED=6]="TOKEN_EXPIRED",h[h.AUTHORIZE_FAIL=7]="AUTHORIZE_FAIL",h[h.DUPLICATED_LOGIN=8]="DUPLICATED_LOGIN",h[h.TIMEOUT=9]="TIMEOUT",h[h.LOGIN_TOO_OFTEN=10]="LOGIN_TOO_OFTEN",h[h.NOT_INITIALIZED=101]="NOT_INITIALIZED",e.RDCEngineState=void 0,(c=e.RDCEngineState||(e.RDCEngineState={}))[c.INITIALIZED=1]="INITIALIZED",c[c.LOGGED_IN=2]="LOGGED_IN",c[c.LOGGED_OUT=3]="LOGGED_OUT",c[c.CONNECTED=4]="CONNECTED",c[c.DISCONNECT=5]="DISCONNECT";class v{constructor(){this.events=new Map,this._defaultMaxListeners=10}get defaultMaxListeners(){return this._defaultMaxListeners}set defaultMaxListeners(e){if(Number.isInteger(e)||e<0){throw new RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative integer. Received ${e}.`)}this._defaultMaxListeners=e}addListener(e,t){return this.on(e,t)}emit(e,...t){const o=this.events.get(e);if(void 0===o){if("error"===e){const e=t[0];if(e instanceof Error)throw e;throw new Error("Unhandled error.")}return!1}return[...o].forEach((e=>{e.apply(this,t)})),!0}setMaxListeners(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`The value of "n" is out of range. It must be a non-negative integer. Received ${e}.`);return this.maxListeners=e,this}getMaxListeners(){return void 0===this.maxListeners?this.defaultMaxListeners:this.maxListeners}listenerCount(e){const t=this.events.get(e);return void 0===t?0:t.length}eventNames(){return Reflect.ownKeys(this.events)}listeners(e){const t=this.events.get(e);return void 0===t?[]:t}off(e,t){return this.removeListener(e,t)}on(e,t,o){!1===this.events.has(e)&&this.events.set(e,[]);const s=this.events.get(e);o?s.unshift(t):s.push(t),"newListener"!==e&&this.events.has("newListener")&&this.emit("newListener",e,t);const n=this.getMaxListeners(),r=s.length;if(n>0&&r>n&&!s.warned){s.warned=!0;const t=new Error(`Possible EventEmitter memory leak detected.\n ${this.listenerCount(e)} ${e.toString()} listeners.\n Use emitter.setMaxListeners() to increase limit`);t.name="MaxListenersExceededWarning",console.warn(t)}return this}removeAllListeners(e){const{events:t}=this;if(!t.has("removeListener"))return 0===arguments.length?this.events=new Map:t.has(e)&&t.delete(e),this;if(0===arguments.length)return Array.from(t.keys()).forEach((e=>{"removeListener"!==e&&this.removeAllListeners(e)})),this.removeAllListeners("removeListener"),this.events=new Map,this;const o=t.get(e);return void 0!==o&&o.forEach((t=>{this.removeListener(e,t)})),this}removeListener(e,t){const{events:o}=this;if(0===o.size)return this;const s=o.get(e);if(void 0===s)return this;const n=s.findIndex((e=>e===t||e.listener===t));return-1===n||(s.splice(n,1),0===s.length&&this.events.delete(e),o.has("removeListener")&&this.emit("removeListener",e,t)),this}once(e,t){return this.on(e,this.onceWrap(e,t)),this}onceWrap(e,t){const o=function(...e){this.context.removeListener(this.eventName,this.wrappedListener),this.listener.apply(this.context,e)},s={eventName:e,listener:t,wrappedListener:o,context:this},n=o.bind(s);return s.wrappedListener=n,n.listener=t,n}prependListener(e,t){return this.on(e,t,!0)}prependOnceListener(e,t){return this.prependListener(e,this.onceWrap(e,t)),this}rawListeners(e){const{events:t}=this;if(void 0===t)return[];const o=t.get(e);return void 0===o?[]:[...o]}}e.RDCRoleType=void 0,(u=e.RDCRoleType||(e.RDCRoleType={}))[u.HOST=1]="HOST",u[u.CONTROLLED=2]="CONTROLLED",e.RDCRemotelyPastingStatus=void 0,(E=e.RDCRemotelyPastingStatus||(e.RDCRemotelyPastingStatus={}))[E.STARTING=0]="STARTING",E[E.TRANSMITTED=1]="TRANSMITTED",E[E.SUCCEEDED=2]="SUCCEEDED",E[E.FAILED=3]="FAILED",e.RDCRemotelyPastingCodes=void 0,(C=e.RDCRemotelyPastingCodes||(e.RDCRemotelyPastingCodes={}))[C.SUCCEEDED=0]="SUCCEEDED",C[C.FAILURE=1]="FAILURE",C[C.TIMEOUT=3]="TIMEOUT",C[C.SIZE_OVERFLOW=4]="SIZE_OVERFLOW",C[C.CONCURRENCY_LIMIT_EXCEEDED=5]="CONCURRENCY_LIMIT_EXCEEDED",C[C.UNSUPPORTED_FILE_TYPE=99]="UNSUPPORTED_FILE_TYPE",C[C.NOT_INITIALIZED=101]="NOT_INITIALIZED",C[C.NOT_LOGGED_IN=102]="NOT_LOGGED_IN",e.RDCAndroidAction=void 0,(p=e.RDCAndroidAction||(e.RDCAndroidAction={}))[p.ACTION_BACK=64001]="ACTION_BACK",p[p.ACTION_HOME=64002]="ACTION_HOME",p[p.ACTION_RECENT=64003]="ACTION_RECENT",p[p.ACTION_NOTIFICATIONS=64004]="ACTION_NOTIFICATIONS",p[p.ACTION_QUICK_SETTINGS=64005]="ACTION_QUICK_SETTINGS",p[p.ACTION_POWER_DIALOG=64006]="ACTION_POWER_DIALOG",p[p.ACTION_TOGGLE_SPLIT_SCREEN=64007]="ACTION_TOGGLE_SPLIT_SCREEN",p[p.ACTION_LOCK_SCREEN=64008]="ACTION_LOCK_SCREEN",p[p.ACTION_SCREENSHOT=64009]="ACTION_SCREENSHOT";const R={bitrate:2e3,frameRate:10,height:1080,width:1920},g={1:"LEFT_CLICK",2:"LEFT_DBL_CLICK",3:"RIGHT_CLICK",4:"RIGHT_DBL_CLICK",5:"MID_CLICK",6:"WHEEL",7:"MOVE",8:"DRAG_BEGIN",9:"DRAG_MOVE",10:"DRAG_END"},T=["android"];function D(e){const t={...e};return Object.keys(t).forEach((e=>{void 0!==t[e]&&null!==t[e]||delete t[e]})),t}e.AbstractAgoraRemoteDesktopControl=class extends v{constructor(t){super(),this.state={},this.handleRequestControl=e=>{const{peer:t,answer:s,msg:n}=JSON.parse(e),r=Boolean(Number(n));return s&&r?(o.debug("Emit `rdc-request-control-authorized`: ",t),void this.emit("rdc-request-control-authorized",t)):s&&!r?(o.debug("Emit `rdc-request-control-unauthorized`: ",t),void this.emit("rdc-request-control-unauthorized",t)):(o.debug("Emit `rdc-request-control`: ",t),void this.emit("rdc-request-control",t))},this.handleGettingFocus=e=>{const{hold:t}=JSON.parse(e),s={...R,captureMouseCursor:!t};this.rtcAdapter.updateDisplayConfiguration(s),o.debug("update screen capture params: ",s)},this.handleRDCMessage=e=>{try{const t=JSON.parse(e),{from:s,event:n}=t;if(!s)return void o.warning("Unknown message from, dispose.");switch(n){case"retrieve-observation":this.rdcAdapter.sendMessage(s,{from:this.userId,event:"retrieved-observation",capturedBy:this.capturedBy});break;case"retrieved-observation":this.emit("retrieved-observation",{userId:s,capturedBy:t.capturedBy});break;case"captured-by":this.setState(s,{capturedBy:t.capturedBy});break;default:o.warning("Unknown message event, dispose.")}}catch(e){o.error(e)}},this.handleMouseStateChange=e=>{const{cursor:t,peer:s}=JSON.parse(e),{cursor:n,cursorUpdater:r,isFocused:a}=this.getState(s);if(a){if(!r)throw new Error(`cursor updater is no created correctly for: ${s}`);t!==n&&(this.setState(s,{cursor:n}),r(s,t),o.debug("update cursor: ",i[t]))}},this.handleMouseEvent=(e,t)=>s=>{s.preventDefault(),s.stopPropagation();const n={userId:e,type:t,x:s.offsetX,y:s.offsetY,delta:s instanceof WheelEvent?s.deltaY:void 0};this.rdcAdapter.emit("mouse-event",n),o.debug("RDCEngine emit `mouse-event`, ",n,g[t])},this.handleMouseDown=e=>t=>{this.getState(e).isFocused&&this.setState(e,{mousedownX:t.x,mousedownY:t.y})},this.handleMouseUp=t=>o=>{if(!this.getState(t).isFocused)return;this.setState(t,{mouseupX:o.x,mouseupY:o.y});const{isDragging:s,mousedownX:n,mousedownY:r,mouseupX:i,mouseupY:a}=this.getState(t);!s||n===i&&r===a||(this.handleMouseEvent(t,e.RDCMouseEventType.DRAG_END)(o),this.setState(t,{isDragging:!1}))},this.handleMouseMove=t=>o=>{if(!this.getState(t).isFocused)return;const{isDragging:s,mousedownX:n,mousedownY:r,mouseupX:i,mouseupY:a}=this.getState(t);!s&&"number"==typeof n&&"number"==typeof r&&void 0===i&&void 0===a&&(Math.abs(n-o.x)>0||Math.abs(r-o.y)>0)&&(this.handleMouseEvent(t,e.RDCMouseEventType.DRAG_BEGIN)(o),this.setState(t,{isDragging:!0})),this.handleMouseEvent(t,this.getState(t).isDragging?e.RDCMouseEventType.DRAG_MOVE:e.RDCMouseEventType.MOVE)(o)},this.handleMouseLeave=e=>t=>{if(!this.getState(e).isFocused)return;this.getState(e).isDragging&&this.handleMouseUp(e)(t);const{cursorUpdater:o}=this.getState(e);o&&o(e,-2),this.getState(e).isFocused&&(this.setState(e,{isFocused:!1}),this.rdcAdapter.focus(!1))},this.handleKeydownEvent=e=>t=>{t.preventDefault(),t.stopPropagation(),this.getState(e).isFocused&&(["Shift","Control","Alt","Meta"].includes(t.key)||(t.shiftKey||t.ctrlKey||t.altKey||t.metaKey)&&this.setState(e,{isCompoundAlt:t.altKey,isCompoundShift:t.shiftKey,isCompoundCtrl:t.ctrlKey,isCompoundMeta:t.metaKey}))},this.handleKeyupEvent=t=>s=>{if(s.preventDefault(),s.stopPropagation(),!this.getState(t).isFocused)return;const{isCompoundShift:n,isCompoundCtrl:r,isCompoundAlt:i,isCompoundMeta:a}=this.getState(t);if(n&&"Shift"===s.key)return o.debug("RDCEngine `keyboard-event`: `Shift` Compounded"),void this.setState(t,{isCompoundShift:!1});if(r&&"Control"===s.key)return o.debug("RDCEngine `keyboard-event`: `Control` Compounded"),void this.setState(t,{isCompoundCtrl:!1});if(i&&"Alt"===s.key)return o.debug("RDCEngine `keyboard-event`: `Alt` Compounded"),void this.setState(t,{isCompoundAlt:!1});if(a&&"Meta"===s.key)return o.debug("RDCEngine `keyboard-event`: `Meta` Compounded"),void this.setState(t,{isCompoundMeta:!1});s.ctrlKey&&"KeyV"===s.code&&(this.rdcAdapter.pasteRemotely(),this.rdcAdapter.getClipboardContentType()===e.RDCClipboardContentType.FILE&&this.handleRemotePasteEvent(e.RDCRemotelyPastingStatus.STARTING,e.RDCRemotelyPastingCodes.SUCCEEDED));const d={userId:t,keyCode:this.getKeyCode(s),isCompoundAlt:s.altKey,isCompoundShift:s.shiftKey,isCompoundCtrl:s.ctrlKey};o.debug("RDCEngine emit `keyboard-event`, ",d),this.rdcAdapter.emit("keyboard-event",d)},this.handleDrop=t=>t=>{var o;t.preventDefault(),t.stopPropagation();const{files:s}=null!==(o=t.dataTransfer)&&void 0!==o?o:{};if(s)for(const t of Array.from(s)){const o=t;this.rdcAdapter.pasteRemotely(!0,o.path),this.handleRemotePasteEvent(e.RDCRemotelyPastingStatus.STARTING,e.RDCRemotelyPastingCodes.SUCCEEDED)}},this.handleFullscreenChange=()=>{document.fullscreenElement?this.emit("rdc-fullscreen-change",!0):this.emit("rdc-fullscreen-change",!1)},this.getKeyCode=e=>r[e.code]?r[e.code]:e.keyCode>="A".charCodeAt(0)&&e.keyCode<="Z".charCodeAt(0)?e.key.charCodeAt(0):e.keyCode,this.handleObservationPositionChange=e=>t=>{const s=t[t.length-1];o.debug("position change",s);const n=document.querySelector(`#cursor-${e}`);if(!n||!s)return;n.style.display="block";const r=n.querySelector("#cursor");r&&(r.style.top=s.y-8+"px",r.style.left=s.x-8+"px")},this.options=t,this.rdcAdapter=n.create()}getRole(){return this.options.role}async getDisplays(){if(this.options.role!==e.RDCRoleType.CONTROLLED)throw new Error("Only `RDCRoleType.CONTROLLED` can call `getDisplays`");return await this.rtcAdapter.getDisplays()}async join(...e){const[t,s,n,r,i]=e;this.userId=t,this.streamId=r,this.channel=n,o.debug(`Join RDC engine with userId: ${t}`),this.rdcAdapter.join(t,s),o.debug(`Join RTC engine with channel: ${n}, streamId: ${r}`),await this.rtcAdapter.join(r,n,null!=i?i:s)}requestControl(t){if(this.options.role!==e.RDCRoleType.HOST)throw new Error("Only `RDCRoleType.HOST` can call `requestControl`");o.debug(`Request control for userId: ${t}`),this.rdcAdapter.requestControl(t)}authorizeControl(t,s,n,r){const{role:i}=this.options;if(i!==e.RDCRoleType.CONTROLLED)throw new Error("Only `RDCRoleType.CONTROLLED` can call `authorizeControl`");o.debug("Start screen capture by displayId:",s.id,"configuration",n),this.rtcAdapter.publish(s,n?D({enableLoopback:!0,...n}):n,r),this.rdcAdapter.updateControlRect(s.width,s.height),this.rdcAdapter.authorizeControl(t,!0),this.rdcAdapter.sendMessage(t,{from:this.userId,event:"captured-by",capturedBy:this.capturedBy})}unauthorizeControl(t){if(this.options.role!==e.RDCRoleType.CONTROLLED)throw new Error("Only `RDCRoleType.CONTROLLED` can call `unauthorizeControl`");this.rdcAdapter.authorizeControl(t,!1)}async takeControl(t,s,n){var r;if(this.options.role!==e.RDCRoleType.HOST)throw new Error("Only `RDCRoleType.HOST` can call `takeControl`");this.setState(t,{attachElMutationObserver:new MutationObserver(this.handleAttachElMutationChange(t))}),null===(r=this.getState(t).attachElMutationObserver)||void 0===r||r.observe(n,{childList:!0,attributeFilter:["style"]}),o.debug(`subscribe screen share video stream by streamId: ${s}, video attach to element:`,n),await this.rtcAdapter.subscribe(s,n)}quitControl(...t){const[o,s,n]=t;if(s===e.RDCRoleType.HOST&&(this.rtcAdapter.unpublish(),this.rdcAdapter.authorizeQuitControl(o,!0)),s===e.RDCRoleType.CONTROLLED&&n){this.rtcAdapter.unsubscribe(n),this.rdcAdapter.quitControl(o);const{renderingElResizeObserver:e,attachElMutationObserver:t}=this.getState(o);e&&e.disconnect(),t&&t.disconnect(),delete this.state[o]}}leave(){this.rtcAdapter.leave(),this.rdcAdapter.leave()}dispose(){this.rdcAdapter.dispose()}async exitFullscreen(){return await document.exitFullscreen()}allowObservation(){if(this.options.role!==e.RDCRoleType.HOST)throw new Error("This method can only be called if the role is `RDCRoleType.HOST`");const{channel:t}=this;if(!t)throw new Error("Please call `join` method before call `allowObservation`");this.on("rdc-state",(o=>{o===e.RDCEngineState.LOGGED_IN&&this.rdcAdapter.joinChannel(t)}))}disallowObservation(){if(this.options.role!==e.RDCRoleType.HOST)throw new Error("This method can only be called if the role is `RDCRoleType.HOST`");this.rdcAdapter.leaveChannel()}observe(t,o,s){if(this.options.role!==e.RDCRoleType.CONTROLLED)throw new Error("This method can only be called if the role is `RDCRoleType.CONTROLLED`");const{channel:n}=this;if(!n)throw new Error("Please call `join` method before call `observe`");this.rdcAdapter.sendMessage(t,{from:this.userId,event:"retrieve-observation"}),this.once("retrieved-observation",(({userId:e,capturedBy:r})=>{var i;t===e&&(this.setState(t,{capturedBy:r}),this.rtcAdapter.subscribe(o,s),"agora-webrtc-sdk-ng"!==r&&(this.setState(t,{attachElMutationObserver:new MutationObserver(this.handleAttachElMutationChange(t,!0))}),null===(i=this.getState(t).attachElMutationObserver)||void 0===i||i.observe(s,{childList:!0,attributeFilter:["style"]}),this.rdcAdapter.joinChannel(n),this.on("observation-position",this.handleObservationPositionChange(t))))}))}unobserve(t,o){if(this.options.role!==e.RDCRoleType.CONTROLLED)throw new Error("This method can only be called if the role is `RDCRoleType.CONTROLLED`");this.rtcAdapter.unsubscribe(o);const{capturedBy:s,attachElMutationObserver:n,renderingElResizeObserver:r}=this.getState(t);"agora-electron-sdk"===s&&this.rdcAdapter.leaveChannel(),n&&n.disconnect(),r&&(null==r||r.disconnect()),delete this.state[t],this.off("observation-position",this.handleObservationPositionChange),this.removeCursor(t)}requestPlatform(e){return new Promise(((t,o)=>{this.once("rdc-remote-end-info",(s=>{s.peer!==e&&o(new Error("The userId is not match")),s.os.toLowerCase().includes("android")?t("android"):t("unknown")})),this.rdcAdapter.requestRemoteEndInfo(e)}))}sendAction(t,o,s){if(this.options.role!==e.RDCRoleType.HOST)throw new Error("This method can only be called if the role is `RDCRoleType.HOST`");if(!T.includes(o))throw new Error("The platform is not supported to send action.");this.rdcAdapter.emit("keyboard-event",{userId:t,keyCode:s})}on(e,t,o){return super.on(e,t,o),this}off(e,t){return super.off(e,t),this}initialize(){const{appId:t,logLevel:s,logPath:n,mouseEventsThreshold:r,keyboardEventsThreshold:i}=this.options;o.setLogLevel(null!=s?s:e.LogLevel.DEBUG),this.rdcAdapter.initialize(t,{logLevel:s,logPath:n,mouseEventsThreshold:r,keyboardEventsThreshold:i}),this.rtcAdapter.initialize(),this.handleAddonEvents()}setState(e,t){var s;o.debug("set state for: ",e,t),this.state[e]={...null!==(s=this.state[e])&&void 0!==s?s:{},...t}}getState(e){var t;return null!==(t=this.state[e])&&void 0!==t?t:{}}updateControlRect(e,t){o.debug(`Update control Rect, width: ${e}, height: ${t}`),this.rdcAdapter.updateControlRect(e,t)}enableFocus(e){e.setAttribute("tabindex","1")}createCursorUpdater(e){return(t,s)=>{const{capturedBy:n}=this.getState(t);switch(n){case"agora-electron-sdk":this.cursorUpdaterForElectronRTC(e,s);break;case"agora-webrtc-sdk-ng":this.cursorUpdaterForWebRTC(e,s);break;default:o.error("Screen stream from unknown sdk.")}}}cursorUpdaterForWebRTC(e,t){-1===t&&(e.style.cursor="none"),-2===t&&(e.style.cursor="default"),e.style.outline="none"}cursorUpdaterForElectronRTC(e,t){if(void 0===t)throw new Error("Cursor code is undefined");-1===t&&(e.style.cursor="none"),-2===t&&(e.style.cursor="default"),i[t]&&(e.style.cursor=i[t],e.style.outline="none")}handleAddonEvents(){this.rdcAdapter.onEvent(((t,s,n)=>{switch(t){case e.RDCAddonEvents.STATE:o.info(`Emit \`rdc-state\`, code: ${s}, message: ${n}`),this.emit("rdc-state",s,n);break;case e.RDCAddonEvents.CTRL_REQ:this.handleRequestControl(n);break;case e.RDCAddonEvents.QUIT_REQ:this.emit("rdc-quit-control",JSON.parse(n).peer);break;case e.RDCAddonEvents.LOGIN:o.info(`Emit \`rdc-join-error\`, code: ${s}, message: ${n}`),this.emit("rdc-join-error",s,n);break;case e.RDCAddonEvents.GETTING_FOCUS:this.handleGettingFocus(n);break;case e.RDCAddonEvents.MOUSE_STATUS:this.handleMouseStateChange(n);break;case e.RDCAddonEvents.MSG:this.handleRDCMessage(n);break;case e.RDCAddonEvents.UPLOAD_RESULT:this.handleRemotePasteEvent(s===e.RDCRemotelyPastingCodes.SUCCEEDED?e.RDCRemotelyPastingStatus.TRANSMITTED:e.RDCRemotelyPastingStatus.FAILED,s);break;case e.RDCAddonEvents.REMOTE_PASTED:this.handleRemotePasteEvent(s===e.RDCRemotelyPastingCodes.SUCCEEDED?e.RDCRemotelyPastingStatus.SUCCEEDED:e.RDCRemotelyPastingStatus.FAILED,s);break;case e.RDCAddonEvents.OBSERVATION:this.emit("observation-position",JSON.parse(n).data);break;case e.RDCAddonEvents.REMOTE_END_INFO:this.emit("rdc-remote-end-info",JSON.parse(n))}}))}handleRemotePasteEvent(e,t){this.emit("rdc-remote-paste",e,t)}bindDOMEvents(t,s){const n={click:this.handleClick(t),dblclick:this.handleDblclick(t),contextmenu:this.handleMouseEvent(t,e.RDCMouseEventType.RIGHT_CLICK),wheel:this.handleMouseEvent(t,e.RDCMouseEventType.WHEEL),keyup:this.handleKeyupEvent(t),keydown:this.handleKeydownEvent(t),mousedown:this.handleMouseDown(t),mouseup:this.handleMouseUp(t),mousemove:this.handleMouseMove(t),mouseleave:this.handleMouseLeave(t),drop:this.handleDrop(t),dragover:e=>e.preventDefault(),dragleave:e=>e.preventDefault(),ondragend:e=>e.preventDefault()};Object.keys(n).forEach((e=>{s.addEventListener(e,n[e])})),this.setState(t,{domEventListeners:n}),o.debug(`bind dom events for userId: ${t}, to: `,s)}unbindDOMEvents(e,t){const{domEventListeners:s}=this.getState(e);s&&(Object.keys(s).forEach((e=>{t.removeEventListener(e,s[e])})),this.setState(e,{domEventListeners:void 0}),o.debug(`unbind dom events for userId: ${e}, to: `,t))}handleClick(t){const{isFocused:o,cursorUpdater:s,capturedBy:n}=this.getState(t);return r=>{o||(this.setState(t,{isFocused:!0}),this.rdcAdapter.focus(!0)),s&&"agora-webrtc-sdk-ng"===n&&s(t,-1);const{mousedownX:i,mousedownY:a,mouseupX:d,mouseupY:l}=this.getState(t);if(i!==d&&a!==l)return void this.setState(t,{mousedownX:void 0,mousedownY:void 0,mouseupX:void 0,mouseupY:void 0});this.setState(t,{mousedownX:void 0,mousedownY:void 0,mouseupX:void 0,mouseupY:void 0});const h=window.setTimeout((()=>{this.getState(t).preventClick||this.handleMouseEvent(t,e.RDCMouseEventType.LEFT_CLICK)(r),this.setState(t,{preventClick:!1})}),200);this.setState(t,{preventTimer:h})}}handleDblclick(t){return o=>{clearTimeout(this.getState(t).preventTimer),this.setState(t,{preventClick:!0}),this.handleMouseEvent(t,e.RDCMouseEventType.LEFT_DBL_CLICK)(o)}}createCursor(e,t){this.removeCursor(e);let o=0,s=0;if(t instanceof HTMLVideoElement&&(o=Math.floor(t.clientHeight),s=Math.floor(t.clientWidth)),t instanceof HTMLCanvasElement){const e=Number(t.style.zoom);o=Math.floor(t.height*e),s=Math.floor(t.width*e)}const n=document.createElement("div");n.style.display="none",n.style.position="absolute",n.style.height=`${o}px`,n.style.width=`${s}px`,n.style.zIndex="9",n.setAttribute("id",`cursor-${e}`),n.innerHTML='\n <div style="height: 100%; width: 100%; position: relative;">\n <div id="cursor" style="display: flex; justify-content: center; align-items: center; position: absolute; height: 16px; width: 16px; border-radius: 16px; background-color: #ddd; opacity: 0.9">\n <div style="height: 10px; width: 10px; border-radius: 10px; background-color: #bbb;">\n </div>\n </div>\n </div>\n ',t.after(n)}removeCursor(e){const t=document.querySelector(`#cursor-${e}`);t&&t.remove()}updateCursorMaskSize(e,t,o){const s=document.querySelector(`#cursor-${e}`);s&&(s.style.height=`${o}px`,s.style.width=`${t}px`)}},e.AbstractRTCAdapter=class extends v{constructor(e,t,o){super(),this.appId=e,this.rtcEngine=t,this.role=o}},e.DEFAULT_DISPLAY_CONFIGURATION=R,e.DEFAULT_RECT={x:0,y:0,height:0,width:0},e.EventEmitter=v,e.MOUSE_EVENTS=g,e.PLATFORMS=T,e.RDCAddon=s,e.RDCAddonAdapter=n,e.RDC_KEY_CODES=r,e.RDC_MOUSE_CURSOR_CODES=i,e.isMacOS=function(){return navigator.userAgent.toLowerCase().indexOf("mac")>=0},e.isRetinaDisplay=function(){return window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)").matches||window.devicePixelRatio>1},e.isWindows=function(){return navigator.userAgent.toLowerCase().indexOf("win")>=0},e.logger=o,e.removeNullable=D,Object.defineProperty(e,"__esModule",{value:!0})}));