UNPKG

agora-rdc-core

Version:

2 lines (1 loc) 24.7 kB
var e;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARNING=2]="WARNING",e[e.ERROR=3]="ERROR",e[e.FATAL=4]="FATAL"}(e||(e={}));const t=new class{constructor(){this.logLevel=e.DEBUG}debug(...t){const s=[e.DEBUG].concat(t);this.log.apply(this,s)}info(...t){const s=[e.INFO].concat(t);this.log.apply(this,s)}warning(...t){const s=[e.WARNING].concat(t);this.log.apply(this,s)}error(...t){const s=[e.ERROR].concat(t);this.log.apply(this,s)}setLogLevel(e){this.logLevel=Math.min(Math.max(0,e),4)}log(...t){const s=Math.max(0,Math.min(4,t[0]));if(s<this.logLevel)return;const o=`${(new Date).toISOString()} %cagora-rdc [${e[s]}]:`;let r=[];switch(s){case e.DEBUG:r=[o,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,r);break;case e.INFO:r=[o,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,r);break;case e.WARNING:r=[o,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,r);break;case e.ERROR:r=[o,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,r)}}};var s=require("../build/Release/agora-rc-extension").RemoteControlEngine;class o{constructor(){this.addon=new s}static create(){return this.instance||(this.instance=new o),this.instance}initialize(t,s){const{logPath:o,mouseEventsThreshold:r,keyboardEventsThreshold:n,logLevel:i=e.DEBUG}=s;let a={log_path:o,mouse_buff_ms:r,kb_buff_ms:n};i===e.DEBUG&&(a.log_level=0),i===e.INFO&&(a.log_level=2),i===e.WARNING&&(a.log_level=3),i===e.ERROR&&(a.log_level=4),i===e.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 s=t.userId;switch(e){case"keyboard-event":const{keyCode:e,isCompoundAlt:o,isCompoundCtrl:r,isCompoundShift:n}=t;this.addon.keyEvent(s,e,r?1:0,o?1:0,n?1:0);break;case"mouse-event":const{type:i,x:a,y:d,delta:h}=t;this.addon.mouseEvent(s,i,a,d,null!=h?h: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},n={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 i,a,d,h,l,c,u,E,p;!function(e){e.LOGIN="login",e.STATE="state",e.SEND_RESULT="send_result",e.MSG="msg",e.CTRL_REQ="ctrl_req",e.QUIT_REQ="quit_req",e.GETTING_FOCUS="hold_control",e.MOUSE_STATUS="mouse_status",e.UPLOAD_RESULT="upload_result",e.PASTED="pasted",e.REMOTE_PASTED="remote_pasted",e.OBSERVATION="bc_data",e.REMOTE_END_INFO="remote_info"}(i||(i={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXT=2]="TEXT",e[e.FILE=1]="FILE"}(a||(a={})),function(e){e[e.LEFT_CLICK=1]="LEFT_CLICK",e[e.LEFT_DBL_CLICK=2]="LEFT_DBL_CLICK",e[e.RIGHT_CLICK=3]="RIGHT_CLICK",e[e.RIGHT_DBL_CLICK=4]="RIGHT_DBL_CLICK",e[e.MID_CLICK=5]="MID_CLICK",e[e.WHEEL=6]="WHEEL",e[e.MOVE=7]="MOVE",e[e.DRAG_BEGIN=8]="DRAG_BEGIN",e[e.DRAG_MOVE=9]="DRAG_MOVE",e[e.DRAG_END=10]="DRAG_END"}(d||(d={})),function(e){e[e.UNKNOWN_ERROR=1]="UNKNOWN_ERROR",e[e.SERVER_REJECTED=2]="SERVER_REJECTED",e[e.INVALID_LOGIN_ARGUMENT=3]="INVALID_LOGIN_ARGUMENT",e[e.INVALID_APP_ID=4]="INVALID_APP_ID",e[e.INVALID_TOKEN=5]="INVALID_TOKEN",e[e.TOKEN_EXPIRED=6]="TOKEN_EXPIRED",e[e.AUTHORIZE_FAIL=7]="AUTHORIZE_FAIL",e[e.DUPLICATED_LOGIN=8]="DUPLICATED_LOGIN",e[e.TIMEOUT=9]="TIMEOUT",e[e.LOGIN_TOO_OFTEN=10]="LOGIN_TOO_OFTEN",e[e.NOT_INITIALIZED=101]="NOT_INITIALIZED"}(h||(h={})),function(e){e[e.INITIALIZED=1]="INITIALIZED",e[e.LOGGED_IN=2]="LOGGED_IN",e[e.LOGGED_OUT=3]="LOGGED_OUT",e[e.CONNECTED=4]="CONNECTED",e[e.DISCONNECT=5]="DISCONNECT"}(l||(l={}));class C{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 s=this.events.get(e);if(void 0===s){if("error"===e){const e=t[0];if(e instanceof Error)throw e;throw new Error("Unhandled error.")}return!1}return[...s].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,s){!1===this.events.has(e)&&this.events.set(e,[]);const o=this.events.get(e);s?o.unshift(t):o.push(t),"newListener"!==e&&this.events.has("newListener")&&this.emit("newListener",e,t);const r=this.getMaxListeners(),n=o.length;if(r>0&&n>r&&!o.warned){o.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 s=t.get(e);return void 0!==s&&s.forEach((t=>{this.removeListener(e,t)})),this}removeListener(e,t){const{events:s}=this;if(0===s.size)return this;const o=s.get(e);if(void 0===o)return this;const r=o.findIndex((e=>e===t||e.listener===t));return-1===r||(o.splice(r,1),0===o.length&&this.events.delete(e),s.has("removeListener")&&this.emit("removeListener",e,t)),this}once(e,t){return this.on(e,this.onceWrap(e,t)),this}onceWrap(e,t){const s=function(...e){this.context.removeListener(this.eventName,this.wrappedListener),this.listener.apply(this.context,e)},o={eventName:e,listener:t,wrappedListener:s,context:this},r=s.bind(o);return o.wrappedListener=r,r.listener=t,r}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 s=t.get(e);return void 0===s?[]:[...s]}}!function(e){e[e.HOST=1]="HOST",e[e.CONTROLLED=2]="CONTROLLED"}(c||(c={})),function(e){e[e.STARTING=0]="STARTING",e[e.TRANSMITTED=1]="TRANSMITTED",e[e.SUCCEEDED=2]="SUCCEEDED",e[e.FAILED=3]="FAILED"}(u||(u={})),function(e){e[e.SUCCEEDED=0]="SUCCEEDED",e[e.FAILURE=1]="FAILURE",e[e.TIMEOUT=3]="TIMEOUT",e[e.SIZE_OVERFLOW=4]="SIZE_OVERFLOW",e[e.CONCURRENCY_LIMIT_EXCEEDED=5]="CONCURRENCY_LIMIT_EXCEEDED",e[e.UNSUPPORTED_FILE_TYPE=99]="UNSUPPORTED_FILE_TYPE",e[e.NOT_INITIALIZED=101]="NOT_INITIALIZED",e[e.NOT_LOGGED_IN=102]="NOT_LOGGED_IN"}(E||(E={})),function(e){e[e.ACTION_BACK=64001]="ACTION_BACK",e[e.ACTION_HOME=64002]="ACTION_HOME",e[e.ACTION_RECENT=64003]="ACTION_RECENT",e[e.ACTION_NOTIFICATIONS=64004]="ACTION_NOTIFICATIONS",e[e.ACTION_QUICK_SETTINGS=64005]="ACTION_QUICK_SETTINGS",e[e.ACTION_POWER_DIALOG=64006]="ACTION_POWER_DIALOG",e[e.ACTION_TOGGLE_SPLIT_SCREEN=64007]="ACTION_TOGGLE_SPLIT_SCREEN",e[e.ACTION_LOCK_SCREEN=64008]="ACTION_LOCK_SCREEN",e[e.ACTION_SCREENSHOT=64009]="ACTION_SCREENSHOT"}(p||(p={}));const v={x:0,y:0,height:0,width:0},g={bitrate:2e3,frameRate:10,height:1080,width:1920},m={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 O(e){const t={...e};return Object.keys(t).forEach((e=>{void 0!==t[e]&&null!==t[e]||delete t[e]})),t}function I(){return navigator.userAgent.toLowerCase().indexOf("mac")>=0}function L(){return navigator.userAgent.toLowerCase().indexOf("win")>=0}function f(){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}class R extends C{constructor(e){super(),this.state={},this.handleRequestControl=e=>{const{peer:s,answer:o,msg:r}=JSON.parse(e),n=Boolean(Number(r));return o&&n?(t.debug("Emit `rdc-request-control-authorized`: ",s),void this.emit("rdc-request-control-authorized",s)):o&&!n?(t.debug("Emit `rdc-request-control-unauthorized`: ",s),void this.emit("rdc-request-control-unauthorized",s)):(t.debug("Emit `rdc-request-control`: ",s),void this.emit("rdc-request-control",s))},this.handleGettingFocus=e=>{const{hold:s}=JSON.parse(e),o={...g,captureMouseCursor:!s};this.rtcAdapter.updateDisplayConfiguration(o),t.debug("update screen capture params: ",o)},this.handleRDCMessage=e=>{try{const s=JSON.parse(e),{from:o,event:r}=s;if(!o)return void t.warning("Unknown message from, dispose.");switch(r){case"retrieve-observation":this.rdcAdapter.sendMessage(o,{from:this.userId,event:"retrieved-observation",capturedBy:this.capturedBy});break;case"retrieved-observation":this.emit("retrieved-observation",{userId:o,capturedBy:s.capturedBy});break;case"captured-by":this.setState(o,{capturedBy:s.capturedBy});break;default:t.warning("Unknown message event, dispose.")}}catch(e){t.error(e)}},this.handleMouseStateChange=e=>{const{cursor:s,peer:o}=JSON.parse(e),{cursor:r,cursorUpdater:i,isFocused:a}=this.getState(o);if(a){if(!i)throw new Error(`cursor updater is no created correctly for: ${o}`);s!==r&&(this.setState(o,{cursor:r}),i(o,s),t.debug("update cursor: ",n[s]))}},this.handleMouseEvent=(e,s)=>o=>{o.preventDefault(),o.stopPropagation();const r={userId:e,type:s,x:o.offsetX,y:o.offsetY,delta:o instanceof WheelEvent?o.deltaY:void 0};this.rdcAdapter.emit("mouse-event",r),t.debug("RDCEngine emit `mouse-event`, ",r,m[s])},this.handleMouseDown=e=>t=>{this.getState(e).isFocused&&this.setState(e,{mousedownX:t.x,mousedownY:t.y})},this.handleMouseUp=e=>t=>{if(!this.getState(e).isFocused)return;this.setState(e,{mouseupX:t.x,mouseupY:t.y});const{isDragging:s,mousedownX:o,mousedownY:r,mouseupX:n,mouseupY:i}=this.getState(e);!s||o===n&&r===i||(this.handleMouseEvent(e,d.DRAG_END)(t),this.setState(e,{isDragging:!1}))},this.handleMouseMove=e=>t=>{if(!this.getState(e).isFocused)return;const{isDragging:s,mousedownX:o,mousedownY:r,mouseupX:n,mouseupY:i}=this.getState(e);!s&&"number"==typeof o&&"number"==typeof r&&void 0===n&&void 0===i&&(Math.abs(o-t.x)>0||Math.abs(r-t.y)>0)&&(this.handleMouseEvent(e,d.DRAG_BEGIN)(t),this.setState(e,{isDragging:!0})),this.handleMouseEvent(e,this.getState(e).isDragging?d.DRAG_MOVE:d.MOVE)(t)},this.handleMouseLeave=e=>t=>{if(!this.getState(e).isFocused)return;this.getState(e).isDragging&&this.handleMouseUp(e)(t);const{cursorUpdater:s}=this.getState(e);s&&s(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=e=>s=>{if(s.preventDefault(),s.stopPropagation(),!this.getState(e).isFocused)return;const{isCompoundShift:o,isCompoundCtrl:r,isCompoundAlt:n,isCompoundMeta:i}=this.getState(e);if(o&&"Shift"===s.key)return t.debug("RDCEngine `keyboard-event`: `Shift` Compounded"),void this.setState(e,{isCompoundShift:!1});if(r&&"Control"===s.key)return t.debug("RDCEngine `keyboard-event`: `Control` Compounded"),void this.setState(e,{isCompoundCtrl:!1});if(n&&"Alt"===s.key)return t.debug("RDCEngine `keyboard-event`: `Alt` Compounded"),void this.setState(e,{isCompoundAlt:!1});if(i&&"Meta"===s.key)return t.debug("RDCEngine `keyboard-event`: `Meta` Compounded"),void this.setState(e,{isCompoundMeta:!1});s.ctrlKey&&"KeyV"===s.code&&(this.rdcAdapter.pasteRemotely(),this.rdcAdapter.getClipboardContentType()===a.FILE&&this.handleRemotePasteEvent(u.STARTING,E.SUCCEEDED));const d={userId:e,keyCode:this.getKeyCode(s),isCompoundAlt:s.altKey,isCompoundShift:s.shiftKey,isCompoundCtrl:s.ctrlKey};t.debug("RDCEngine emit `keyboard-event`, ",d),this.rdcAdapter.emit("keyboard-event",d)},this.handleDrop=e=>e=>{var t;e.preventDefault(),e.stopPropagation();const{files:s}=null!==(t=e.dataTransfer)&&void 0!==t?t:{};if(s)for(const e of Array.from(s)){const t=e;this.rdcAdapter.pasteRemotely(!0,t.path),this.handleRemotePasteEvent(u.STARTING,E.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=>s=>{const o=s[s.length-1];t.debug("position change",o);const r=document.querySelector(`#cursor-${e}`);if(!r||!o)return;r.style.display="block";const n=r.querySelector("#cursor");n&&(n.style.top=o.y-8+"px",n.style.left=o.x-8+"px")},this.options=e,this.rdcAdapter=o.create()}getRole(){return this.options.role}async getDisplays(){if(this.options.role!==c.CONTROLLED)throw new Error("Only `RDCRoleType.CONTROLLED` can call `getDisplays`");return await this.rtcAdapter.getDisplays()}async join(...e){const[s,o,r,n,i]=e;this.userId=s,this.streamId=n,this.channel=r,t.debug(`Join RDC engine with userId: ${s}`),this.rdcAdapter.join(s,o),t.debug(`Join RTC engine with channel: ${r}, streamId: ${n}`),await this.rtcAdapter.join(n,r,null!=i?i:o)}requestControl(e){if(this.options.role!==c.HOST)throw new Error("Only `RDCRoleType.HOST` can call `requestControl`");t.debug(`Request control for userId: ${e}`),this.rdcAdapter.requestControl(e)}authorizeControl(e,s,o,r){const{role:n}=this.options;if(n!==c.CONTROLLED)throw new Error("Only `RDCRoleType.CONTROLLED` can call `authorizeControl`");t.debug("Start screen capture by displayId:",s.id,"configuration",o),this.rtcAdapter.publish(s,o?O({enableLoopback:!0,...o}):o,r),this.rdcAdapter.updateControlRect(s.width,s.height),this.rdcAdapter.authorizeControl(e,!0),this.rdcAdapter.sendMessage(e,{from:this.userId,event:"captured-by",capturedBy:this.capturedBy})}unauthorizeControl(e){if(this.options.role!==c.CONTROLLED)throw new Error("Only `RDCRoleType.CONTROLLED` can call `unauthorizeControl`");this.rdcAdapter.authorizeControl(e,!1)}async takeControl(e,s,o){var r;if(this.options.role!==c.HOST)throw new Error("Only `RDCRoleType.HOST` can call `takeControl`");this.setState(e,{attachElMutationObserver:new MutationObserver(this.handleAttachElMutationChange(e))}),null===(r=this.getState(e).attachElMutationObserver)||void 0===r||r.observe(o,{childList:!0,attributeFilter:["style"]}),t.debug(`subscribe screen share video stream by streamId: ${s}, video attach to element:`,o),await this.rtcAdapter.subscribe(s,o)}quitControl(...e){const[t,s,o]=e;if(s===c.HOST&&(this.rtcAdapter.unpublish(),this.rdcAdapter.authorizeQuitControl(t,!0)),s===c.CONTROLLED&&o){this.rtcAdapter.unsubscribe(o),this.rdcAdapter.quitControl(t);const{renderingElResizeObserver:e,attachElMutationObserver:s}=this.getState(t);e&&e.disconnect(),s&&s.disconnect(),delete this.state[t]}}leave(){this.rtcAdapter.leave(),this.rdcAdapter.leave()}dispose(){this.rdcAdapter.dispose()}async exitFullscreen(){return await document.exitFullscreen()}allowObservation(){if(this.options.role!==c.HOST)throw new Error("This method can only be called if the role is `RDCRoleType.HOST`");const{channel:e}=this;if(!e)throw new Error("Please call `join` method before call `allowObservation`");this.on("rdc-state",(t=>{t===l.LOGGED_IN&&this.rdcAdapter.joinChannel(e)}))}disallowObservation(){if(this.options.role!==c.HOST)throw new Error("This method can only be called if the role is `RDCRoleType.HOST`");this.rdcAdapter.leaveChannel()}observe(e,t,s){if(this.options.role!==c.CONTROLLED)throw new Error("This method can only be called if the role is `RDCRoleType.CONTROLLED`");const{channel:o}=this;if(!o)throw new Error("Please call `join` method before call `observe`");this.rdcAdapter.sendMessage(e,{from:this.userId,event:"retrieve-observation"}),this.once("retrieved-observation",(({userId:r,capturedBy:n})=>{var i;e===r&&(this.setState(e,{capturedBy:n}),this.rtcAdapter.subscribe(t,s),"agora-webrtc-sdk-ng"!==n&&(this.setState(e,{attachElMutationObserver:new MutationObserver(this.handleAttachElMutationChange(e,!0))}),null===(i=this.getState(e).attachElMutationObserver)||void 0===i||i.observe(s,{childList:!0,attributeFilter:["style"]}),this.rdcAdapter.joinChannel(o),this.on("observation-position",this.handleObservationPositionChange(e))))}))}unobserve(e,t){if(this.options.role!==c.CONTROLLED)throw new Error("This method can only be called if the role is `RDCRoleType.CONTROLLED`");this.rtcAdapter.unsubscribe(t);const{capturedBy:s,attachElMutationObserver:o,renderingElResizeObserver:r}=this.getState(e);"agora-electron-sdk"===s&&this.rdcAdapter.leaveChannel(),o&&o.disconnect(),r&&(null==r||r.disconnect()),delete this.state[e],this.off("observation-position",this.handleObservationPositionChange),this.removeCursor(e)}requestPlatform(e){return new Promise(((t,s)=>{this.once("rdc-remote-end-info",(o=>{o.peer!==e&&s(new Error("The userId is not match")),o.os.toLowerCase().includes("android")?t("android"):t("unknown")})),this.rdcAdapter.requestRemoteEndInfo(e)}))}sendAction(e,t,s){if(this.options.role!==c.HOST)throw new Error("This method can only be called if the role is `RDCRoleType.HOST`");if(!T.includes(t))throw new Error("The platform is not supported to send action.");this.rdcAdapter.emit("keyboard-event",{userId:e,keyCode:s})}on(e,t,s){return super.on(e,t,s),this}off(e,t){return super.off(e,t),this}initialize(){const{appId:s,logLevel:o,logPath:r,mouseEventsThreshold:n,keyboardEventsThreshold:i}=this.options;t.setLogLevel(null!=o?o:e.DEBUG),this.rdcAdapter.initialize(s,{logLevel:o,logPath:r,mouseEventsThreshold:n,keyboardEventsThreshold:i}),this.rtcAdapter.initialize(),this.handleAddonEvents()}setState(e,s){var o;t.debug("set state for: ",e,s),this.state[e]={...null!==(o=this.state[e])&&void 0!==o?o:{},...s}}getState(e){var t;return null!==(t=this.state[e])&&void 0!==t?t:{}}updateControlRect(e,s){t.debug(`Update control Rect, width: ${e}, height: ${s}`),this.rdcAdapter.updateControlRect(e,s)}enableFocus(e){e.setAttribute("tabindex","1")}createCursorUpdater(e){return(s,o)=>{const{capturedBy:r}=this.getState(s);switch(r){case"agora-electron-sdk":this.cursorUpdaterForElectronRTC(e,o);break;case"agora-webrtc-sdk-ng":this.cursorUpdaterForWebRTC(e,o);break;default:t.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"),n[t]&&(e.style.cursor=n[t],e.style.outline="none")}handleAddonEvents(){this.rdcAdapter.onEvent(((e,s,o)=>{switch(e){case i.STATE:t.info(`Emit \`rdc-state\`, code: ${s}, message: ${o}`),this.emit("rdc-state",s,o);break;case i.CTRL_REQ:this.handleRequestControl(o);break;case i.QUIT_REQ:this.emit("rdc-quit-control",JSON.parse(o).peer);break;case i.LOGIN:t.info(`Emit \`rdc-join-error\`, code: ${s}, message: ${o}`),this.emit("rdc-join-error",s,o);break;case i.GETTING_FOCUS:this.handleGettingFocus(o);break;case i.MOUSE_STATUS:this.handleMouseStateChange(o);break;case i.MSG:this.handleRDCMessage(o);break;case i.UPLOAD_RESULT:this.handleRemotePasteEvent(s===E.SUCCEEDED?u.TRANSMITTED:u.FAILED,s);break;case i.REMOTE_PASTED:this.handleRemotePasteEvent(s===E.SUCCEEDED?u.SUCCEEDED:u.FAILED,s);break;case i.OBSERVATION:this.emit("observation-position",JSON.parse(o).data);break;case i.REMOTE_END_INFO:this.emit("rdc-remote-end-info",JSON.parse(o))}}))}handleRemotePasteEvent(e,t){this.emit("rdc-remote-paste",e,t)}bindDOMEvents(e,s){const o={click:this.handleClick(e),dblclick:this.handleDblclick(e),contextmenu:this.handleMouseEvent(e,d.RIGHT_CLICK),wheel:this.handleMouseEvent(e,d.WHEEL),keyup:this.handleKeyupEvent(e),keydown:this.handleKeydownEvent(e),mousedown:this.handleMouseDown(e),mouseup:this.handleMouseUp(e),mousemove:this.handleMouseMove(e),mouseleave:this.handleMouseLeave(e),drop:this.handleDrop(e),dragover:e=>e.preventDefault(),dragleave:e=>e.preventDefault(),ondragend:e=>e.preventDefault()};Object.keys(o).forEach((e=>{s.addEventListener(e,o[e])})),this.setState(e,{domEventListeners:o}),t.debug(`bind dom events for userId: ${e}, to: `,s)}unbindDOMEvents(e,s){const{domEventListeners:o}=this.getState(e);o&&(Object.keys(o).forEach((e=>{s.removeEventListener(e,o[e])})),this.setState(e,{domEventListeners:void 0}),t.debug(`unbind dom events for userId: ${e}, to: `,s))}handleClick(e){const{isFocused:t,cursorUpdater:s,capturedBy:o}=this.getState(e);return r=>{t||(this.setState(e,{isFocused:!0}),this.rdcAdapter.focus(!0)),s&&"agora-webrtc-sdk-ng"===o&&s(e,-1);const{mousedownX:n,mousedownY:i,mouseupX:a,mouseupY:h}=this.getState(e);if(n!==a&&i!==h)return void this.setState(e,{mousedownX:void 0,mousedownY:void 0,mouseupX:void 0,mouseupY:void 0});this.setState(e,{mousedownX:void 0,mousedownY:void 0,mouseupX:void 0,mouseupY:void 0});const l=window.setTimeout((()=>{this.getState(e).preventClick||this.handleMouseEvent(e,d.LEFT_CLICK)(r),this.setState(e,{preventClick:!1})}),200);this.setState(e,{preventTimer:l})}}handleDblclick(e){return t=>{clearTimeout(this.getState(e).preventTimer),this.setState(e,{preventClick:!0}),this.handleMouseEvent(e,d.LEFT_DBL_CLICK)(t)}}createCursor(e,t){this.removeCursor(e);let s=0,o=0;if(t instanceof HTMLVideoElement&&(s=Math.floor(t.clientHeight),o=Math.floor(t.clientWidth)),t instanceof HTMLCanvasElement){const e=Number(t.style.zoom);s=Math.floor(t.height*e),o=Math.floor(t.width*e)}const r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height=`${s}px`,r.style.width=`${o}px`,r.style.zIndex="9",r.setAttribute("id",`cursor-${e}`),r.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(r)}removeCursor(e){const t=document.querySelector(`#cursor-${e}`);t&&t.remove()}updateCursorMaskSize(e,t,s){const o=document.querySelector(`#cursor-${e}`);o&&(o.style.height=`${s}px`,o.style.width=`${t}px`)}}class D extends C{constructor(e,t,s){super(),this.appId=e,this.rtcEngine=t,this.role=s}}export{R as AbstractAgoraRemoteDesktopControl,D as AbstractRTCAdapter,g as DEFAULT_DISPLAY_CONFIGURATION,v as DEFAULT_RECT,C as EventEmitter,e as LogLevel,m as MOUSE_EVENTS,T as PLATFORMS,s as RDCAddon,o as RDCAddonAdapter,i as RDCAddonEvents,p as RDCAndroidAction,a as RDCClipboardContentType,l as RDCEngineState,h as RDCJoinErrorCode,d as RDCMouseEventType,E as RDCRemotelyPastingCodes,u as RDCRemotelyPastingStatus,c as RDCRoleType,r as RDC_KEY_CODES,n as RDC_MOUSE_CURSOR_CODES,I as isMacOS,f as isRetinaDisplay,L as isWindows,t as logger,O as removeNullable};