UNPKG

agora-rtc-sdk-ng

Version:
6 lines (4 loc) 44.2 kB
/** * AgoraWebSDK_N-v4.24.8-0-gf100be755-dirty Copyright AgoraInc. */ import{IS_GLOBAL_VERSION as e,getParameter as t,EventEmitter as n,PromiseMutex as o,NETWORK_STATE as s,networkIndicator as i,NETWORK_INDICATOR_EVENTS as E,createDefer as r,AgoraRTCError as c,AgoraRTCErrorCode as _,getRetryWaitTime as a,wait as R,emitAsPromise as A,emitAsInvokerNoResponse as N,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as h,retryable as C,getRandomString as O,DEFAULT_RETRY_CONFIG as T}from"@agora-js/shared";import{logger as S,AgoraRTCError as l,AgoraRTCErrorCode as L,report as d}from"@agora-js/report";import{frameData2CryptoBuffer as u}from"@agora-js/media";import"@agora-js/protocol";import D from"axios";import"formdata-polyfill";function w(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function g(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?f(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let p=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),V=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),m=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e}({}),U=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),y=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_TOO_MANY_MESSAGES=2033]="ERR_TOO_MANY_MESSAGES",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),b=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.SHOULD_ENTER_RECONNECTING="websocket:should_enter_reconnecting",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",e}({}),M=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});M.AFRICA,M.ASIA,M.CHINA,M.EUROPE,M.GLOBAL,M.INDIA,M.JAPAN,M.NORTH_AMERICA,M.OCEANIA,M.OVERSEA,M.SOUTH_AMERICA;let P=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});P.ASIA,P.NORTH_AMERICA,P.EUROPE,P.JAPAN,P.INDIA,P.KOREA,P.HKMC,P.US,P.OVERSEA,P.GLOBAL,P.OCEANIA,P.SOUTH_AMERICA,P.AFRICA,e&&P.CHINA;let k=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),v=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),B=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({});class W extends n{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reportUrl(){return"connected"===this._state&&this.websocket?this.websocket.url:this._lastAttemptedUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get isFirstJoin(){return this.queryReconnectingWhenConnecting}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(b.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(b.CONNECTED):"closed"===this._state?this.emit(b.CLOSED):"failed"===this._state&&this.emit(b.FAILED))}resetReconnectCount(e){S.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],c=arguments.length>4&&void 0!==arguments[4]&&arguments[4],_=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=null,this._lastAttemptedUrl=null,this.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=void 0,this.name=void 0,this._state="closed",this.reconnectInterrupter=void 0,this.websocket=void 0,this.retryConfig=void 0,this.reconnectCount=0,this.forceCloseTimeout=5e3,this.queryReconnectingWhenConnecting=!1,this.onlineReconnectListener=void 0,this.useCompress=void 0,this.tryDoubleDomain=!1,this.use443PortOnly=!1,this.wsInflateLength=0,this.wsDeflateLength=0,this.closeEstablishingWs=()=>{},this.store=void 0,this.joinGatewayRecordIndex=void 0,this.store=_,this.name=e,this.retryConfig=g({},t),this.useCompress=n,this.tryDoubleDomain=r,this.use443PortOnly=c,this._initMutex=new o("websocket",_?_.clientId:void 0);const a=t.timeout,R=t.timeoutFactor,A=Math.max(300,Math.floor(3*a/5)),N=Math.max(1.2,Math.floor(8*R)/10);s.ONLINE&&(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=N),i.on(E.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===s.ONLINE?(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=N):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}disableQueryReconnectingWhenConnecting(){this.queryReconnectingWhenConnecting=!1}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const o=await this._initMutex.lock();this._lastAttemptedUrl=null,this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.queryReconnectingWhenConnecting=!0===n.queryReconnectingWhenConnecting,this.urls=e,this.state="connecting";try{var s;const e=r(),t=this.urls[this.currentURLIndex];null===(s=this.store)||void 0===s||s.beforeConnect(),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(b.CLOSED,(()=>{e.reject(new c(_.WS_DISCONNECT))})),this.once(b.CONNECTED,e.resolve),await e.promise}catch(e){}finally{o()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void S.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),S.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new c(_.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new c(_.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var n;const o=r();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const s=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),S.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),o.resolve()},i=async e=>{var t;if(S.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)o.reject(new c(_.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{const t=this.queryReconnectingWhenConnecting;this.disableQueryReconnectingWhenConnecting();const n=t&&("connecting"===this.state||"connected"===this.state)&&!0===N(this,b.SHOULD_ENTER_RECONNECTING,e.reason);("connected"===this.state||n)&&(this.reconnectReason=e.reason,this.state="reconnecting");const s=N(this,b.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,i=await this.reconnectWithAction(s);if("closed"===this.state)return void S.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!i)return o.reject(new c(_.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);o.resolve()}},E=e=>{this.emit(b.ON_MESSAGE,e)},a=e=>{S.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),t("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=t("GATEWAY_WSS_ADDRESS")),S.debug("[".concat(this.name,"] start connect, url:"),e);const R=null===(n=this.store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var A;const n=function(e,n){if("string"==typeof e)return e;const o=e.proxy,s=e.host,i=e.port;if(n){const e=t("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(s,"/ws/?p=").concat(Number(i)+150):"wss://".concat(s,":").concat(e,"/ws/?p=").concat(Number(i)+150)}return o?"wss://".concat(o,"/ws/?h=").concat(s,"&p=").concat(i):"wss://".concat(s,":").concat(i)}(e);this._websocketUrl=n,this._lastAttemptedUrl=n;const o=await this.chooseBestWebsocketConnection(e);this.websocket=o,s&&s(this.websocket.url),this.websocket.onclose=i,this.websocket.onmessage=E,this.websocket.onerror=a,null===(A=this.store)||void 0===A||A.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(e){const t="closed"===this.state,n=e instanceof c,s=n&&e.code===_.WS_ABORT,E=n&&e.code===_.WS_ERR,r=n?e.message:e&&(e.reason||e.toString());S.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},R),t||E?(o.reject(t?new c(_.WS_DISCONNECT,"websocket is closed: ".concat(r)):new c(_.WS_ERR,"init websocket failed: ".concat(r))),E&&S.error("[".concat(this.name,"] init websocket failed: ").concat(r))):i&&i(e)}return o.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;S.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||i.isOnline||!i.onlineWaiter||(this.onlineReconnectListener=i.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);S.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([R(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const o=async(e,t)=>{this.emit(b.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await o(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);S.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await o(this.urls[this.currentURLIndex],e)}else"recover"===e&&(S.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await A(this,b.REQUEST_NEW_URLS),this.currentURLIndex=0,await o(this.urls[this.currentURLIndex],e))}catch(n){var s;S.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const o=null==n||null===(s=n.data)||void 0===s?void 0:s.desc;if(Array.isArray(o)){if(o.includes("dynamic key expired"))return this.emit(b.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(o.includes("request downgrade fallback"))return this.emit(b.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class K extends W{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,n){return new Promise(((o,s)=>{let i=!1;const E=[];this.closeEstablishingWs=()=>{S.debug("[choose-best-ws] close establishing websockets"),E.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),s(new c(_.WS_ABORT,"choose best websocket aborted"))};const r=t("GATEWAY_DOMAINS");let a;const A=e.indexOf("?h="),N=r.find((t=>-1!==A?e.includes(t,A):e.includes(t)));S.debug("[choose-best-ws] currentDomain: ",N,", domains: ",r);let I=!this.tryDoubleDomain||!N;if(!I&&N){var h;const t=Date.now();try{r.forEach((t=>{const n=-1===A?e.replace(N,t):e.substr(0,A)+e.substr(A).replace(N,t),o=new WebSocket(n);o.binaryType="arraybuffer",E.push(o),S.debug("[choose-best-ws] ws is connecting:",o.url)}))}catch(e){for(S.debug("[choose-best-ws] ws create failed, fallback to single url"),E.forEach((e=>e.close()));E.length;)E.pop();I=!0}null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:E.map((e=>e.url)),service:"gateway"},n),E.forEach((e=>{e.onopen=()=>{if(i)return;const n=Date.now()-t;S.debug("[choose-best-ws] ws open cost ".concat(n,"ms")),E.filter((t=>t!==e)).forEach((e=>{S.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),i=!0,o(e)},e.onclose=e=>{if(a=e,i)return;E.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(S.debug("[choose-best-ws] all websocket is closed"),i=!0,s(a))},e.onmessage=t=>{S.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),R(this.forceCloseTimeout).then((()=>{E.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var C;let t;S.debug("[choose-best-ws] use single url: ",e),null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:[e],service:"gateway"},n);try{t=new WebSocket(e),E.push(t),t.binaryType="arraybuffer"}catch(e){const t=new c(_.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return S.error("[".concat(this.name,"]").concat(t)),void s(t)}t.onopen=()=>{o(t)},t.onclose=e=>{s(e)},t.onmessage=e=>{S.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))},R(this.forceCloseTimeout).then((()=>{t&&t.readyState!==WebSocket.OPEN&&t.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function G(e){let t=z();return function(e,t){let n=e.appId;void 0!==n&&(Ae(t,10),ie(t,n));let o=e.cid;void 0!==o&&(Ae(t,16),Ae(t,o));let s=e.cname;void 0!==s&&(Ae(t,26),ie(t,s));let i=e.deviceId;void 0!==i&&(Ae(t,34),ie(t,i));let E=e.elapse;void 0!==E&&(Ae(t,40),Ne(t,E));let r=e.fileSize;void 0!==r&&(Ae(t,48),Ne(t,Q(r)));let c=e.height;void 0!==c&&(Ae(t,56),Ne(t,Q(c)));let _=e.jpg;void 0!==_&&(Ae(t,66),Ae(t,_.length),function(e,t){let n=ne(e,t.length);e.bytes.set(t,n)}(t,_));let a=e.networkType;void 0!==a&&(Ae(t,72),Ne(t,Q(a)));let R=e.osType;void 0!==R&&(Ae(t,80),Ne(t,Q(R)));let A=e.requestId;void 0!==A&&(Ae(t,90),ie(t,A));let N=e.sdkVersion;void 0!==N&&(Ae(t,98),ie(t,N));let I=e.sequence;void 0!==I&&(Ae(t,104),Ne(t,Q(I)));let h=e.sid;void 0!==h&&(Ae(t,114),ie(t,h));let C=e.timestamp;void 0!==C&&(Ae(t,120),Ne(t,C));let O=e.uid;void 0!==O&&(Ae(t,128),Ae(t,O));let T=e.vid;void 0!==T&&(Ae(t,136),Ae(t,T));let S=e.width;void 0!==S&&(Ae(t,144),Ne(t,Q(S)));let l=e.service;void 0!==l&&(Ae(t,152),Ae(t,l));let L=e.callbackData;void 0!==L&&(Ae(t,162),ie(t,L));let d=e.jpgEncryption;void 0!==d&&(Ae(t,168),Ae(t,d));let u=e.requestType;void 0!==u&&(Ae(t,176),Ae(t,u));let D=e.scorePorn;void 0!==D&&(Ae(t,185),ae(t,D));let w=e.scoreSexy;void 0!==w&&(Ae(t,193),ae(t,w));let f=e.scoreNeutral;void 0!==f&&(Ae(t,201),ae(t,f));let g=e.scene;void 0!==g&&(Ae(t,208),Ae(t,g));let p=e.ossFilePrefix;void 0!==p&&(Ae(t,218),ie(t,p));let V=e.serviceVendor;if(void 0!==V)for(let e of V){Ae(t,226);let n=z();F(e,n),Ae(t,n.limit),Ee(t,n),$(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function H(e){return function(e){let t={};e:for(;!te(e);){let n=Re(e);switch(n>>>3){case 0:break e;case 1:t.code=Re(e);break;case 2:t.msg=se(e,Re(e));break;case 3:{let n=x(e);t.data=Y(e),e.limit=n;break}default:q(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Y(e){let t={};e:for(;!te(e);){let n=Re(e);switch(n>>>3){case 0:break e;case 1:t.requestId=se(e,Re(e));break;case 2:t.requestType=Re(e)>>>0;break;case 3:t.scorePorn=_e(e);break;case 4:t.scoreSexy=_e(e);break;case 5:t.scoreNeutral=_e(e);break;case 6:t.requestScene=Re(e)>>>0;break;case 7:t.scene=Re(e)>>>0;break;default:q(e,7&n)}}return t}function F(e,t){let n=e.service;void 0!==n&&(Ae(t,8),Ae(t,n));let o=e.vendor;void 0!==o&&(Ae(t,16),Ae(t,o));let s=e.token;void 0!==s&&(Ae(t,26),ie(t,s));let i=e.callbackUrl;void 0!==i&&(Ae(t,34),ie(t,i))}function x(e){let t=Re(e),n=e.limit;return e.limit=e.offset+t,n}function q(e,t){switch(t){case 0:for(;128&re(e););break;case 2:ee(e,Re(e));break;case 5:ee(e,4);break;case 1:ee(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let J=new Float32Array(1);new Uint8Array(J.buffer);let j=new Float64Array(1),X=new Uint8Array(j.buffer);function Q(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Z=[];function z(){const e=Z.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function $(e){Z.push(e)}function ee(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function te(e){return e.offset>=e.limit}function ne(e,t){let n=e.bytes,o=e.offset,s=e.limit,i=o+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>s&&(e.limit=i),o}function oe(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function se(e,t){let n=oe(e,t),o=String.fromCharCode,s=e.bytes,i="�",E="";for(let e=0;e<t;e++){let r,c,_,a,R=s[e+n];0==(128&R)?E+=o(R):192==(224&R)?e+1>=t?E+=i:(r=s[e+n+1],128!=(192&r)?E+=i:(a=(31&R)<<6|63&r,a<128?E+=i:(E+=o(a),e++))):224==(240&R)?e+2>=t?E+=i:(r=s[e+n+1],c=s[e+n+2],32896!=(49344&(r|c<<8))?E+=i:(a=(15&R)<<12|(63&r)<<6|63&c,a<2048||a>=55296&&a<=57343?E+=i:(E+=o(a),e+=2))):240==(248&R)?e+3>=t?E+=i:(r=s[e+n+1],c=s[e+n+2],_=s[e+n+3],8421504!=(12632256&(r|c<<8|_<<16))?E+=i:(a=(7&R)<<18|(63&r)<<12|(63&c)<<6|63&_,a<65536||a>1114111?E+=i:(a-=65536,E+=o(55296+(a>>10),56320+(1023&a)),e+=3))):E+=i}return E}function ie(e,t){let n=t.length,o=0;for(let e=0;e<n;e++){let s=t.charCodeAt(e);s>=55296&&s<=56319&&e+1<n&&(s=(s<<10)+t.charCodeAt(++e)-56613888),o+=s<128?1:s<2048?2:s<65536?3:4}Ae(e,o);let s=ne(e,o),i=e.bytes;for(let e=0;e<n;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<n&&(o=(o<<10)+t.charCodeAt(++e)-56613888),o<128?i[s++]=o:(o<2048?i[s++]=o>>6&31|192:(o<65536?i[s++]=o>>12&15|224:(i[s++]=o>>18&7|240,i[s++]=o>>12&63|128),i[s++]=o>>6&63|128),i[s++]=63&o|128)}}function Ee(e,t){let n=ne(e,t.limit),o=e.bytes,s=t.bytes;for(let e=0,i=t.limit;e<i;e++)o[e+n]=s[e]}function re(e){return e.bytes[oe(e,1)]}function ce(e,t){let n=ne(e,1);e.bytes[n]=t}function _e(e){let t=oe(e,8),n=e.bytes;return X[0]=n[t++],X[1]=n[t++],X[2]=n[t++],X[3]=n[t++],X[4]=n[t++],X[5]=n[t++],X[6]=n[t++],X[7]=n[t++],j[0]}function ae(e,t){let n=ne(e,8),o=e.bytes;j[0]=t,o[n++]=X[0],o[n++]=X[1],o[n++]=X[2],o[n++]=X[3],o[n++]=X[4],o[n++]=X[5],o[n++]=X[6],o[n++]=X[7]}function Re(e){let t,n=0,o=0;do{t=re(e),n<32&&(o|=(127&t)<<n),n+=7}while(128&t);return o}function Ae(e,t){for(t>>>=0;t>=128;)ce(e,127&t|128),t>>>=7;ce(e,t)}function Ne(e,t){let n=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,s=t.high>>>24,i=0===s?0===o?n<16384?n<128?1:2:n<1<<21?3:4:o<16384?o<128?5:6:o<1<<21?7:8:s<128?9:10,E=ne(e,i),r=e.bytes;switch(i){case 10:r[E+9]=s>>>7&1;case 9:r[E+8]=9!==i?128|s:127&s;case 8:r[E+7]=8!==i?o>>>21|128:o>>>21&127;case 7:r[E+6]=7!==i?o>>>14|128:o>>>14&127;case 6:r[E+5]=6!==i?o>>>7|128:o>>>7&127;case 5:r[E+4]=5!==i?128|o:127&o;case 4:r[E+3]=4!==i?n>>>21|128:n>>>21&127;case 3:r[E+2]=3!==i?n>>>14|128:n>>>14&127;case 2:r[E+1]=2!==i?n>>>7|128:n>>>7&127;case 1:r[E]=1!==i?128|n:127&n}}let Ie=0,he=0;p.ACCESS_POINT,U.NO_FLAG_SET,U.FLAG_SET_BUT_EMPTY,U.INVALID_FALG_SET,U.FLAG_SET_BUT_NO_RE,U.INVALID_SERVICE_ID,U.NO_SERVICE_AVAILABLE,U.NO_SERVICE_AVAILABLE_P2P,U.NO_SERVICE_AVAILABLE_VOICE,U.NO_SERVICE_AVAILABLE_WEBRTC,U.NO_SERVICE_AVAILABLE_CDS,U.NO_SERVICE_AVAILABLE_CDN,U.NO_SERVICE_AVAILABLE_TDS,U.NO_SERVICE_AVAILABLE_REPORT,U.NO_SERVICE_AVAILABLE_APP_CENTER,U.NO_SERVICE_AVAILABLE_ENV0,U.NO_SERVICE_AVAILABLE_VOET,U.NO_SERVICE_AVAILABLE_STRING_UID,U.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,p.UNILBS,m.INVALID_VENDOR_KEY,m.INVALID_CHANNEL_NAME,m.INTERNAL_ERROR,m.NO_AUTHORIZED,m.DYNAMIC_KEY_TIMEOUT,m.NO_ACTIVE_STATUS,m.DYNAMIC_KEY_EXPIRED,m.STATIC_USE_DYNAMIC_KEY,m.DYNAMIC_USE_STATIC_KEY,m.USER_OVERLOAD,m.FORBIDDEN_REGION,m.CANNOT_MEET_AREA_DEMAND,m.REQ_DOWNGRADE_FALLBACK,p.STRING_UID_ALLOCATOR,V.IIIEGAL_APPID,V.IIIEGAL_UID,V.INTERNAL_ERROR,y.K_TIMESTAMP_EXPIRED,y.K_CHANNEL_PERMISSION_INVALID,y.K_CERTIFICATE_INVALID,y.K_CHANNEL_NAME_EMPTY,y.K_CHANNEL_NOT_FOUND,y.K_TICKET_INVALID,y.K_CHANNEL_CONFLICTED,y.K_SERVICE_NOT_READY,y.K_SERVICE_TOO_HEAVY,y.K_UID_BANNED,y.K_IP_BANNED,y.DATASTREAM2_NOT_AVAILABLE,y.K_AUTO_REBALANCE,y.K_VOS_FALLBACK,y.ERR_INVALID_VENDOR_KEY,y.ERR_INVALID_CHANNEL_NAME,y.WARN_NO_AVAILABLE_CHANNEL,y.WARN_LOOKUP_CHANNEL_TIMEOUT,y.WARN_LOOKUP_CHANNEL_REJECTED,y.WARN_OPEN_CHANNEL_TIMEOUT,y.WARN_OPEN_CHANNEL_REJECTED,y.WARN_REQUEST_DEFERRED,y.ERR_DYNAMIC_KEY_TIMEOUT,y.ERR_NO_AUTHORIZED,y.ERR_VOM_SERVICE_UNAVAILABLE,y.ERR_NO_CHANNEL_AVAILABLE_CODE,y.ERR_MASTER_VOCS_UNAVAILABLE,y.ERR_INTERNAL_ERROR,y.ERR_NO_ACTIVE_STATUS,y.ERR_INVALID_UID,y.ERR_DYNAMIC_KEY_EXPIRED,y.ERR_STATIC_USE_DYANMIC_KE,y.ERR_DYNAMIC_USE_STATIC_KE,y.ERR_NO_VOCS_AVAILABLE,y.ERR_NO_VOS_AVAILABLE,y.ERR_JOIN_CHANNEL_TIMEOUT,y.ERR_JOIN_BY_MULTI_IP,y.ERR_NOT_JOINED,y.ERR_REPEAT_JOIN_REQUEST,y.ERR_REPEAT_JOIN_CHANNEL,y.ERR_INVALID_STRINGUID,y.ERR_TOO_MANY_USERS,y.ERR_SET_CLIENT_ROLE_TIMEOUT,y.ERR_SET_CLIENT_ROLE_NO_PERMISSION,y.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,y.ERR_PUBLISH_REQUEST_INVALID,y.ERR_SUBSCRIBE_REQUEST_INVALID,y.ERR_NOT_SUPPORTED_MESSAGE,y.ERR_ILLEAGAL_PLUGIN,y.ILLEGAL_CLIENT_ROLE_LEVEL,y.ERR_REJOIN_TOKEN_INVALID,y.ERR_REJOIN_USER_NOT_JOINED,y.ERR_INVALID_OPTIONAL_INFO,y.ERR_TEST_RECOVER,y.ERR_TEST_TRYNEXT,y.ERR_TEST_RETRY,y.ILLEGAL_AES_PASSWORD,y.ERR_TOO_MANY_BROADCASTERS,y.ERR_TOO_MANY_SUBSCRIBERS,y.ERR_TOO_MANY_MESSAGES,y.ERR_LICENSE_ILLEGAL,y.ERR_LICENSE_MISSING,y.ERR_LICENSE_EXPIRED,y.ERR_LICENSE_MINUTES_EXCEEDED,y.ERR_LICENSE_PERIOD_INVALID,y.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const Ce={GLOBAL:{ASIA:[M.CHINA,M.JAPAN,M.INDIA,M.KOREA,M.HKMC],EUROPE:[],NORTH_AMERICA:[M.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(Ce[M.GLOBAL]),M.CHINA,M.NORTH_AMERICA,M.EUROPE,M.ASIA,M.JAPAN,M.INDIA,M.OCEANIA,M.SOUTH_AMERICA,M.AFRICA,M.KOREA,M.HKMC,M.US;let Oe=0;function Te(e,n,o,s){let i=n.appId,E=n.areaCode,r=n.cname,c=n.sid,a=n.token,R=n.uid;Oe++;const A="image_moderation_api",N={service_name:A,json_body:JSON.stringify({appId:i,areaCode:E,cname:r,command:"allocateEdge",requestId:Oe,seq:Oe,sid:c,token:a,ts:Date.now(),uid:R+""})};let O,T,u=e[0];return C((async()=>{O=Date.now();const e=await function(e,n,o,s){return new Promise(((i,E)=>{n.timeout=n.timeout||t("HTTP_CONNECT_TIMEOUT"),n.responseType=n.responseType||"json",n.data&&!o?(n.data=JSON.stringify(n.data),Ie+=I(n.data)):o&&(n.data.size?Ie+=n.data.size:n.data instanceof FormData?Ie+=h(n.data):Ie+=I(JSON.stringify(n.data))),n.headers=n.headers||{},n.headers["Content-Type"]=n.headers["Content-Type"]||"application/json",n.method="POST",n.url=e,D.request(n).then((e=>{"string"==typeof e.data?he+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?he+=e.data.byteLength:he+=I(JSON.stringify(e.data)),s&&i({data:e.data,headers:e.headers}),i(e.data)})).catch((e=>{D.isCancel(e)?E(new l(_.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?E(new l(_.NETWORK_TIMEOUT,e.message)):e.response?E(new l(_.NETWORK_RESPONSE_ERROR,e.response.status)):E(new l(_.NETWORK_ERROR,e.message))}))}))}(u,{data:N,cancelToken:o,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(T=Date.now()-O,0!==e.code){const t=new l(L.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:T});throw S.error(t.toString()),t}const n=JSON.parse(e.json_body);if(200!==n.code){const e=new l(L.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(n.code,", reason: ").concat(n.reason),{code:n.code,responseTime:T});throw S.error(e.toString()),e}if(!n.servers||!Array.isArray(n.servers)||0===n.servers.length){const e=new l(L.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:n.code,responseTime:T});throw S.error(e.toString()),e}const s=t("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(s)return{addressList:[s],workerToken:n.workerToken,vid:n.vid,responseTime:T};const i=t("VIDEO_INSPECT_WORKER_MANAGER_HOST"),E=t("VIDEO_INSPECT_WORKER_MANAGER_PORT"),r=n.servers.map((e=>{let t=e.address,n=e.wss;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(i,":").concat(E||n)})).filter((e=>!!e));return{addressList:r,workerToken:n.workerToken,vid:n.vid,responseTime:T}}),((t,n)=>(d.apworkerEvent(c,{success:!0,sc:200,serviceName:A,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:T,serverIp:e[n%e.length]}),!1)),((t,n)=>(d.apworkerEvent(c,{success:!1,sc:t.data&&t.data.code||200,serviceName:A,responseTime:T,serverIp:e[n%e.length]}),!!(t.code!==L.OPERATION_ABORTED&&t.code!==L.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(u=e[(n+1)%e.length],!0))),s)}const Se={},le={},Le=4294967296,de=Le*Le,ue=de/2,De=Ve(0,!0),we=Ve(0),fe=me(0,-2147483648,!1),ge=me(-1,2147483647,!1),pe=me(-1,-1,!0);function Ve(e,t){let n,o,s;return t?(s=0<=(e>>>=0)&&e<256)&&(o=le[e],o)?o:(n=me(e,0,!0),s&&(le[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(o=Se[e],o)?o:(n=me(e,e<0?-1:0,!1),s&&(Se[e]=n),n)}function me(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function Ue(e,t){if(isNaN(e))return t?De:we;if(t){if(e<0)return De;if(e>=de)return pe}else{if(e<=-ue)return fe;if(e+1>=ue)return ge}return e<0?t?De:we:me(e%Le|0,e/Le|0,t)}const ye=new Map([["moderation",1],["supervise",2]]);class be extends n{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(B.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>ye.get(e)||0)).reduce(((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),this.name="AgoraRTCVideoContentInspect",this._connectionState=k.CONNECTING,this._innerConnectionState=void 0,this.sequence=0,this.inspectStartTime=void 0,this.workerManagerConnection=void 0,this.workerConnection=void 0,this.workerMessageLengthLimit=void 0,this.inspectIntervalMinimum=void 0,this.qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=D.CancelToken.source(),this._retryConfig=void 0,this.wmSequence=0,this.inspectInterval=void 0,this.inspectTimer=null,this.ossFilePrefix=void 0,this.extraInfo=void 0,this._inspectType=void 0,this._inspectMode=void 0,this._quality=1,this.qualityTimer=null,this._inspectId=void 0,this._needWorkUrlOnly=!1,this.inspectImage=()=>{if(this.connectionState!==k.CONNECTED)throw new l(L.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===k.CONNECTED?this.requestToInspectImage():S.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()},this._inspectId=O(5,"inspect-"),this.workerMessageLengthLimit=t("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=t("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=t("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new K("worker-manager-"+this._inspectId,T),this.on(B.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,S.debug("[".concat(this._inspectId,"] Inspect operation :").concat(v[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new K("worker-"+this._inspectId,T),this.handleWorkerEvents()}async init(e,t){this.emit(B.STATE_CHANGE,v.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((o,s)=>{this.on(B.CONNECTION_STATE_CHANGE,((e,t)=>{t===k.CONNECTED&&o()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{s(e)}))}))}async requestAP(e,n,o){const s=t("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),i=await Te(s,e,n,o);this.emit(B.STATE_CHANGE,v.AP_CONNECTED);const E=i.addressList;return this.wmSequence++,E}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(B.STATE_CHANGE,v.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(b.CONNECTED,(async()=>{this.emit(B.STATE_CHANGE,v.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.8",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(b.CLOSED,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(b.FAILED,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(b.RECONNECTING,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(b.ON_MESSAGE,(async e=>{this.emit(B.STATE_CHANGE,v.GET_WORKER_MANAGER_RESPONSE);const n=this.workerManagerConnection.url;this.workerManagerConnection.close();const o=JSON.parse(e.data);if(200!==o.code)throw S.error("[".concat(this._inspectId,"] Unexpected code ").concat(o.code," from worker manager")),new l(L.UNEXPECTED_RESPONSE,"response code of worker is unexpected",o);if(!(o.serverResponse&&o.serverResponse.portWss&&n))throw S.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(o))),new l(L.UNEXPECTED_RESPONSE,"response content of worker is unexpected",o);{const e=t("VIDEO_INSPECT_WORKER_PORT")||o.serverResponse.portWss,s=n.replace(/:\d+\/?$/,":".concat(e));this.emit(B.STATE_CHANGE,v.CONNECT_WORKER,s),this._needWorkUrlOnly?this.emit(B.REQUEST_NEW_WORKER_URL,s):await this.connectWorker(s)}})),this.workerManagerConnection.on(b.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(b.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(b.CONNECTED,(async()=>{this.emit(B.STATE_CHANGE,v.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=k.CONNECTED})),this.workerConnection.on(b.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const n=H(new Uint8Array(e.data));if(t("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&S.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(n)),200===n.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(B.INSPECT_RESULT,void 0,void 0);if(n.data&&n.data.scorePorn&&n.data.scoreSexy&&n.data.scoreNeutral){const e={porn:n.data.scorePorn,sexy:n.data.scoreSexy,neutral:n.data.scoreNeutral},t=Object.keys(e).reduce(((t,n)=>e[t]>e[n]?t:n),"porn"),o=Object.keys(e).find((e=>e===t));this.emit(B.INSPECT_RESULT,o)}else this.emit(B.INSPECT_RESULT,void 0,new l(L.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(B.INSPECT_RESULT,void 0,new l(L.UNEXPECTED_RESPONSE,n.code+"",n.msg))}else S.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(B.INSPECT_RESULT,void 0,new l(L.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(b.CLOSED,(()=>{this.connectionState=k.CLOSED})),this.workerConnection.on(b.FAILED,(()=>{this.connectionState=k.CLOSED})),this.workerConnection.on(b.RECONNECTING,(()=>{this.connectionState=this.connectionState===k.CONNECTED?k.RECONNECTING:k.CONNECTING})),this.workerConnection.on(b.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(b.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(B.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=N(this,B.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(B.INSPECT_RESULT,void 0,new l(L.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(B.INSPECT_RESULT,void 0,new l(L.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,n){let o=n.appId,s=n.cname,i=n.cid,E=n.vid,r=n.sid,c=n.uid;const _=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await u(a,o,s),A=this.sequence+"-"+i+"-"+c+"-"+_+"-"+O(12,""),N={appId:o,cid:i,cname:s,deviceId:"",elapse:(I=Number(_-this.inspectStartTime),{low:I|=0,high:I>>31,unsigned:I>=0}),fileSize:R.byteLength,jpgEncryption:2,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:A,sdkVersion:"4.24.8",sequence:this.sequence,sid:r,timestamp:Ue(_),uid:c,vid:E,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var I;void 0===this.extraInfo&&delete N.callbackData,void 0===this.ossFilePrefix&&delete N.ossFilePrefix;const h=G(N);if(h.byteLength<this.workerMessageLengthLimit){if(t("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=g({},N);delete e.jpg,S.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return h}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:o,cname:s,cid:i,vid:E,sid:r,uid:c})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=D.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=k.CLOSED,this.emit(B.STATE_CHANGE,v.CLOSED)}}function Me(e){if(!e)throw new l(L.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new l(L.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{if(!["supervise","moderation"].includes(e))throw new l(L.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new l(L.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}const Pe={name:"ContentInspect",create:function(e){let t=e.config;return Me(t),new be(t)}};export{Pe as ContentInspectService,Me as checkContentInspectConfig};