jiuyiUniapp/jiuyi2/node_modules/agora-rtc-sdk-ng/services/content-inspect/index.js

6 lines
42 KiB
JavaScript
Raw Blame History

/**
* AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc.
*/
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as s,createDefer as i,getParameter as r,AgoraRTCError as _,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as N,emitAsPromise as R,emitAsInvokerNoResponse as I,getUTF8StringByteLength as A,getMultiUnilbsFormDataByteLength as C,retryable as T,getRandomString as O,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{frameData2CryptoBuffer as u}from"@agora-js/media";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 E=n.call(e,t||"default");if("object"!=typeof E)return E;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 E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function p(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 g=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}({}),m=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}({}),V=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}({}),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}({}),U=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.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",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}({}),y=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_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",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 b=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}({});b.ASIA,b.NORTH_AMERICA,b.EUROPE,b.JAPAN,b.INDIA,b.KOREA,b.HKMC,b.US,b.OVERSEA,b.GLOBAL,b.OCEANIA,b.SOUTH_AMERICA,b.AFRICA,e&&b.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}({}),W=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}({}),B=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_WAITTING_FINISH="transmitter:reconnect_waitting_finish",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 K extends t{get url(){return this.websocket&&this.websocket.url||null}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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){S.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=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.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=new n("websocket"),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=p({},t),this.useCompress=i,this.tryDoubleDomain=r,this.use443PortOnly=_;const{timeout:a,timeoutFactor:N}=t,R=Math.max(300,Math.floor(3*a/5)),I=Math.max(1.2,Math.floor(8*N)/10);E.ONLINE&&(this.retryConfig.timeout=R,this.retryConfig.timeoutFactor=I),o.on(s.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=R,this.retryConfig.timeoutFactor=I):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=N))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=i(),t=this.urls[this.currentURLIndex];r("ENABLE_PREALLOC_PC")&&this.emit(B.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new _(c.WS_DISCONNECT))})),this.once(y.CONNECTED,e.resolve),await e.promise}catch(e){}finally{n()}}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.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 t;const n=i();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"),n.resolve()},o=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)n.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=I(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void S.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new _(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},s=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{S.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),r("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=r("GATEWAY_WSS_ADDRESS")),S.debug("[".concat(this.name,"] start connect, url:"),e);const N=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var R;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=s,this.websocket.onerror=a,null===(R=this.store)||void 0===R||R.recordJoinChannelService({endTs:Date.now(),status:"success"},N),this.joinGatewayRecordIndex=N}catch(e){const t="closed"===this.state,E=e instanceof _,s=E&&e.code===c.WS_ABORT,i=E&&e.code===c.WS_ERR,r=E?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]},N),t||i?(n.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))):o&&o(e)}return n.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||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.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([N(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(y.RECONNECT_WAITTING_FINISH,e),await E(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)),this.emit(y.RECONNECT_WAITTING_FINISH,e),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(S.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(y.RECONNECT_WAITTING_FINISH,e),this.urls=await R(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var s;S.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(s=n.data)||void 0===s?void 0:s.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class G extends K{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,t){return new Promise(((n,E)=>{let o=!1;const s=[];this.closeEstablishingWs=()=>{S.debug("[choose-best-ws] close establishing websockets"),s.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new _(c.WS_ABORT,"choose best websocket aborted"))};const i=r("GATEWAY_DOMAINS");let a;const R=e.indexOf("?h="),I=i.find((t=>-1!==R?e.includes(t,R):e.includes(t)));S.debug("[choose-best-ws] currentDomain: ",I,", domains: ",i);let A=!this.tryDoubleDomain||!I;if(!A&&I){var C;const r=Date.now();try{i.forEach((t=>{const n=-1===R?e.replace(I,t):e.substr(0,R)+e.substr(R).replace(I,t),E=new WebSocket(n);E.binaryType="arraybuffer",s.push(E),S.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(S.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach((e=>e.close()));s.length;)s.pop();A=!0}null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},t),s.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-r;S.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter((t=>t!==e)).forEach((e=>{S.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;s.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(S.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{S.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),N(this.forceCloseTimeout).then((()=>{s.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var T;let o;S.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),s.push(o),o.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)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{S.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},N(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function H(e){let t=$();return function(e,t){let n=e.appId;void 0!==n&&(Ie(t,10),ie(t,n));let E=e.cid;void 0!==E&&(Ie(t,16),Ie(t,E));let o=e.cname;void 0!==o&&(Ie(t,26),ie(t,o));let s=e.deviceId;void 0!==s&&(Ie(t,34),ie(t,s));let i=e.elapse;void 0!==i&&(Ie(t,40),Ae(t,i));let r=e.fileSize;void 0!==r&&(Ie(t,48),Ae(t,Z(r)));let _=e.height;void 0!==_&&(Ie(t,56),Ae(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),Ae(t,Z(a)));let N=e.osType;void 0!==N&&(Ie(t,80),Ae(t,Z(N)));let R=e.requestId;void 0!==R&&(Ie(t,90),ie(t,R));let I=e.sdkVersion;void 0!==I&&(Ie(t,98),ie(t,I));let A=e.sequence;void 0!==A&&(Ie(t,104),Ae(t,Z(A)));let C=e.sid;void 0!==C&&(Ie(t,114),ie(t,C));let T=e.timestamp;void 0!==T&&(Ie(t,120),Ae(t,T));let O=e.uid;void 0!==O&&(Ie(t,128),Ie(t,O));let h=e.vid;void 0!==h&&(Ie(t,136),Ie(t,h));let S=e.width;void 0!==S&&(Ie(t,144),Ae(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),ie(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 w=e.scoreSexy;void 0!==w&&(Ie(t,193),Ne(t,w));let f=e.scoreNeutral;void 0!==f&&(Ie(t,201),Ne(t,f));let p=e.scene;void 0!==p&&(Ie(t,208),Ie(t,p));let g=e.ossFilePrefix;void 0!==g&&(Ie(t,218),ie(t,g));let m=e.serviceVendor;if(void 0!==m)for(let e of m){Ie(t,226);let n=$();x(e,n),Ie(t,n.limit),re(t,n),ee(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function Y(e){return function(e){let t={};e:for(;!ne(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=q(e);t.data=F(e),e.limit=n;break}default:J(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function F(e){let t={};e:for(;!ne(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=ae(e);break;case 4:t.scoreSexy=ae(e);break;case 5:t.scoreNeutral=ae(e);break;case 6:t.requestScene=Re(e)>>>0;break;case 7:t.scene=Re(e)>>>0;break;default:J(e,7&n)}}return t}function x(e,t){let n=e.service;void 0!==n&&(Ie(t,8),Ie(t,n));let E=e.vendor;void 0!==E&&(Ie(t,16),Ie(t,E));let o=e.token;void 0!==o&&(Ie(t,26),ie(t,o));let s=e.callbackUrl;void 0!==s&&(Ie(t,34),ie(t,s))}function q(e){let t=Re(e),n=e.limit;return e.limit=e.offset+t,n}function J(e,t){switch(t){case 0:for(;128&_e(e););break;case 2:te(e,Re(e));break;case 5:te(e,4);break;case 1:te(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let j=new Float32Array(1);new Uint8Array(j.buffer);let X=new Float64Array(1),Q=new Uint8Array(X.buffer);function Z(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let z=[];function $(){const e=z.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function ee(e){z.push(e)}function te(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ne(e){return e.offset>=e.limit}function Ee(e,t){let n=e.bytes,E=e.offset,o=e.limit,s=E+t;if(s>n.length){let t=new Uint8Array(2*s);t.set(n),e.bytes=t}return e.offset=s,s>o&&(e.limit=s),E}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),E=String.fromCharCode,o=e.bytes,s="<22>",i="";for(let e=0;e<t;e++){let r,_,c,a,N=o[e+n];0==(128&N)?i+=E(N):192==(224&N)?e+1>=t?i+=s:(r=o[e+n+1],128!=(192&r)?i+=s:(a=(31&N)<<6|63&r,a<128?i+=s:(i+=E(a),e++))):224==(240&N)?e+2>=t?i+=s:(r=o[e+n+1],_=o[e+n+2],32896!=(49344&(r|_<<8))?i+=s:(a=(15&N)<<12|(63&r)<<6|63&_,a<2048||a>=55296&&a<=57343?i+=s:(i+=E(a),e+=2))):240==(248&N)?e+3>=t?i+=s:(r=o[e+n+1],_=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(r|_<<8|c<<16))?i+=s:(a=(7&N)<<18|(63&r)<<12|(63&_)<<6|63&c,a<65536||a>1114111?i+=s:(a-=65536,i+=E(55296+(a>>10),56320+(1023&a)),e+=3))):i+=s}return i}function ie(e,t){let n=t.length,E=0;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),E+=o<128?1:o<2048?2:o<65536?3:4}Ie(e,E);let o=Ee(e,E),s=e.bytes;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),E<128?s[o++]=E:(E<2048?s[o++]=E>>6&31|192:(E<65536?s[o++]=E>>12&15|224:(s[o++]=E>>18&7|240,s[o++]=E>>12&63|128),s[o++]=E>>6&63|128),s[o++]=63&E|128)}}function re(e,t){let n=Ee(e,t.limit),E=e.bytes,o=t.bytes;for(let e=0,s=t.limit;e<s;e++)E[e+n]=o[e]}function _e(e){return e.bytes[oe(e,1)]}function ce(e,t){let n=Ee(e,1);e.bytes[n]=t}function ae(e){let t=oe(e,8),n=e.bytes;return Q[0]=n[t++],Q[1]=n[t++],Q[2]=n[t++],Q[3]=n[t++],Q[4]=n[t++],Q[5]=n[t++],Q[6]=n[t++],Q[7]=n[t++],X[0]}function Ne(e,t){let n=Ee(e,8),E=e.bytes;X[0]=t,E[n++]=Q[0],E[n++]=Q[1],E[n++]=Q[2],E[n++]=Q[3],E[n++]=Q[4],E[n++]=Q[5],E[n++]=Q[6],E[n++]=Q[7]}function Re(e){let t,n=0,E=0;do{t=_e(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function Ie(e,t){for(t>>>=0;t>=128;)ce(e,127&t|128),t>>>=7;ce(e,t)}function Ae(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,s=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,i=Ee(e,s),r=e.bytes;switch(s){case 10:r[i+9]=o>>>7&1;case 9:r[i+8]=9!==s?128|o:127&o;case 8:r[i+7]=8!==s?E>>>21|128:E>>>21&127;case 7:r[i+6]=7!==s?E>>>14|128:E>>>14&127;case 6:r[i+5]=6!==s?E>>>7|128:E>>>7&127;case 5:r[i+4]=5!==s?128|E:127&E;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 Ce=0,Te=0;g.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,g.UNILBS,V.INVALID_VENDOR_KEY,V.INVALID_CHANNEL_NAME,V.INTERNAL_ERROR,V.NO_AUTHORIZED,V.DYNAMIC_KEY_TIMEOUT,V.NO_ACTIVE_STATUS,V.DYNAMIC_KEY_EXPIRED,V.STATIC_USE_DYNAMIC_KEY,V.DYNAMIC_USE_STATIC_KEY,V.USER_OVERLOAD,V.FORBIDDEN_REGION,V.CANNOT_MEET_AREA_DEMAND,g.STRING_UID_ALLOCATOR,m.IIIEGAL_APPID,m.IIIEGAL_UID,m.INTERNAL_ERROR,U.K_TIMESTAMP_EXPIRED,U.K_CHANNEL_PERMISSION_INVALID,U.K_CERTIFICATE_INVALID,U.K_CHANNEL_NAME_EMPTY,U.K_CHANNEL_NOT_FOUND,U.K_TICKET_INVALID,U.K_CHANNEL_CONFLICTED,U.K_SERVICE_NOT_READY,U.K_SERVICE_TOO_HEAVY,U.K_UID_BANNED,U.K_IP_BANNED,U.K_AUTO_REBALANCE,U.ERR_INVALID_VENDOR_KEY,U.ERR_INVALID_CHANNEL_NAME,U.WARN_NO_AVAILABLE_CHANNEL,U.WARN_LOOKUP_CHANNEL_TIMEOUT,U.WARN_LOOKUP_CHANNEL_REJECTED,U.WARN_OPEN_CHANNEL_TIMEOUT,U.WARN_OPEN_CHANNEL_REJECTED,U.WARN_REQUEST_DEFERRED,U.ERR_DYNAMIC_KEY_TIMEOUT,U.ERR_NO_AUTHORIZED,U.ERR_VOM_SERVICE_UNAVAILABLE,U.ERR_NO_CHANNEL_AVAILABLE_CODE,U.ERR_MASTER_VOCS_UNAVAILABLE,U.ERR_INTERNAL_ERROR,U.ERR_NO_ACTIVE_STATUS,U.ERR_INVALID_UID,U.ERR_DYNAMIC_KEY_EXPIRED,U.ERR_STATIC_USE_DYANMIC_KE,U.ERR_DYNAMIC_USE_STATIC_KE,U.ERR_NO_VOCS_AVAILABLE,U.ERR_NO_VOS_AVAILABLE,U.ERR_JOIN_CHANNEL_TIMEOUT,U.ERR_JOIN_BY_MULTI_IP,U.ERR_NOT_JOINED,U.ERR_REPEAT_JOIN_REQUEST,U.ERR_REPEAT_JOIN_CHANNEL,U.ERR_INVALID_STRINGUID,U.ERR_TOO_MANY_USERS,U.ERR_SET_CLIENT_ROLE_TIMEOUT,U.ERR_SET_CLIENT_ROLE_NO_PERMISSION,U.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,U.ERR_PUBLISH_REQUEST_INVALID,U.ERR_SUBSCRIBE_REQUEST_INVALID,U.ERR_NOT_SUPPORTED_MESSAGE,U.ERR_ILLEAGAL_PLUGIN,U.ILLEGAL_CLIENT_ROLE_LEVEL,U.ERR_REJOIN_TOKEN_INVALID,U.ERR_REJOIN_USER_NOT_JOINED,U.ERR_INVALID_OPTIONAL_INFO,U.ERR_TEST_RECOVER,U.ERR_TEST_TRYNEXT,U.ERR_TEST_RETRY,U.ILLEGAL_AES_PASSWORD,U.ERR_TOO_MANY_BROADCASTERS,U.ERR_TOO_MANY_SUBSCRIBERS,U.ERR_LICENSE_ILLEGAL,U.ERR_LICENSE_MISSING,U.ERR_LICENSE_EXPIRED,U.ERR_LICENSE_MINUTES_EXCEEDED,U.ERR_LICENSE_PERIOD_INVALID,U.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const Oe={GLOBAL:{ASIA:[M.CHINA,M.JAPAN,M.INDIA,M.KOREA,M.HKMC],EUROPE:[],NORTH_AMERICA:[M.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(Oe[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 he=0;function Se(e,t,n,E){let{appId:o,areaCode:s,cname:i,sid:_,token:a,uid:N}=t;he++;const R="image_moderation_api",I={service_name:R,json_body:JSON.stringify({appId:o,areaCode:s,cname:i,command:"allocateEdge",requestId:he,seq:he,sid:_,token:a,ts:Date.now(),uid:N+""})};let O,h,u=e[0];return T((async()=>{O=Date.now();const e=await function(e,t,n,E){return new Promise(((o,s)=>{t.timeout=t.timeout||r("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),Ce+=A(t.data)):n&&(t.data.size?Ce+=t.data.size:t.data instanceof FormData?Ce+=C(t.data):Ce+=A(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,D.request(t).then((e=>{"string"==typeof e.data?Te+=A(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Te+=e.data.byteLength:Te+=A(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{D.isCancel(e)?s(new L(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new L(c.NETWORK_TIMEOUT,e.message)):e.response?s(new L(c.NETWORK_RESPONSE_ERROR,e.response.status)):s(new L(c.NETWORK_ERROR,e.message))}))}))}(u,{data:I,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-O,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 t=JSON.parse(e.json_body);if(200!==t.code){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw S.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:h});throw S.error(e.toString()),e}const E=r("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=r("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(o||n)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:h}}),((t,n)=>(d.apworkerEvent(_,{success:!0,sc:200,serviceName:R,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:R,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=new Map([["moderation",1],["supervise",2]]);function le(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}class de extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(W.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>Le.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=r("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=r("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=r("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 G("worker-manager-"+this._inspectId,h),this.on(W.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,S.debug("[".concat(this._inspectId,"] Inspect operation :").concat(v[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new G("worker-"+this._inspectId,h),this.handleWorkerEvents()}async init(e,t){this.emit(W.STATE_CHANGE,v.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(W.CONNECTION_STATE_CHANGE,((e,t)=>{t===k.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{o(e)}))}))}async requestAP(e,t,n){const E=r("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await Se(E,e,t,n);this.emit(W.STATE_CHANGE,v.AP_CONNECTED);const{addressList:s}=o;return this.wmSequence++,s}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(W.STATE_CHANGE,v.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(y.CONNECTED,(async()=>{this.emit(W.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.22.1",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(y.CLOSED,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(y.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(y.RECONNECTING,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(y.ON_MESSAGE,(async e=>{this.emit(W.STATE_CHANGE,v.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw S.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new L(l.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw S.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new L(l.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=r("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,E=t.replace(/:\d+\/?$/,":".concat(e));this.emit(W.STATE_CHANGE,v.CONNECT_WORKER,E),this._needWorkUrlOnly?this.emit(W.REQUEST_NEW_WORKER_URL,E):await this.connectWorker(E)}})),this.workerManagerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,v.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=k.CONNECTED})),this.workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Y(new Uint8Array(e.data));if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&S.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(t)),200===t.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(W.INSPECT_RESULT,void 0,void 0);if(t.data&&t.data.scorePorn&&t.data.scoreSexy&&t.data.scoreNeutral){const e={porn:t.data.scorePorn,sexy:t.data.scoreSexy,neutral:t.data.scoreNeutral},n=Object.keys(e).reduce(((t,n)=>e[t]>e[n]?t:n),"porn"),E=Object.keys(e).find((e=>e===n));this.emit(W.INSPECT_RESULT,E)}else this.emit(W.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"","There is an unexpected data on message"))}else this.emit(W.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"",t.msg))}else S.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(W.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(y.CLOSED,(()=>{this.connectionState=k.CLOSED})),this.workerConnection.on(y.FAILED,(()=>{this.connectionState=k.CLOSED})),this.workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===k.CONNECTED?k.RECONNECTING:k.CONNECTING})),this.workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(W.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=I(this,W.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(W.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(W.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:s,sid:i,uid:_}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),N=await u(a,n,E),R=this.sequence+"-"+o+"-"+_+"-"+c+"-"+O(12,""),I={appId:n,cid:o,cname:E,deviceId:"",elapse:le(Number(c-this.inspectStartTime)),fileSize:N.byteLength,jpgEncryption:2,height:a.height,width:a.width,jpg:N,networkType:6,osType:7,requestId:R,sdkVersion:"4.22.1",sequence:this.sequence,sid:i,timestamp:le(c),uid:_,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete I.callbackData,void 0===this.ossFilePrefix&&delete I.ossFilePrefix;const A=H(I);if(A.byteLength<this.workerMessageLengthLimit){if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=p({},I);delete e.jpg,S.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return A}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:s,sid:i,uid:_})}}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(W.STATE_CHANGE,v.CLOSED)}}function ue(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 De={name:"ContentInspect",create:function(e){let{config:t}=e;return ue(t),new de(t)}};export{De as ContentInspectService,ue as checkContentInspectConfig};