6 lines
38 KiB
JavaScript
6 lines
38 KiB
JavaScript
/**
|
||
* 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 i,createDefer as _,getParameter as s,AgoraRTCError as r,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as N,emitAsPromise as R,emitAsInvokerNoResponse as I,getUTF8StringByteLength as A,getMultiUnilbsFormDataByteLength as O,retryable as T,checkValidNumber as C,getRandomString as h,DEFAULT_RETRY_CONFIG as S,AgoraAPIName as L,AgoraAPITag as d}from"@agora-js/shared";import{logger as l,AgoraRTCError as u,AgoraRTCErrorCode as D,report as m}from"@agora-js/report";import{frameData2CryptoBuffer as f}from"@agora-js/media";import w from"axios";import"formdata-polyfill";function g(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 V(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 M(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach((function(t){g(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let U=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}({}),b=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}({}),p=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}({}),v=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}({}),P=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}({}),k=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}({});k.AFRICA,k.ASIA,k.CHINA,k.EUROPE,k.GLOBAL,k.INDIA,k.JAPAN,k.NORTH_AMERICA,k.OCEANIA,k.OVERSEA,k.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 G=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}({}),K=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="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}({}),H=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}({});class Y 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){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let _=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=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=M({},t),this.useCompress=_,this.tryDoubleDomain=s,this.use443PortOnly=r;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(i.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=_(),t=this.urls[this.currentURLIndex];s("ENABLE_PREALLOC_PC")&&this.emit(G.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new r(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 l.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),l.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 r(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new r(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=_();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),l.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(l.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 r(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 l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new r(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),s("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=s("GATEWAY_WSS_ADDRESS")),l.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=i,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 r,i=E&&e.code===c.WS_ABORT,_=E&&e.code===c.WS_ERR,s=E?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(s)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},N),t||_?(n.reject(t?new r(c.WS_DISCONNECT,"websocket is closed: ".concat(s)):new r(c.WS_ERR,"init websocket failed: ".concat(s))),_&&l.error("[".concat(this.name,"] init websocket failed: ").concat(s))):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;l.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);l.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);l.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&&(l.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 i;l.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(i=n.data)||void 0===i?void 0:i.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 F extends Y{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 i=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new r(c.WS_ABORT,"choose best websocket aborted"))};const _=s("GATEWAY_DOMAINS");let a;const R=e.indexOf("?h="),I=_.find((t=>-1!==R?e.includes(t,R):e.includes(t)));l.debug("[choose-best-ws] currentDomain: ",I,", domains: ",_);let A=!this.tryDoubleDomain||!I;if(!A&&I){var O;const s=Date.now();try{_.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",i.push(E),l.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(l.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();A=!0}null===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},t),i.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-s;l.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),i.filter((t=>t!==e)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),N(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var T;let o;l.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),i.push(o),o.binaryType="arraybuffer"}catch(e){const t=new r(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void E(t)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{l.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 J(e){let t=function(){const e=X.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(_e(t,10),ne(t,n));let E=e.cid;void 0!==E&&(_e(t,16),_e(t,E));let o=e.cname;void 0!==o&&(_e(t,26),ne(t,o));let i=e.deviceId;void 0!==i&&(_e(t,34),ne(t,i));let _=e.elapse;void 0!==_&&(_e(t,40),re(t,_));let s=e.fileSize;void 0!==s&&(_e(t,48),re(t,j(s)));let r=e.height;void 0!==r&&(_e(t,56),re(t,j(r)));let c=e.jpg;void 0!==c&&(_e(t,66),_e(t,c.length),ee(t,c));let a=e.networkType;void 0!==a&&(_e(t,72),re(t,j(a)));let N=e.osType;void 0!==N&&(_e(t,80),re(t,j(N)));let R=e.requestId;void 0!==R&&(_e(t,90),ne(t,R));let I=e.sdkVersion;void 0!==I&&(_e(t,98),ne(t,I));let A=e.sequence;void 0!==A&&(_e(t,104),re(t,j(A)));let O=e.sid;void 0!==O&&(_e(t,114),ne(t,O));let T=e.timestamp;void 0!==T&&(_e(t,120),re(t,T));let C=e.uid;void 0!==C&&(_e(t,128),_e(t,C));let h=e.vid;void 0!==h&&(_e(t,136),_e(t,h));let S=e.width;void 0!==S&&(_e(t,144),re(t,j(S)));let L=e.service;void 0!==L&&(_e(t,152),_e(t,L));let d=e.callbackData;void 0!==d&&(_e(t,162),_e(t,d.length),ee(t,d));let l=e.ticket;void 0!==l&&(_e(t,170),ne(t,l));let u=e.vendorConfigs;void 0!==u&&(_e(t,178),ne(t,u))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function x(e){return function(e){let t={};e:for(;!Z(e);){let n=ie(e);switch(n>>>3){case 0:break e;case 1:t.code=ie(e);break;case 2:t.msg=te(e,ie(e));break;case 3:t.requestId=te(e,ie(e));break;case 4:t.timestamp=se(e,!1);break;default:q(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function q(e,t){switch(t){case 0:for(;128&Ee(e););break;case 2:Q(e,ie(e));break;case 5:Q(e,4);break;case 1:Q(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function j(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let X=[];function Q(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Z(e){return e.offset>=e.limit}function z(e,t){let n=e.bytes,E=e.offset,o=e.limit,i=E+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>o&&(e.limit=i),E}function $(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ee(e,t){let n=z(e,t.length);e.bytes.set(t,n)}function te(e,t){let n=$(e,t),E=String.fromCharCode,o=e.bytes,i="<22>",_="";for(let e=0;e<t;e++){let s,r,c,a,N=o[e+n];0==(128&N)?_+=E(N):192==(224&N)?e+1>=t?_+=i:(s=o[e+n+1],128!=(192&s)?_+=i:(a=(31&N)<<6|63&s,a<128?_+=i:(_+=E(a),e++))):224==(240&N)?e+2>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],32896!=(49344&(s|r<<8))?_+=i:(a=(15&N)<<12|(63&s)<<6|63&r,a<2048||a>=55296&&a<=57343?_+=i:(_+=E(a),e+=2))):240==(248&N)?e+3>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(s|r<<8|c<<16))?_+=i:(a=(7&N)<<18|(63&s)<<12|(63&r)<<6|63&c,a<65536||a>1114111?_+=i:(a-=65536,_+=E(55296+(a>>10),56320+(1023&a)),e+=3))):_+=i}return _}function ne(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}_e(e,E);let o=z(e,E),i=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?i[o++]=E:(E<2048?i[o++]=E>>6&31|192:(E<65536?i[o++]=E>>12&15|224:(i[o++]=E>>18&7|240,i[o++]=E>>12&63|128),i[o++]=E>>6&63|128),i[o++]=63&E|128)}}function Ee(e){return e.bytes[$(e,1)]}function oe(e,t){let n=z(e,1);e.bytes[n]=t}function ie(e){let t,n=0,E=0;do{t=Ee(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function _e(e,t){for(t>>>=0;t>=128;)oe(e,127&t|128),t>>>=7;oe(e,t)}function se(e,t){let n,E=0,o=0,i=0;return n=Ee(e),E=127&n,128&n&&(n=Ee(e),E|=(127&n)<<7,128&n&&(n=Ee(e),E|=(127&n)<<14,128&n&&(n=Ee(e),E|=(127&n)<<21,128&n&&(n=Ee(e),o=127&n,128&n&&(n=Ee(e),o|=(127&n)<<7,128&n&&(n=Ee(e),o|=(127&n)<<14,128&n&&(n=Ee(e),o|=(127&n)<<21,128&n&&(n=Ee(e),i=127&n,128&n&&(n=Ee(e),i|=(127&n)<<7))))))))),{low:E|o<<28,high:o>>>4|i<<24,unsigned:t}}function re(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,i=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,_=z(e,i),s=e.bytes;switch(i){case 10:s[_+9]=o>>>7&1;case 9:s[_+8]=9!==i?128|o:127&o;case 8:s[_+7]=8!==i?E>>>21|128:E>>>21&127;case 7:s[_+6]=7!==i?E>>>14|128:E>>>14&127;case 6:s[_+5]=6!==i?E>>>7|128:E>>>7&127;case 5:s[_+4]=5!==i?128|E:127&E;case 4:s[_+3]=4!==i?n>>>21|128:n>>>21&127;case 3:s[_+2]=3!==i?n>>>14|128:n>>>14&127;case 2:s[_+1]=2!==i?n>>>7|128:n>>>7&127;case 1:s[_]=1!==i?128|n:127&n}}const ce={},ae={},Ne=4294967296,Re=Ne*Ne,Ie=Re/2,Ae=Se(0,!0),Oe=Se(0),Te=Le(0,-2147483648,!1),Ce=Le(-1,2147483647,!1),he=Le(-1,-1,!0);function Se(e,t){let n,E,o;return t?(o=0<=(e>>>=0)&&e<256)&&(E=ae[e],E)?E:(n=Le(e,0,!0),o&&(ae[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(E=ce[e],E)?E:(n=Le(e,e<0?-1:0,!1),o&&(ce[e]=n),n)}function Le(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function de(e,t){if(isNaN(e))return t?Ae:Oe;if(t){if(e<0)return Ae;if(e>=Re)return he}else{if(e<=-Ie)return Te;if(e+1>=Ie)return Ce}return e<0?t?Ae:Oe:Le(e%Ne|0,e/Ne|0,t)}let le=0,ue=0;U.ACCESS_POINT,v.NO_FLAG_SET,v.FLAG_SET_BUT_EMPTY,v.INVALID_FALG_SET,v.FLAG_SET_BUT_NO_RE,v.INVALID_SERVICE_ID,v.NO_SERVICE_AVAILABLE,v.NO_SERVICE_AVAILABLE_P2P,v.NO_SERVICE_AVAILABLE_VOICE,v.NO_SERVICE_AVAILABLE_WEBRTC,v.NO_SERVICE_AVAILABLE_CDS,v.NO_SERVICE_AVAILABLE_CDN,v.NO_SERVICE_AVAILABLE_TDS,v.NO_SERVICE_AVAILABLE_REPORT,v.NO_SERVICE_AVAILABLE_APP_CENTER,v.NO_SERVICE_AVAILABLE_ENV0,v.NO_SERVICE_AVAILABLE_VOET,v.NO_SERVICE_AVAILABLE_STRING_UID,v.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,U.UNILBS,p.INVALID_VENDOR_KEY,p.INVALID_CHANNEL_NAME,p.INTERNAL_ERROR,p.NO_AUTHORIZED,p.DYNAMIC_KEY_TIMEOUT,p.NO_ACTIVE_STATUS,p.DYNAMIC_KEY_EXPIRED,p.STATIC_USE_DYNAMIC_KEY,p.DYNAMIC_USE_STATIC_KEY,p.USER_OVERLOAD,p.FORBIDDEN_REGION,p.CANNOT_MEET_AREA_DEMAND,U.STRING_UID_ALLOCATOR,b.IIIEGAL_APPID,b.IIIEGAL_UID,b.INTERNAL_ERROR,P.K_TIMESTAMP_EXPIRED,P.K_CHANNEL_PERMISSION_INVALID,P.K_CERTIFICATE_INVALID,P.K_CHANNEL_NAME_EMPTY,P.K_CHANNEL_NOT_FOUND,P.K_TICKET_INVALID,P.K_CHANNEL_CONFLICTED,P.K_SERVICE_NOT_READY,P.K_SERVICE_TOO_HEAVY,P.K_UID_BANNED,P.K_IP_BANNED,P.K_AUTO_REBALANCE,P.ERR_INVALID_VENDOR_KEY,P.ERR_INVALID_CHANNEL_NAME,P.WARN_NO_AVAILABLE_CHANNEL,P.WARN_LOOKUP_CHANNEL_TIMEOUT,P.WARN_LOOKUP_CHANNEL_REJECTED,P.WARN_OPEN_CHANNEL_TIMEOUT,P.WARN_OPEN_CHANNEL_REJECTED,P.WARN_REQUEST_DEFERRED,P.ERR_DYNAMIC_KEY_TIMEOUT,P.ERR_NO_AUTHORIZED,P.ERR_VOM_SERVICE_UNAVAILABLE,P.ERR_NO_CHANNEL_AVAILABLE_CODE,P.ERR_MASTER_VOCS_UNAVAILABLE,P.ERR_INTERNAL_ERROR,P.ERR_NO_ACTIVE_STATUS,P.ERR_INVALID_UID,P.ERR_DYNAMIC_KEY_EXPIRED,P.ERR_STATIC_USE_DYANMIC_KE,P.ERR_DYNAMIC_USE_STATIC_KE,P.ERR_NO_VOCS_AVAILABLE,P.ERR_NO_VOS_AVAILABLE,P.ERR_JOIN_CHANNEL_TIMEOUT,P.ERR_JOIN_BY_MULTI_IP,P.ERR_NOT_JOINED,P.ERR_REPEAT_JOIN_REQUEST,P.ERR_REPEAT_JOIN_CHANNEL,P.ERR_INVALID_STRINGUID,P.ERR_TOO_MANY_USERS,P.ERR_SET_CLIENT_ROLE_TIMEOUT,P.ERR_SET_CLIENT_ROLE_NO_PERMISSION,P.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,P.ERR_PUBLISH_REQUEST_INVALID,P.ERR_SUBSCRIBE_REQUEST_INVALID,P.ERR_NOT_SUPPORTED_MESSAGE,P.ERR_ILLEAGAL_PLUGIN,P.ILLEGAL_CLIENT_ROLE_LEVEL,P.ERR_REJOIN_TOKEN_INVALID,P.ERR_REJOIN_USER_NOT_JOINED,P.ERR_INVALID_OPTIONAL_INFO,P.ERR_TEST_RECOVER,P.ERR_TEST_TRYNEXT,P.ERR_TEST_RETRY,P.ILLEGAL_AES_PASSWORD,P.ERR_TOO_MANY_BROADCASTERS,P.ERR_TOO_MANY_SUBSCRIBERS,P.ERR_LICENSE_ILLEGAL,P.ERR_LICENSE_MISSING,P.ERR_LICENSE_EXPIRED,P.ERR_LICENSE_MINUTES_EXCEEDED,P.ERR_LICENSE_PERIOD_INVALID,P.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const De={GLOBAL:{ASIA:[k.CHINA,k.JAPAN,k.INDIA,k.KOREA,k.HKMC],EUROPE:[],NORTH_AMERICA:[k.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(De[k.GLOBAL]),k.CHINA,k.NORTH_AMERICA,k.EUROPE,k.ASIA,k.JAPAN,k.INDIA,k.OCEANIA,k.SOUTH_AMERICA,k.AFRICA,k.KOREA,k.HKMC,k.US;let me=0;function fe(e,t,n,E){let{appId:o,areaCode:i,cname:_,sid:r,token:a,uid:N}=t;me++;const R="moderation_plugin",I={service_name:R,json_body:JSON.stringify({appId:o,areaCode:i,cname:_,command:"allocateEdge",requestId:me,seq:me,sid:r,appToken:a,ts:Date.now(),uid:N+""})};let C,h,S=e[0];return T((async()=>{C=Date.now();const e=await function(e,t,n,E){return new Promise(((o,i)=>{t.timeout=t.timeout||s("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),le+=A(t.data)):n&&(t.data.size?le+=t.data.size:t.data instanceof FormData?le+=O(t.data):le+=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,w.request(t).then((e=>{"string"==typeof e.data?ue+=A(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ue+=e.data.byteLength:ue+=A(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{w.isCancel(e)?i(new u(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new u(c.NETWORK_TIMEOUT,e.message)):e.response?i(new u(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new u(c.NETWORK_ERROR,e.message))}))}))}(S,{data:I,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-C,0!==e.code){const t=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:h});throw l.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:h});throw l.error(e.toString()),e}const E=s("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(n,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:h}}),((t,n)=>(m.apworkerEvent(r,{success:!0,sc:200,serviceName:R,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(m.apworkerEvent(r,{success:!1,sc:t.data&&t.data.code||200,serviceName:R,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==D.OPERATION_ABORTED&&t.code!==D.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(S=e[(n+1)%e.length],!0))),E)}class we 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,e,t)}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){var t;super(),this.name="AgoraRTCImageModeration",this._connectionState=K.CONNECTING,this._sequence=0,this._moderationStartTime=void 0,this._workerConnection=void 0,this._workerMessageLengthLimit=void 0,this._qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=w.CancelToken.source(),this._retryConfig=void 0,this._moderationInterval=void 0,this._moderationTimer=null,this._moderationMode=1,this._quality=1,this._qualityTimer=null,this._ticket=void 0,this._moderationIntervalMinimum=void 0,this._uploadFailedNum=0,this._uploadNum=0,this._uploadTimer=null,this._extraInfo=void 0,this._vendor="",this._encoder=new TextEncoder,this._moderationId=void 0,this.inspectImage=()=>{if(this.connectionState!==K.CONNECTED)throw new u(D.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===K.CONNECTED?this.requestToInspectImage():l.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()},this._moderationId=h(5,"image-moderation-"),this._workerMessageLengthLimit=s("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=s("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=s("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new F("worker-"+this._moderationId,S),this.on(W.STATE_CHANGE,((e,t)=>{l.debug("[".concat(this._moderationId,"] Moderation operation :").concat(H[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(W.STATE_CHANGE,H.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)=>{e===K.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{o(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),l.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===K.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const E=s("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await fe(E,e,t,n);this.emit(W.STATE_CHANGE,H.AP_CONNECTED);const{addressList:i,ticket:_}=o;return this._ticket=_,i}async connectWorker(e){this.emit(W.STATE_CHANGE,H.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,H.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=K.CONNECTED})),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.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=x(new Uint8Array(e.data));s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,l.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{m.reportApiInvoke(this._connectInfo.sid||null,{name:L.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:d.TRACER}).onError(new u(D.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),s("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else l.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),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.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){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(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),N=await f(a,n,E),R=this._sequence+"-"+o+"-"+r+"-"+c+"-"+h(12,""),I={appId:n,cid:o,cname:E,deviceId:"",elapse:we.intToLong(Number(c-this._moderationStartTime)),fileSize:a.buffer.byteLength,height:a.height,width:a.width,jpg:N,networkType:6,osType:7,requestId:R,sdkVersion:"4.22.1",sequence:this._sequence,sid:_,timestamp:de(c),uid:r,vid:i,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete I.callbackData;const A=J(I);if(A.byteLength<this._workerMessageLengthLimit){if(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=M({},I);delete e.jpg,l.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),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:i,sid:_,uid:r})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=w.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=K.CLOSED,this.emit(W.STATE_CHANGE,H.CLOSED)}}function ge(e){if(C(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new u(D.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new u(D.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Ve={name:"ImageModeration",create:function(e){let{config:t}=e;return ge(t),new we(t)}};export{Ve as ImageModerationService,ge as checkImageModerationConfig};
|