UNPKG

agora-rtc-sdk-ng

Version:
6 lines (4 loc) 44 kB
/** * AgoraWebSDK_N-v4.24.3-0-g6cc16b0bb-dirty Copyright AgoraInc. */ import{IS_GLOBAL_VERSION as e,getParameter as t,EventEmitter as n,PromiseMutex as o,NETWORK_STATE as E,networkIndicator as s,NETWORK_INDICATOR_EVENTS as i,createDefer as r,AgoraRTCError as _,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as R,emitAsPromise as N,emitAsInvokerNoResponse as A,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as C,retryable as O,getRandomString as T,DEFAULT_RETRY_CONFIG as h}from"@agora-js/shared";import{logger as S,AgoraRTCError as L,AgoraRTCErrorCode as l,report as d}from"@agora-js/report";import{detectSupportPrePc as u,frameData2CryptoBuffer as D}from"@agora-js/media";import"@agora-js/protocol";import f 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 p(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?p(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):p(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let m=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}({}),U=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}({}),P=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_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.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 k=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}({});k.ASIA,k.NORTH_AMERICA,k.EUROPE,k.JAPAN,k.INDIA,k.KOREA,k.HKMC,k.US,k.OVERSEA,k.GLOBAL,k.OCEANIA,k.SOUTH_AMERICA,k.AFRICA,e&&k.CHINA;let v=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),B=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}({}),K=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}({}),W=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({});class G extends n{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}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],_=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=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.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=c,this.name=e,this.retryConfig=g({},t),this.useCompress=n,this.tryDoubleDomain=r,this.use443PortOnly=_,this._initMutex=new o("websocket",c?c.clientId:void 0);const{timeout:a,timeoutFactor:R}=t,N=Math.max(300,Math.floor(3*a/5)),A=Math.max(1.2,Math.floor(8*R)/10);E.ONLINE&&(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=A),s.on(i.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=A):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const o=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=n,this.urls=e,this.state="connecting";try{var E;const e=r(),n=this.urls[this.currentURLIndex];null===(E=this.store)||void 0===E||E.beforeConnect(),(u(this.store)||t("ENABLE_JOIN_V4"))&&this.emit(W.PRE_CONNECT_PC),this.createWebSocketConnection(n).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 E=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()},s=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{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=A(this,b.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void S.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return o.reject(new _(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);o.resolve()}},i=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 N;this._websocketUrl=function(e,n){if("string"==typeof e)return e;const{proxy:o,host:E,port:s}=e;if(n){const e=t("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(E,"/ws/?p=").concat(Number(s)+150):"wss://".concat(E,":").concat(e,"/ws/?p=").concat(Number(s)+150)}return o?"wss://".concat(o,"/ws/?h=").concat(E,"&p=").concat(s):"wss://".concat(E,":").concat(s)}(e);const n=await this.chooseBestWebsocketConnection(e);this.websocket=n,E&&E(this.websocket.url),this.websocket.onclose=s,this.websocket.onmessage=i,this.websocket.onerror=a,null===(N=this.store)||void 0===N||N.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(e){const t="closed"===this.state,n=e instanceof _,E=n&&e.code===c.WS_ABORT,i=n&&e.code===c.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:E?"aborted":"error",errors:[e]},R),t||i?(o.reject(t?new _(c.WS_DISCONNECT,"websocket is closed: ".concat(r)):new _(c.WS_ERR,"init websocket failed: ".concat(r))),i&&S.error("[".concat(this.name,"] init websocket failed: ").concat(r))):s&&s(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||s.isOnline||!s.onlineWaiter||(this.onlineReconnectListener=s.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 N(this,b.REQUEST_NEW_URLS),this.currentURLIndex=0,await o(this.urls[this.currentURLIndex],e))}catch(n){var E;S.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const o=null==n||null===(E=n.data)||void 0===E?void 0:E.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 H extends G{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,E)=>{let s=!1;const i=[];this.closeEstablishingWs=()=>{S.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new _(c.WS_ABORT,"choose best websocket aborted"))};const r=t("GATEWAY_DOMAINS");let a;const N=e.indexOf("?h="),A=r.find((t=>-1!==N?e.includes(t,N):e.includes(t)));S.debug("[choose-best-ws] currentDomain: ",A,", domains: ",r);let I=!this.tryDoubleDomain||!A;if(!I&&A){var C;const t=Date.now();try{r.forEach((t=>{const n=-1===N?e.replace(A,t):e.substr(0,N)+e.substr(N).replace(A,t),o=new WebSocket(n);o.binaryType="arraybuffer",i.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"),i.forEach((e=>e.close()));i.length;)i.pop();I=!0}null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},n),i.forEach((e=>{e.onopen=()=>{if(s)return;const n=Date.now()-t;S.debug("[choose-best-ws] ws open cost ".concat(n,"ms")),i.filter((t=>t!==e)).forEach((e=>{S.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),s=!0,o(e)},e.onclose=e=>{if(a=e,s)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(S.debug("[choose-best-ws] all websocket is closed"),s=!0,E(a))},e.onmessage=t=>{S.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),R(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var O;let t;S.debug("[choose-best-ws] use single url: ",e),null===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:[e],service:"gateway"},n);try{t=new WebSocket(e),i.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 E(t)}t.onopen=()=>{o(t)},t.onclose=e=>{E(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 Y(e){let t=ee();return function(e,t){let n=e.appId;void 0!==n&&(Ie(t,10),re(t,n));let o=e.cid;void 0!==o&&(Ie(t,16),Ie(t,o));let E=e.cname;void 0!==E&&(Ie(t,26),re(t,E));let s=e.deviceId;void 0!==s&&(Ie(t,34),re(t,s));let i=e.elapse;void 0!==i&&(Ie(t,40),Ce(t,i));let r=e.fileSize;void 0!==r&&(Ie(t,48),Ce(t,z(r)));let _=e.height;void 0!==_&&(Ie(t,56),Ce(t,z(_)));let c=e.jpg;void 0!==c&&(Ie(t,66),Ie(t,c.length),function(e,t){let n=Ee(e,t.length);e.bytes.set(t,n)}(t,c));let a=e.networkType;void 0!==a&&(Ie(t,72),Ce(t,z(a)));let R=e.osType;void 0!==R&&(Ie(t,80),Ce(t,z(R)));let N=e.requestId;void 0!==N&&(Ie(t,90),re(t,N));let A=e.sdkVersion;void 0!==A&&(Ie(t,98),re(t,A));let I=e.sequence;void 0!==I&&(Ie(t,104),Ce(t,z(I)));let C=e.sid;void 0!==C&&(Ie(t,114),re(t,C));let O=e.timestamp;void 0!==O&&(Ie(t,120),Ce(t,O));let T=e.uid;void 0!==T&&(Ie(t,128),Ie(t,T));let h=e.vid;void 0!==h&&(Ie(t,136),Ie(t,h));let S=e.width;void 0!==S&&(Ie(t,144),Ce(t,z(S)));let L=e.service;void 0!==L&&(Ie(t,152),Ie(t,L));let l=e.callbackData;void 0!==l&&(Ie(t,162),re(t,l));let d=e.jpgEncryption;void 0!==d&&(Ie(t,168),Ie(t,d));let u=e.requestType;void 0!==u&&(Ie(t,176),Ie(t,u));let D=e.scorePorn;void 0!==D&&(Ie(t,185),Ne(t,D));let f=e.scoreSexy;void 0!==f&&(Ie(t,193),Ne(t,f));let w=e.scoreNeutral;void 0!==w&&(Ie(t,201),Ne(t,w));let p=e.scene;void 0!==p&&(Ie(t,208),Ie(t,p));let g=e.ossFilePrefix;void 0!==g&&(Ie(t,218),re(t,g));let m=e.serviceVendor;if(void 0!==m)for(let e of m){Ie(t,226);let n=ee();q(e,n),Ie(t,n.limit),_e(t,n),te(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function F(e){return function(e){let t={};e:for(;!oe(e);){let n=Ae(e);switch(n>>>3){case 0:break e;case 1:t.code=Ae(e);break;case 2:t.msg=ie(e,Ae(e));break;case 3:{let n=J(e);t.data=x(e),e.limit=n;break}default:j(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function x(e){let t={};e:for(;!oe(e);){let n=Ae(e);switch(n>>>3){case 0:break e;case 1:t.requestId=ie(e,Ae(e));break;case 2:t.requestType=Ae(e)>>>0;break;case 3:t.scorePorn=Re(e);break;case 4:t.scoreSexy=Re(e);break;case 5:t.scoreNeutral=Re(e);break;case 6:t.requestScene=Ae(e)>>>0;break;case 7:t.scene=Ae(e)>>>0;break;default:j(e,7&n)}}return t}function q(e,t){let n=e.service;void 0!==n&&(Ie(t,8),Ie(t,n));let o=e.vendor;void 0!==o&&(Ie(t,16),Ie(t,o));let E=e.token;void 0!==E&&(Ie(t,26),re(t,E));let s=e.callbackUrl;void 0!==s&&(Ie(t,34),re(t,s))}function J(e){let t=Ae(e),n=e.limit;return e.limit=e.offset+t,n}function j(e,t){switch(t){case 0:for(;128&ce(e););break;case 2:ne(e,Ae(e));break;case 5:ne(e,4);break;case 1:ne(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let X=new Float32Array(1);new Uint8Array(X.buffer);let Q=new Float64Array(1),Z=new Uint8Array(Q.buffer);function z(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let $=[];function ee(){const e=$.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function te(e){$.push(e)}function ne(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function oe(e){return e.offset>=e.limit}function Ee(e,t){let n=e.bytes,o=e.offset,E=e.limit,s=o+t;if(s>n.length){let t=new Uint8Array(2*s);t.set(n),e.bytes=t}return e.offset=s,s>E&&(e.limit=s),o}function se(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ie(e,t){let n=se(e,t),o=String.fromCharCode,E=e.bytes,s="�",i="";for(let e=0;e<t;e++){let r,_,c,a,R=E[e+n];0==(128&R)?i+=o(R):192==(224&R)?e+1>=t?i+=s:(r=E[e+n+1],128!=(192&r)?i+=s:(a=(31&R)<<6|63&r,a<128?i+=s:(i+=o(a),e++))):224==(240&R)?e+2>=t?i+=s:(r=E[e+n+1],_=E[e+n+2],32896!=(49344&(r|_<<8))?i+=s:(a=(15&R)<<12|(63&r)<<6|63&_,a<2048||a>=55296&&a<=57343?i+=s:(i+=o(a),e+=2))):240==(248&R)?e+3>=t?i+=s:(r=E[e+n+1],_=E[e+n+2],c=E[e+n+3],8421504!=(12632256&(r|_<<8|c<<16))?i+=s:(a=(7&R)<<18|(63&r)<<12|(63&_)<<6|63&c,a<65536||a>1114111?i+=s:(a-=65536,i+=o(55296+(a>>10),56320+(1023&a)),e+=3))):i+=s}return i}function re(e,t){let n=t.length,o=0;for(let e=0;e<n;e++){let E=t.charCodeAt(e);E>=55296&&E<=56319&&e+1<n&&(E=(E<<10)+t.charCodeAt(++e)-56613888),o+=E<128?1:E<2048?2:E<65536?3:4}Ie(e,o);let E=Ee(e,o),s=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?s[E++]=o:(o<2048?s[E++]=o>>6&31|192:(o<65536?s[E++]=o>>12&15|224:(s[E++]=o>>18&7|240,s[E++]=o>>12&63|128),s[E++]=o>>6&63|128),s[E++]=63&o|128)}}function _e(e,t){let n=Ee(e,t.limit),o=e.bytes,E=t.bytes;for(let e=0,s=t.limit;e<s;e++)o[e+n]=E[e]}function ce(e){return e.bytes[se(e,1)]}function ae(e,t){let n=Ee(e,1);e.bytes[n]=t}function Re(e){let t=se(e,8),n=e.bytes;return Z[0]=n[t++],Z[1]=n[t++],Z[2]=n[t++],Z[3]=n[t++],Z[4]=n[t++],Z[5]=n[t++],Z[6]=n[t++],Z[7]=n[t++],Q[0]}function Ne(e,t){let n=Ee(e,8),o=e.bytes;Q[0]=t,o[n++]=Z[0],o[n++]=Z[1],o[n++]=Z[2],o[n++]=Z[3],o[n++]=Z[4],o[n++]=Z[5],o[n++]=Z[6],o[n++]=Z[7]}function Ae(e){let t,n=0,o=0;do{t=ce(e),n<32&&(o|=(127&t)<<n),n+=7}while(128&t);return o}function Ie(e,t){for(t>>>=0;t>=128;)ae(e,127&t|128),t>>>=7;ae(e,t)}function Ce(e,t){let n=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,E=t.high>>>24,s=0===E?0===o?n<16384?n<128?1:2:n<1<<21?3:4:o<16384?o<128?5:6:o<1<<21?7:8:E<128?9:10,i=Ee(e,s),r=e.bytes;switch(s){case 10:r[i+9]=E>>>7&1;case 9:r[i+8]=9!==s?128|E:127&E;case 8:r[i+7]=8!==s?o>>>21|128:o>>>21&127;case 7:r[i+6]=7!==s?o>>>14|128:o>>>14&127;case 6:r[i+5]=6!==s?o>>>7|128:o>>>7&127;case 5:r[i+4]=5!==s?128|o:127&o;case 4:r[i+3]=4!==s?n>>>21|128:n>>>21&127;case 3:r[i+2]=3!==s?n>>>14|128:n>>>14&127;case 2:r[i+1]=2!==s?n>>>7|128:n>>>7&127;case 1:r[i]=1!==s?128|n:127&n}}let Oe=0,Te=0;m.ACCESS_POINT,P.NO_FLAG_SET,P.FLAG_SET_BUT_EMPTY,P.INVALID_FALG_SET,P.FLAG_SET_BUT_NO_RE,P.INVALID_SERVICE_ID,P.NO_SERVICE_AVAILABLE,P.NO_SERVICE_AVAILABLE_P2P,P.NO_SERVICE_AVAILABLE_VOICE,P.NO_SERVICE_AVAILABLE_WEBRTC,P.NO_SERVICE_AVAILABLE_CDS,P.NO_SERVICE_AVAILABLE_CDN,P.NO_SERVICE_AVAILABLE_TDS,P.NO_SERVICE_AVAILABLE_REPORT,P.NO_SERVICE_AVAILABLE_APP_CENTER,P.NO_SERVICE_AVAILABLE_ENV0,P.NO_SERVICE_AVAILABLE_VOET,P.NO_SERVICE_AVAILABLE_STRING_UID,P.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,m.UNILBS,U.INVALID_VENDOR_KEY,U.INVALID_CHANNEL_NAME,U.INTERNAL_ERROR,U.NO_AUTHORIZED,U.DYNAMIC_KEY_TIMEOUT,U.NO_ACTIVE_STATUS,U.DYNAMIC_KEY_EXPIRED,U.STATIC_USE_DYNAMIC_KEY,U.DYNAMIC_USE_STATIC_KEY,U.USER_OVERLOAD,U.FORBIDDEN_REGION,U.CANNOT_MEET_AREA_DEMAND,U.REQ_DOWNGRADE_FALLBACK,m.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_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 he={GLOBAL:{ASIA:[M.CHINA,M.JAPAN,M.INDIA,M.KOREA,M.HKMC],EUROPE:[],NORTH_AMERICA:[M.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(he[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 Se=0;function Le(e,n,o,E){let{appId:s,areaCode:i,cname:r,sid:_,token:a,uid:R}=n;Se++;const N="image_moderation_api",A={service_name:N,json_body:JSON.stringify({appId:s,areaCode:i,cname:r,command:"allocateEdge",requestId:Se,seq:Se,sid:_,token:a,ts:Date.now(),uid:R+""})};let T,h,u=e[0];return O((async()=>{T=Date.now();const e=await function(e,n,o,E){return new Promise(((s,i)=>{n.timeout=n.timeout||t("HTTP_CONNECT_TIMEOUT"),n.responseType=n.responseType||"json",n.data&&!o?(n.data=JSON.stringify(n.data),Oe+=I(n.data)):o&&(n.data.size?Oe+=n.data.size:n.data instanceof FormData?Oe+=C(n.data):Oe+=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,f.request(n).then((e=>{"string"==typeof e.data?Te+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Te+=e.data.byteLength:Te+=I(JSON.stringify(e.data)),E&&s({data:e.data,headers:e.headers}),s(e.data)})).catch((e=>{f.isCancel(e)?i(new L(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new L(c.NETWORK_TIMEOUT,e.message)):e.response?i(new L(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new L(c.NETWORK_ERROR,e.message))}))}))}(u,{data:A,cancelToken:o,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-T,0!==e.code){const t=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:h});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:h});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:h});throw S.error(e.toString()),e}const E=t("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(E)return{addressList:[E],workerToken:n.workerToken,vid:n.vid,responseTime:h};const s=t("VIDEO_INSPECT_WORKER_MANAGER_HOST"),i=t("VIDEO_INSPECT_WORKER_MANAGER_PORT"),r=n.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(s,":").concat(i||n)})).filter((e=>!!e));return{addressList:r,workerToken:n.workerToken,vid:n.vid,responseTime:h}}),((t,n)=>(d.apworkerEvent(_,{success:!0,sc:200,serviceName:N,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(d.apworkerEvent(_,{success:!1,sc:t.data&&t.data.code||200,serviceName:N,responseTime:h,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))),E)}const le={},de={},ue=4294967296,De=ue*ue,fe=De/2,we=Ue(0,!0),pe=Ue(0),ge=Pe(0,-2147483648,!1),me=Pe(-1,2147483647,!1),Ve=Pe(-1,-1,!0);function Ue(e,t){let n,o,E;return t?(E=0<=(e>>>=0)&&e<256)&&(o=de[e],o)?o:(n=Pe(e,0,!0),E&&(de[e]=n),n):(E=-128<=(e|=0)&&e<128)&&(o=le[e],o)?o:(n=Pe(e,e<0?-1:0,!1),E&&(le[e]=n),n)}function Pe(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function ye(e,t){if(isNaN(e))return t?we:pe;if(t){if(e<0)return we;if(e>=De)return Ve}else{if(e<=-fe)return ge;if(e+1>=fe)return me}return e<0?t?we:pe:Pe(e%ue|0,e/ue|0,t)}const be=new Map([["moderation",1],["supervise",2]]);class Me extends n{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(K.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>be.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=v.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=f.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!==v.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===v.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=T(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 H("worker-manager-"+this._inspectId,h),this.on(K.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,S.debug("[".concat(this._inspectId,"] Inspect operation :").concat(B[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new H("worker-"+this._inspectId,h),this.handleWorkerEvents()}async init(e,t){this.emit(K.STATE_CHANGE,B.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((o,E)=>{this.on(K.CONNECTION_STATE_CHANGE,((e,t)=>{t===v.CONNECTED&&o()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{E(e)}))}))}async requestAP(e,n,o){const E=t("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),s=await Le(E,e,n,o);this.emit(K.STATE_CHANGE,B.AP_CONNECTED);const{addressList:i}=s;return this.wmSequence++,i}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(K.STATE_CHANGE,B.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(K.STATE_CHANGE,B.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.3",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<B.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(b.FAILED,(()=>{this._innerConnectionState<B.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<B.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(K.STATE_CHANGE,B.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,E=n.replace(/:\d+\/?$/,":".concat(e));this.emit(K.STATE_CHANGE,B.CONNECT_WORKER,E),this._needWorkUrlOnly?this.emit(K.REQUEST_NEW_WORKER_URL,E):await this.connectWorker(E)}})),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(K.STATE_CHANGE,B.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=v.CONNECTED})),this.workerConnection.on(b.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const n=F(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(K.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(K.INSPECT_RESULT,o)}else this.emit(K.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(K.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(K.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(b.CLOSED,(()=>{this.connectionState=v.CLOSED})),this.workerConnection.on(b.FAILED,(()=>{this.connectionState=v.CLOSED})),this.workerConnection.on(b.RECONNECTING,(()=>{this.connectionState=this.connectionState===v.CONNECTED?v.RECONNECTING:v.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(K.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=A(this,K.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(K.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(K.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,n){let{appId:o,cname:E,cid:s,vid:i,sid:r,uid:_}=n;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await D(a,o,E),N=this.sequence+"-"+s+"-"+_+"-"+c+"-"+T(12,""),A={appId:o,cid:s,cname:E,deviceId:"",elapse:(I=Number(c-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:N,sdkVersion:"4.24.3",sequence:this.sequence,sid:r,timestamp:ye(c),uid:_,vid:i,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var I;void 0===this.extraInfo&&delete A.callbackData,void 0===this.ossFilePrefix&&delete A.ossFilePrefix;const C=Y(A);if(C.byteLength<this.workerMessageLengthLimit){if(t("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=g({},A);delete e.jpg,S.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return C}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:o,cname:E,cid:s,vid:i,sid:r,uid:_})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=f.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=v.CLOSED,this.emit(K.STATE_CHANGE,B.CLOSED)}}function ke(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 ve={name:"ContentInspect",create:function(e){let{config:t}=e;return ke(t),new Me(t)}};export{ve as ContentInspectService,ke as checkContentInspectConfig};