call-engine-wx 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.mjs +2 -2
- package/dist/index.mp.js +1 -1
- package/dist/index.umd.js +5 -3546
- package/dist/index.umd.js.map +1 -1
- package/dist/index.umd.min.js +1 -1
- package/dist/index.umd.min.js.map +1 -1
- package/package.json +1 -3
package/dist/index.umd.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! call-engine-wx | (c) 2024 Tencent | MIT */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CallsEngineWX={})}(this,function(e){"use strict";class t{constructor(){this._handlers=new Map}on(e,t){if("function"!=typeof t)return this;let s=this._handlers.get(e);return s||(s=[],this._handlers.set(e,s)),s.push({fn:t,once:!1}),this}once(e,t){if("function"!=typeof t)return this;let s=this._handlers.get(e);return s||(s=[],this._handlers.set(e,s)),s.push({fn:t,once:!0}),this}off(e,t){if(!e)return this._handlers.clear(),this;const s=this._handlers.get(e);if(!s)return this;if(!t)return this._handlers.delete(e),this;const n=s.filter(e=>e.fn!==t);return 0===n.length?this._handlers.delete(e):this._handlers.set(e,n),this}emit(e,...t){const s=this._handlers.get(e);if(!s||0===s.length)return!1;const n=s.slice();for(const s of n){try{s.fn.apply(null,t)}catch(e){console.error("[call-engine-wx] listener threw:",e)}s.once&&this.off(e,s.fn)}return!0}removeAllListeners(e){return e?this._handlers.delete(e):this._handlers.clear(),this}listenerCount(e){const t=this._handlers.get(e);return t?t.length:0}}var s,n,o,i,r,a,c,u,l,d;e.CallStatus=void 0,(s=e.CallStatus||(e.CallStatus={}))[s.NONE=0]="NONE",s[s.WAITING=1]="WAITING",s[s.CALLING=2]="CALLING",e.CallRole=void 0,(n=e.CallRole||(e.CallRole={}))[n.NONE=0]="NONE",n[n.CALLER=1]="CALLER",n[n.CALLEE=2]="CALLEE",e.CallMediaType=void 0,(o=e.CallMediaType||(e.CallMediaType={}))[o.UNKNOWN=0]="UNKNOWN",o[o.AUDIO=1]="AUDIO",o[o.VIDEO=2]="VIDEO",e.CallScene=void 0,(i=e.CallScene||(e.CallScene={}))[i.NONE=0]="NONE",i[i.GROUP=1]="GROUP",i[i.MULTI=2]="MULTI",i[i.SINGLE=3]="SINGLE",e.IOSOfflinePushType=void 0,(r=e.IOSOfflinePushType||(e.IOSOfflinePushType={}))[r.APNs=0]="APNs",r[r.VoIP=1]="VoIP",e.CallInvitationResultCodeType=void 0,(a=e.CallInvitationResultCodeType||(e.CallInvitationResultCodeType={}))[a.SUCCESS=0]="SUCCESS",a[a.INVITED=1]="INVITED",a[a.LINE_BUSY=2]="LINE_BUSY",e.CallEndReason=void 0,(c=e.CallEndReason||(e.CallEndReason={}))[c.UNKNOWN=0]="UNKNOWN",c[c.HANGUP=1]="HANGUP",c[c.REJECT=2]="REJECT",c[c.NO_RESPONSE=3]="NO_RESPONSE",c[c.OFFLINE=4]="OFFLINE",c[c.LINE_BUSY=5]="LINE_BUSY",c[c.CANCELED=6]="CANCELED",c[c.OTHER_DEVICE_ACCEPTED=7]="OTHER_DEVICE_ACCEPTED",c[c.OTHER_DEVICE_REJECT=8]="OTHER_DEVICE_REJECT",c[c.END_BY_SERVER=9]="END_BY_SERVER",e.LOG_LEVEL=void 0,(u=e.LOG_LEVEL||(e.LOG_LEVEL={}))[u.DEBUG=0]="DEBUG",u[u.INFO=1]="INFO",u[u.WARN=2]="WARN",u[u.ERROR=3]="ERROR",u[u.NONE=4]="NONE",e.CameraPosition=void 0,(l=e.CameraPosition||(e.CameraPosition={}))[l.FRONT=1]="FRONT",l[l.BACK=0]="BACK",e.AudioPlayBackDevice=void 0,(d=e.AudioPlayBackDevice||(e.AudioPlayBackDevice={}))[d.SPEAKER=0]="SPEAKER",d[d.EAR=1]="EAR";const h=Object.freeze({None:0,AcceptedByInvitee:1,RejectedByInvitee:2,NoResponseUntilTimeout:3,Hangup:4,Join:5,Offline:6,InviteUser:7}),p=Object.freeze({ERR_FAILED:-1}),g=Object.freeze({ERROR:"onError",SDK_READY:"sdkReady",KICKED_OUT:"onKickedOffline",onUserSigExpired:"onUserSigExpired",ON_CALL_BEGIN:"onCallBegin",ON_CALL_END:"onCallEnd",ON_CALL_RECEIVED:"onCallReceived",ON_CALL_CANCELED:"onCallCanceled",ON_CALL_NOT_CONNECTED:"onCallNotConnected",INVITED:"onInvited",USER_ENTER:"onUserJoin",USER_LEAVE:"onUserLeave",VIEW_LAYOUT_CHANGED:"viewLayoutChanged"}),_="number",m="object",f="array",v="function",I=function(e){return typeof e===_},E=function(e){return typeof Array.isArray===v?Array.isArray(e):y(e)===f},C=function(e){return typeof e===v},y=function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()};let S=null;const M=function(e){const t=function(){if(S)return S;const e={osName:"Unknown",osVersion:"0.0.0",deviceName:"Unknown"};try{const t="undefined"!=typeof wx?wx:null,s="undefined"!=typeof uni?uni:null;if(t&&"function"==typeof t.getSystemInfoSync){const s=t.getSystemInfoSync()||{},[n="Unknown",o="0.0.0"]=String(s.system||"").split(" ");e.osName=n,e.osVersion=o,e.deviceName=s.model||s.brand||"Unknown"}else if(s&&"function"==typeof s.getSystemInfoSync){const t=s.getSystemInfoSync()||{},[n="Unknown",o="0.0.0"]=String(t.system||"").split(" ");e.osName=n,e.osVersion=o,e.deviceName=t.model||t.brand||"Unknown"}else if("undefined"!=typeof navigator&&navigator.userAgent){const t=navigator.userAgent;if(/Mac OS X/i.test(t)){e.osName="MacOS";const s=t.match(/Mac OS X ([\d_\.]+)/);e.osVersion=s?s[1].replace(/_/g,"."):"0.0.0",e.deviceName="Mac"}else if(/Windows/i.test(t)){e.osName="Windows";const s=t.match(/Windows NT ([\d\.]+)/);e.osVersion=s?s[1]:"0.0.0",e.deviceName="PC"}else if(/Android/i.test(t)){e.osName="Android";const s=t.match(/Android ([\d\.]+)/);e.osVersion=s?s[1]:"0.0.0",e.deviceName="Android"}else if(/iPhone|iPad|iPod/i.test(t)){e.osName="iOS";const s=t.match(/OS ([\d_]+)/);e.osVersion=s?s[1].replace(/_/g,"."):"0.0.0",e.deviceName=/iPad/i.test(t)?"iPad":"iPhone"}}}catch(e){}return S=e,e}();return{Command:e,DeviceName:t.deviceName,LongPollingKey:"",OSName:t.osName,OSVersion:t.osVersion,RoomId:"",SdkVersion:"1.0.0.0",Version:2}},T=function(t={}){let s=e.CallScene.NONE;const n=t.userIDList||[];return n.length>1&&(s=e.CallScene.MULTI),1===n.length&&(s=e.CallScene.SINGLE),{callId:t.callId||"",roomId:{strRoomId:t.strRoomID||t.strRoomId||"",intRoomId:t.roomID||t.roomId||0},inviter:t.inviter||"",inviteeList:n,groupId:t.chatGroupID||"",mediaType:t.type,status:t.status||e.CallStatus.NONE,role:t.role||e.CallRole.NONE,scene:s,callStartTime:0}},R=Object.freeze({IntRoomId:1,StrRoomId:2});function A(t,s){const n={Title:(t=t||{}).title||"",Sound:t.iosSound||"",BadgeMode:t.ignoreIosBadge?1:0,IsVoipPush:t.iosPushType||0,ContentAvailable:t.enableIosBackgroundNotification?1:0,InterruptionLevel:t.iosInterruptionLevel||"",Image:t.iosImage||""},o={Sound:t.androidSound||"",Title:t.title||"",OPPOChannelID:t.androidOppoChannelId||"",OPPOCategory:t.oppoCategory||"IM",OPPONotifyLevel:t.oppoNotifyLevel||0,GoogleChannelID:t.androidFcmChannelId||"",GoogleImage:t.fcmImage||"",XiaoMiChannelID:t.androidXiaomiChannelId||"",VIVOClassification:t.androidVivoClassification||0,VIVOCategory:t.vivoCategory||"IM",HuaWeiCategory:t.androidHuaweiCategory||"IM",HuaWeiImage:t.huaweiImage||"",HonorImportance:t.honorImportance||"NORMAL",HonorImage:t.honorImage||""},i={entity:{action:2},timPushFeatures:{fcmPushType:0,fcmNotificationType:1},voip_ext:{voip_type:"call",voip_media_type:s===e.CallMediaType.VIDEO?"video":"audio"}};return{Title:t.title||"",Description:t.description||"",Ext:JSON.stringify(i),AndroidInfo:o,ApnsInfo:n}}const O="sendTRTCCustomData",D="call_engine_srv.start_call",b="call_engine_srv.heart_beat",L="call_engine_srv.handle_call",N="call_engine_srv.hangup",w="call_engine_srv.cancel_invite",P="call_engine_srv.get_invitation",G=-1,U={errCode:0,errMsg:"",inviteId:"",callResultList:[]};let k=null,F="",x=0;function V(){k&&(clearInterval(k),k=null),F="",x=0}async function $(e,t){const s=e||{},n=s.chat;if(!n||!C(n.callExperimentalAPI))return{errCode:G,errMsg:"chat.callExperimentalAPI is not available"};if(!s.callId)return{errCode:G,errMsg:"callId is required"};if(!s.terminalId)return{errCode:G,errMsg:"terminalId is required"};let o=L;t===h.Hangup&&(o=N);const i=function(e,t,s,n){return{Body:{CallId:e||"",TerminalId:t||"",ActionType:s>>>0},Head:M(n)}}(s.callId,s.terminalId,t,o);try{const e={serviceCommand:o,data:JSON.stringify(i)},t=await n.callExperimentalAPI(O,e),s=t&&t.data||t||{},r=I(s.ErrorCode)?s.ErrorCode:I(s.errorCode)?s.errorCode:0;return 0!==r?{errCode:r,errMsg:s.ErrorInfo||s.errorInfo||""}:{errCode:0,errMsg:""}}catch(e){return{errCode:e&&(e.code||e.errorCode)||G,errMsg:e&&(e.message||e.errorInfo)||"send failed"}}}const q={CMD_START_CALL:D,CMD_HEART_BEAT:b,CMD_HANDLE_CALL:L,CMD_HANGUP_CALL:N,CMD_CANCEL_CALL:w,CMD_GET_INVITATION:P,HEARTBEAT_INTERVAL_MS:2e3,HEARTBEAT_FAIL_RETRY_DEFAULT:5,HEARTBEAT_FAIL_INTERVAL_MS:2e3,startCall:async function(t){const s=t||{},n=s.chat;if(!n||!C(n.callExperimentalAPI))return{...U,errCode:G,errMsg:"chat.callExperimentalAPI is not available"};if(!s.inviter)return{...U,errCode:G,errMsg:"inviter is required"};if(!E(s.userIdList)||0===s.userIdList.length)return{...U,errCode:G,errMsg:"userIdList cannot be empty"};if(s.mediaType!==e.CallMediaType.AUDIO&&s.mediaType!==e.CallMediaType.VIDEO)return{...U,errCode:G,errMsg:"invalid mediaType"};const o={roomId:s.roomId||{},timeout:s.timeout,userData:s.userData,isEphemeralCall:!!s.isEphemeralCall,offlinePushInfo:s.offlinePushInfo},i=function(e,t,s,n,o){const i=n||{},r=i.roomId||{},a={CallId:"",CallMediaType:s>>>0};"number"==typeof r.intRoomId&&r.intRoomId>0?(a.RoomId=String(r.intRoomId),a.RoomIdType=R.IntRoomId):(!r.intRoomId||0===r.intRoomId)&&"string"==typeof r.strRoomId&&r.strRoomId.length>0&&(a.RoomId=r.strRoomId,a.RoomIdType=R.StrRoomId),a.ExcludeFromHistoryMessage=!1,a.GroupId=o||"",a.IsEphemeralCall=!!i.isEphemeralCall;const c="number"==typeof i.timeout?i.timeout:30;return{Body:{Caller_Account:e,CalleeList_Account:(t||[]).slice(),CallInfo:a,Timeout:1e3*c,UserData:i.userData||"",OfflinePushInfo:A(i.offlinePushInfo,s)},Head:M("call_engine_srv.start_call")}}(s.inviter,s.userIdList,s.mediaType,o,s.groupId||"");let r;try{const e={serviceCommand:D,data:JSON.stringify(i)};r=await n.callExperimentalAPI(O,e)}catch(e){const t=e&&(e.code||e.errorCode)||G,s=e&&(e.message||e.errorInfo)||"send failed";return{...U,errCode:t,errMsg:s}}const a=r&&r.data||r||{};return 0!==a.ErrorCode?{...U,errCode:a.ErrorCode,errMsg:a.ErrorInfo}:{errCode:a?.ErrorCode||0,errMsg:a?.errMsg||"",inviteId:a?.Response?.CallId||"",callResultList:a?.Response?.CallResult||[]}},startHeartBeat:function(e){const t=e||{},{chat:s,callId:n,userId:o}=t;if(!s||!C(s.callExperimentalAPI))return void console.warn("[SSOChannel] startHeartBeat: chat.callExperimentalAPI unavailable");if(!n||!o)return void console.warn("[SSOChannel] startHeartBeat: callId and userId are required");V();const i=I(t.intervalMs)&&t.intervalMs>0?t.intervalMs:2e3,r=I(t.retryCount)&&t.retryCount>0?t.retryCount:5;F=n,k=setInterval(async()=>{if(!F||F!==n)return;const e=await async function(e,t,s){const n={Body:{User_Account:s,CallId:t},Head:M(b)};try{const t={serviceCommand:b,data:JSON.stringify(n)},s=await e.callExperimentalAPI(O,t),o=s&&s.data||s||{},i=I(o.ErrorCode)?o.ErrorCode:I(o.errorCode)?o.errorCode:0;return 0!==i?{errCode:i,errMsg:o.ErrorInfo||o.errorInfo||""}:{errCode:0,errMsg:""}}catch(e){return{errCode:e&&(e.code||e.errorCode)||G,errMsg:e&&(e.message||e.errorInfo)||"send failed"}}}(s,n,o);if(F&&F===n)if(0!==e.errCode){if(x+=1,console.warn("[SSOChannel] heartbeat failed",x,e.errCode,e.errMsg),x>=r){const e=F;if(V(),"function"==typeof t.onTimeout)try{t.onTimeout(e)}catch(e){}}}else x=0},i)},stopHeartBeat:V,accept:async function(e){return $(e,h.AcceptedByInvitee)},reject:async function(e){return $(e,h.RejectedByInvitee)},hangup:async function(e){return $(e,h.Hangup)},cancel:async function(e){const t=e||{},s=t.chat;if(!s||!C(s.callExperimentalAPI))return{errCode:G,errMsg:"chat.callExperimentalAPI is not available"};if(!t.callId)return{errCode:G,errMsg:"callId is required"};if(!t.inviter)return{errCode:G,errMsg:"inviter is required"};if(!E(t.calleeList)||0===t.calleeList.length)return{errCode:G,errMsg:"calleeList cannot be empty"};const n=(o=t.inviter,i=t.callId,r=t.calleeList,a=w,{Body:{CallId:i||"",Operator_Account:o||"",CalleeList_Account:Array.isArray(r)?r.filter(Boolean):[]},Head:M(a)});var o,i,r,a;try{const e={serviceCommand:w,data:JSON.stringify(n)},t=await s.callExperimentalAPI(O,e),o=t&&t.data||t||{},i=I(o.ErrorCode)?o.ErrorCode:I(o.ErrorCode)?o.errorCode:0;return 0!==i?{errCode:i,errMsg:o.ErrorInfo||o.errorInfo||""}:{errCode:0,errMsg:""}}catch(e){return{errCode:e&&(e.code||e.errorCode)||G,errMsg:e&&(e.message||e.errorInfo)||"send failed"}}},getInvitation:async function(e){const t=e||{},s=t.chat;if(!s||!C(s.callExperimentalAPI))return{errCode:G,errMsg:"chat.callExperimentalAPI is not available",data:null};if(!t.userId)return{errCode:G,errMsg:"userId is required",data:null};const n={Body:{User_Account:t.userId||""},Head:M(P)};var o;try{const e={serviceCommand:P,data:JSON.stringify(n)},t=await s.callExperimentalAPI(O,e),i=t&&t.data||t||{},r=I(i.ErrorCode)?i.ErrorCode:I(i.ErrorCode)?i.errorCode:0;if(0!==r)return{errCode:r,errMsg:i.ErrorInfo||i.errorInfo||"",data:null};const a=i?.Response;return a&&(null!==(o=a)&&typeof o===m)&&0!==Object.keys(a).length?{errCode:0,errMsg:"",data:a}:{errCode:0,errMsg:"",data:null}}catch(e){return{errCode:e&&(e.code||e.errorCode)||G,errMsg:e&&(e.message||e.errorInfo)||"send failed",data:null}}}};var B,j;e.LayoutTemplate=void 0,(B=e.LayoutTemplate||(e.LayoutTemplate={}))[B.FLOAT=0]="FLOAT",B[B.GRID=1]="GRID",function(e){e[e.NONE=0]="NONE",e[e.WAITING=1]="WAITING",e[e.CALLING=2]="CALLING"}(j||(j={}));const H=720,K=1280,W={x:480,y:80,w:200,h:300};class Y{constructor(){this.currentTemplate=e.LayoutTemplate.FLOAT,this.largeViewUserId="",this.isViewReversed=!1,this.currentLayout=J(),this.previousLayout=J()}setLayoutTemplate(e){this.currentTemplate=e,this.largeViewUserId="",this.isViewReversed=!1}setLargeViewUser(e){this.largeViewUserId===e?this.largeViewUserId="":this.largeViewUserId=e}toggleViewReversed(){this.isViewReversed=!this.isViewReversed}getCurrentTemplate(){return this.currentTemplate}getCurrentLayout(){return this.currentLayout}recalculate(t){switch(this.previousLayout=this.currentLayout,this.currentTemplate){case e.LayoutTemplate.FLOAT:this.currentLayout=this.calculateFloatLayout(t);break;case e.LayoutTemplate.GRID:this.currentLayout=this.calculateGridLayout(t)}return this.isLayoutChanged()}toJson(){return JSON.stringify(this.toJsonObject())}toJsonObject(){const t=this.currentLayout,s={template:z(t.template)};return t.template===e.LayoutTemplate.FLOAT?(s.canvas={w:t.canvas.w,h:t.canvas.h},s.primaryUser={userId:t.primaryUser.userId,isLocal:t.primaryUser.isLocal},t.secondaryUser?s.secondaryUser={userId:t.secondaryUser.userId,isLocal:t.secondaryUser.isLocal,frame:{...t.secondaryUser.frame}}:s.secondaryUser=null,s.showRemoteInfo=t.showRemoteInfo):(s.canvas={w:t.canvas.w,h:t.canvas.h},s.participants=t.participants.map(e=>({userId:e.userId,frame:{...e.frame},isLocal:e.isLocal,showName:e.showName}))),s}isLayoutChanged(){const t=this.previousLayout,s=this.currentLayout;if(t.template!==s.template)return!0;if(s.template===e.LayoutTemplate.FLOAT&&t.template===e.LayoutTemplate.FLOAT){if(t.primaryUser.userId!==s.primaryUser.userId)return!0;return(t.secondaryUser?t.secondaryUser.userId:"")!==(s.secondaryUser?s.secondaryUser.userId:"")||t.showRemoteInfo!==s.showRemoteInfo}if(s.template===e.LayoutTemplate.GRID&&t.template===e.LayoutTemplate.GRID){if(t.participants.length!==s.participants.length)return!0;for(let e=0;e<s.participants.length;e++){const n=t.participants[e],o=s.participants[e];if(n.userId!==o.userId)return!0;if(n.frame.x!==o.frame.x)return!0;if(n.frame.y!==o.frame.y)return!0;if(n.frame.w!==o.frame.w)return!0;if(n.frame.h!==o.frame.h)return!0;if(n.showName!==o.showName)return!0}return!1}return!0}calculateFloatLayout(t){const s=t.selfId;let n="";for(const e of t.allParticipants)if(e.id!==s){n=e.id;break}const o=t.selfStatus===j.CALLING,i=t.mediaType===e.CallMediaType.AUDIO;let r,a,c,u;return o||i?!o&&i||i?(r=n,a=!1,c=null,u=!0):(this.isViewReversed?(r=s,a=!0,c={userId:n,isLocal:!1,frame:{...W}}):(r=n,a=!1,c={userId:s,isLocal:!0,frame:{...W}}),u=!1):(r=s,a=!0,c=null,u=!0),{template:e.LayoutTemplate.FLOAT,canvas:{w:H,h:K},primaryUser:{userId:r,isLocal:a},secondaryUser:c,showRemoteInfo:u}}calculateGridLayout(t){const s=new Map;for(const e of t.allParticipants)s.set(e.id,e.status);const n=[];if(t.inviter){const e=s.get(t.inviter);void 0!==e&&e!==j.NONE&&n.push(t.inviter)}for(const e of t.inviteeList){const t=s.get(e);void 0!==t&&t!==j.NONE&&n.push(e)}const o=this.calculateGridPositions(n.length,n,t.selfId);return{template:e.LayoutTemplate.GRID,canvas:{w:H,h:K},participants:o}}calculateGridPositions(e,t,s){const n=[];if(e<=0)return n;const o=240,i=360;let r=-1;if(this.largeViewUserId)for(let s=0;s<e;s++)if(t[s]===this.largeViewUserId){r=s;break}if(r>=0&&e<=4){const i=[r];for(let t=0;t<e;t++)t!==r&&i.push(t);const a=o,c=e-1,u=[{x:0,y:0,w:H,h:H}],l=H;for(let e=0;e<c;e++)u.push({x:e*a,y:l,w:a,h:a});for(let e=0;e<i.length&&e<u.length;e++){const o=t[i[e]];n.push({userId:o,frame:u[e],isLocal:o===s,showName:0===e})}return n}if(r>=0&&e>4){const i=480,a=480,c=[r];for(let t=0;t<e;t++)t!==r&&c.push(t);{const e=t[c[0]];n.push({userId:e,frame:{x:0,y:0,w:i,h:a},isLocal:e===s,showName:!0})}let u=1;if(u<c.length){const e=t[c[u]];n.push({userId:e,frame:{x:i,y:0,w:o,h:o},isLocal:e===s,showName:!1}),u++}if(u<c.length){const e=t[c[u]];n.push({userId:e,frame:{x:i,y:o,w:o,h:o},isLocal:e===s,showName:!1}),u++}let l=a;for(;u<c.length;){for(let e=0;e<3&&u<c.length;e++){const i=t[c[u]];n.push({userId:i,frame:{x:e*o,y:l,w:o,h:o},isLocal:i===s,showName:!1}),u++}l+=o}return n}if(1===e)n.push({userId:t[0],frame:{x:0,y:0,w:H,h:K},isLocal:t[0]===s,showName:!1});else if(2===e)n.push({userId:t[0],frame:{x:0,y:0,w:i,h:i},isLocal:t[0]===s,showName:!1}),n.push({userId:t[1],frame:{x:i,y:0,w:i,h:i},isLocal:t[1]===s,showName:!1});else if(3===e)n.push({userId:t[0],frame:{x:0,y:0,w:i,h:i},isLocal:t[0]===s,showName:!1}),n.push({userId:t[1],frame:{x:i,y:0,w:i,h:i},isLocal:t[1]===s,showName:!1}),n.push({userId:t[2],frame:{x:180,y:i,w:i,h:i},isLocal:t[2]===s,showName:!1});else if(4===e)n.push({userId:t[0],frame:{x:0,y:0,w:i,h:i},isLocal:t[0]===s,showName:!1}),n.push({userId:t[1],frame:{x:i,y:0,w:i,h:i},isLocal:t[1]===s,showName:!1}),n.push({userId:t[2],frame:{x:0,y:i,w:i,h:i},isLocal:t[2]===s,showName:!1}),n.push({userId:t[3],frame:{x:i,y:i,w:i,h:i},isLocal:t[3]===s,showName:!1});else{let i=0;for(let r=0;r<e;r+=3){const a=Math.min(3,e-r);for(let e=0;e<a;e++){const a=r+e;n.push({userId:t[a],frame:{x:e*o,y:i,w:o,h:o},isLocal:t[a]===s,showName:!1})}i+=o}}return n}}function z(t){switch(t){case e.LayoutTemplate.FLOAT:return"float";case e.LayoutTemplate.GRID:return"grid";default:return"float"}}function J(){return{template:e.LayoutTemplate.FLOAT,canvas:{w:H,h:K},primaryUser:{userId:"",isLocal:!1},secondaryUser:null,showRemoteInfo:!1}}var Q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function X(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Z,ee={exports:{}},te={},se={exports:{}};var ne,oe,ie={exports:{}};function re(){return ne||(ne=1,function(e){e.exports=function(){function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var s=0;s<t.length;s++){var n=t[s];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function n(e,t,n){return t&&s(e.prototype,t),e}function o(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function i(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,n)}return s}function r(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?i(Object(s),!0).forEach(function(t){o(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):i(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}function a(){var e=(new Date).getTime(),t=new Date(e),s=t.getHours(),n=t.getMinutes(),o=t.getSeconds(),i=t.getMilliseconds();return s=s<10?"0".concat(s):s,n=n<10?"0".concat(n):n,o=o<10?"0".concat(o):o,"".concat(s,":").concat(n,":").concat(o,".").concat(i)}var c="TRTC-WX",u=0,l=1,d=2,h=3,p=new(function(){function e(){t(this,e),this.logLevel=0}return n(e,[{key:"setLogLevel",value:function(e){this.logLevel=e}},{key:"log",value:function(){var e;this.logLevel===u&&(e=console).log.apply(e,[c,a()].concat(Array.prototype.slice.call(arguments)))}},{key:"info",value:function(){var e;this.logLevel<=l&&(e=console).info.apply(e,[c,a()].concat(Array.prototype.slice.call(arguments)))}},{key:"warn",value:function(){var e;this.logLevel<=d&&(e=console).warn.apply(e,[c,a()].concat(Array.prototype.slice.call(arguments)))}},{key:"error",value:function(){var e;this.logLevel<=h&&(e=console).error.apply(e,[c,a()].concat(Array.prototype.slice.call(arguments)))}}]),e}());function g(e){if(!_(e))return null;e.scene=e.scene&&"rtc"!==e.scene?e.scene:"videocall",e.enableBlackStream=e.enableBlackStream||"",e.encsmall=e.encsmall||0,e.cloudenv=e.cloudenv||"PRO",e.streamID=e.streamID||"",e.userDefineRecordID=e.userDefineRecordID||"",e.privateMapKey=e.privateMapKey||"",e.pureAudioMode=e.pureAudioMode||"",e.recvMode=e.recvMode||1,e.enableinfiniteanchor=e.enableinfiniteanchor||0;var t="";return t=e.strRoomID?"&strroomid=".concat(e.strRoomID):"&roomid=".concat(e.roomID),"room://cloud.tencent.com/rtc?sdkappid=".concat(e.sdkAppID).concat(t,"&userid=").concat(e.userID,"&usersig=").concat(e.userSig,"&appscene=").concat(e.scene,"&encsmall=").concat(e.encsmall,"&cloudenv=").concat(e.cloudenv,"&enableBlackStream=").concat(e.enableBlackStream,"&streamid=").concat(e.streamID,"&userdefinerecordid=").concat(e.userDefineRecordID,"&privatemapkey=").concat(e.privateMapKey,"&pureaudiomode=").concat(e.pureAudioMode,"&recvmode=").concat(e.recvMode,"&enableinfiniteanchor=").concat(e.enableinfiniteanchor,"&component=").concat(function(){var e,t;try{e=wx&&wx.TUIScene?wx.TUIScene:wx&&wx.getStorageSync&&wx.getStorageSync("TUIScene")?wx.getStorageSync("TUIScene"):getApp&&getApp()&&getApp().globalData&&getApp().globalData.TUIScene?getApp().globalData.TUIScene:""}catch(t){e="",console.error(t)}if(e&&"number"==typeof(t=Number(e))&&!isNaN(t)&&0<Number(e)&&Number(e)<20)return e;switch(e){case"sampleDemo":return 2;case"TUICalling":return 3;case"TUIRoom":return 5;case"TUIVoiceRoom":return 6;case"TIMCalling":return 10;case"TUICallKit":return 14;case"TIMCallKit":return 15;case"TUIRoomEngine":return 16;case"TUICallEngine":return 17;case"TUIRoomKit":return 18;default:return 1}}())}var _=function(e){var t=/[\u4e00-\u9fa5]/;return e.sdkAppID?void 0===e.roomID&&void 0===e.strRoomID?(p.error("未设置 roomID"),!1):!e.strRoomID&&(e.roomID<1||e.roomID>4294967296)?(p.error("roomID 超出取值范围 1 ~ 4294967295"),!1):e.strRoomID&&t.test(e.strRoomID)?(p.error("strRoomID 请勿使用中文字符"),!1):e.userID?e.userID&&t.test(e.userID)?(p.error("userID 请勿使用中文字符"),!1):!!e.userSig||(p.error("未设置 userSig"),!1):(p.error("未设置 userID"),!1):(p.error("未设置 sdkAppID"),!1)},m={LOCAL_JOIN:"LOCAL_JOIN",LOCAL_LEAVE:"LOCAL_LEAVE",KICKED_OUT:"KICKED_OUT",REMOTE_USER_JOIN:"REMOTE_USER_JOIN",REMOTE_USER_LEAVE:"REMOTE_USER_LEAVE",REMOTE_VIDEO_ADD:"REMOTE_VIDEO_ADD",REMOTE_VIDEO_REMOVE:"REMOTE_VIDEO_REMOVE",REMOTE_AUDIO_ADD:"REMOTE_AUDIO_ADD",REMOTE_AUDIO_REMOVE:"REMOTE_AUDIO_REMOVE",REMOTE_STATE_UPDATE:"REMOTE_STATE_UPDATE",LOCAL_NET_STATE_UPDATE:"LOCAL_NET_STATE_UPDATE",REMOTE_NET_STATE_UPDATE:"REMOTE_NET_STATE_UPDATE",LOCAL_AUDIO_VOLUME_UPDATE:"LOCAL_AUDIO_VOLUME_UPDATE",REMOTE_AUDIO_VOLUME_UPDATE:"REMOTE_AUDIO_VOLUME_UPDATE",VIDEO_FULLSCREEN_UPDATE:"VIDEO_FULLSCREEN_UPDATE",BGM_PLAY_START:"BGM_PLAY_START",BGM_PLAY_FAIL:"BGM_PLAY_FAIL",BGM_PLAY_PROGRESS:"BGM_PLAY_PROGRESS",BGM_PLAY_COMPLETE:"BGM_PLAY_COMPLETE",ERROR:"ERROR",PLAYER_WARNING:"PLAYER_WARNING",IM_READY:"IM_READY",IM_MESSAGE_RECEIVED:"IM_MESSAGE_RECEIVED",IM_NOT_READY:"IM_NOT_READY",IM_KICKED_OUT:"IM_KICKED_OUT",IM_ERROR:"IM_ERROR"},f={url:"",mode:"RTC",autopush:!1,enableCamera:!1,enableMic:!1,enableAgc:!1,enableAns:!1,enableEarMonitor:!1,enableAutoFocus:!0,enableZoom:!1,minBitrate:600,maxBitrate:900,videoWidth:360,videoHeight:640,beautyLevel:0,whitenessLevel:0,videoOrientation:"vertical",videoAspect:"9:16",frontCamera:"front",enableRemoteMirror:!1,localMirror:"auto",enableBackgroundMute:!1,audioQuality:"high",audioVolumeType:"voicecall",audioReverbType:0,waitingImage:"",waitingImageHash:"",beautyStyle:"smooth",filter:"",netStatus:{}},v={src:"",mode:"RTC",autoplay:!0,muteAudio:!1,muteVideo:!1,orientation:"vertical",objectFit:"fillCrop",enableBackgroundMute:!1,minCache:1,maxCache:2,soundMode:"speaker",enableRecvMessage:!1,autoPauseIfNavigate:!0,autoPauseIfOpenNative:!0,isVisible:!0,_definitionType:"main",netStatus:{}};function I(){var e=new Date;return e.setTime((new Date).getTime()+0),e.toLocaleString()}(new Date).getTime();var E=function(e){var t=[];if(e&&e.TUIScene&&t.push(e.TUIScene),e&&"test"===e.env)return"default";if(wx&&wx.TUIScene&&t.push(wx.TUIScene),wx&&"function"==typeof getApp){var s=getApp().globalData;s&&s.TUIScene&&t.push(s.TUIScene)}return wx&&wx.getStorage({key:"TUIScene",success:function(e){t.push(e.data)}}),t[0]||"default"},C=new(function(){function e(){t(this,e),this.sdkAppId="",this.userId="",this.version="",this.common={}}return n(e,[{key:"setConfig",value:function(e){this.sdkAppId="".concat(e.sdkAppId),this.userId="".concat(e.userId),this.version="".concat(e.version),this.common.TUIScene=E(e)}},{key:"log",value:function(e){wx.request({url:"https://yun.tim.qq.com/v5/AVQualityReportSvc/C2S?sdkappid=1&cmdtype=jssdk_log",method:"POST",header:{"content-type":"application/json"},data:{timestamp:I(),sdkAppId:this.sdkAppId,userId:this.userId,version:this.version,log:JSON.stringify(r(r({},e),this.common))}})}}]),e}()),y="enterRoom",S="exitRoom",M="setPusherAttributes",T="setPlayerAttributes",R="init",A="error",O="connectServer",D="startPusher",b="openCamera",L="screenCap",N="pusherResolution",w="pusherCodeRate",P="collectionFirstFrame",G="encoderStart",U="enterRoomSuccess",k="exitRoomSuccess",F="kicked_out",x="renderFirstFrame",V="miniAppHang",$="closeSuspension",q="other",B="update",j="addUser",H="remove_user",K="update_user_video",W="update_user_audio",Y="pusherStart",z="pusherStop",J="pusherPause",Q="pusherResume",X=function(){function s(e,n){t(this,s),this.context=wx.createLivePusherContext(n),this.pusherAttributes={},Object.assign(this.pusherAttributes,f,e)}return n(s,[{key:"setPusherAttributes",value:function(e){return Object.assign(this.pusherAttributes,e),this.pusherAttributes}},{key:"start",value:function(e){p.log("[apiLog][pusherStart]"),C.log({name:Y,options:e}),this.context.start(e)}},{key:"stop",value:function(e){p.log("[apiLog][pusherStop]"),C.log({name:z,options:e}),this.context.stop(e)}},{key:"pause",value:function(e){p.log("[apiLog] pusherPause()"),C.log({name:J,options:e}),this.context.pause(e)}},{key:"resume",value:function(e){p.log("[apiLog][pusherResume]"),C.log({name:Q,options:e}),this.context.resume(e)}},{key:"switchCamera",value:function(e){return p.log("[apiLog][switchCamera]"),this.pusherAttributes.frontCamera="front"===this.pusherAttributes.frontCamera?"back":"front",this.context.switchCamera(e),this.pusherAttributes}},{key:"sendMessage",value:function(e){p.log("[apiLog][sendMessage]",e.msg),this.context.sendMessage(e)}},{key:"snapshot",value:function(){var e=this;return p.log("[apiLog][pusherSnapshot]"),new Promise(function(t,s){e.context.snapshot({quality:"raw",complete:function(e){e.tempImagePath?(wx.saveImageToPhotosAlbum({filePath:e.tempImagePath,success:function(s){t(e)},fail:function(e){p.error("[error] pusher截图失败: ",e),s(new Error("截图失败"))}}),t(e)):(p.error("[error] snapShot 回调失败",e),s(new Error("截图失败")))}})})}},{key:"toggleTorch",value:function(e){this.context.toggleTorch(e)}},{key:"startDumpAudio",value:function(e){this.context.startDumpAudio(e)}},{key:"stopDumpAudio",value:function(e){this.context.startDumpAudio(e)}},{key:"playBGM",value:function(e){p.log("[apiLog] playBGM() url: ",e.url),this.context.playBGM(e)}},{key:"pauseBGM",value:function(e){p.log("[apiLog] pauseBGM()"),this.context.pauseBGM(e)}},{key:"resumeBGM",value:function(e){p.log("[apiLog] resumeBGM()"),this.context.resumeBGM(e)}},{key:"stopBGM",value:function(e){p.log("[apiLog] stopBGM()"),this.context.stopBGM(e)}},{key:"setBGMVolume",value:function(t){p.log("[apiLog] setBGMVolume() volume:",t),t&&t.volume&&"object"===e(t.volume)&&t.volume.volume?this.context.setBGMVolume(t.volume):this.context.setBGMVolume(t)}},{key:"setMICVolume",value:function(t){p.log("[apiLog] setMICVolume() volume:",t),t&&t.volume&&"object"===e(t.volume)&&t.volume.volume?this.context.setMICVolume(t.volume):this.context.setMICVolume(t)}},{key:"startPreview",value:function(e){p.log("[apiLog] startPreview()"),this.context.startPreview(e)}},{key:"stopPreview",value:function(e){p.log("[apiLog] stopPreview()"),this.context.stopPreview(e)}},{key:"reset",value:function(){return console.log("Pusher reset",this.context),this.pusherAttributes={},this.context&&(this.stop({success:function(){console.log("Pusher context.stop()")}}),this.context=null),this.pusherAttributes}}]),s}(),Z=function e(s){t(this,e),Object.assign(this,{userID:"",streams:{}},s)},ee=function(){function e(s,n){t(this,e),this.ctx=n,this.playerAttributes=this.getInitPlayerAttributes(s)}return n(e,[{key:"play",value:function(e){this.getPlayerContext().play(e)}},{key:"stop",value:function(e){this.getPlayerContext().stop(e)}},{key:"mute",value:function(e){this.getPlayerContext().mute(e)}},{key:"pause",value:function(e){this.getPlayerContext().pause(e)}},{key:"resume",value:function(e){this.getPlayerContext().resume(e)}},{key:"requestFullScreen",value:function(e){var t=this;return new Promise(function(s,n){t.getPlayerContext().requestFullScreen({direction:e.direction,success:function(e){s(e)},fail:function(e){n(e)}})})}},{key:"requestExitFullScreen",value:function(){var e=this;return new Promise(function(t,s){e.getPlayerContext().exitFullScreen({success:function(e){t(e)},fail:function(e){s(e)}})})}},{key:"snapshot",value:function(e){var t=this;return p.log("[playerSnapshot]",e),new Promise(function(e,s){t.getPlayerContext().snapshot({quality:"raw",complete:function(t){t.tempImagePath?(wx.saveImageToPhotosAlbum({filePath:t.tempImagePath,success:function(s){p.log("save photo is success",s),e(t)},fail:function(e){p.error("save photo is fail",e),s(e)}}),e(t)):(p.error("snapShot 回调失败",t),s(new Error("截图失败")))}})})}},{key:"setPlayerAttributes",value:function(e){this.playerAttributes=Object.assign({},this.playerAttributes,e)}},{key:"getPlayerContext",value:function(){return this.playerContext||(this.playerContext=wx.createLivePlayerContext(this.playerAttributes.id,this.ctx)),this.playerContext}},{key:"reset",value:function(){this.playerContext&&(this.playerContext.stop(),this.playerContext=void 0),this.playerAttributes=this.getInitPlayerAttributes()}},{key:"getInitPlayerAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.assign({},v,{userID:"",streamType:"",streamID:"",id:"",hasVideo:!1,hasAudio:!1,volume:0,playerContext:void 0},e)}}]),e}(),te="UserController",se=function(){function e(s,n){t(this,e),this.ctx=n,this.userMap=new Map,this.userList=[],this.streamList=[],this.emitter=s,this.rtcConfig={}}return n(e,[{key:"setRtcConfig",value:function(e){this.rtcConfig=e||{}}},{key:"userEventHandler",value:function(e){var t=e.detail.code,s=e.detail.message,n={name:q,code:t,message:s,data:""};switch(t){case 0:p.log(s,t);break;case 1001:p.log("已经连接推流服务器",t),n.name=O;break;case 1002:p.log("已经与服务器握手完毕,开始推流",t),n.name=D;break;case 1003:p.log("打开摄像头成功",t),n.name=b;break;case 1004:p.log("录屏启动成功",t),n.name=L;break;case 1005:p.log("推流动态调整分辨率",t),n.name=N;break;case 1006:p.log("推流动态调整码率",t),n.name=w;break;case 1007:p.log("首帧画面采集完成",t),n.name=P;break;case 1008:p.log("编码器启动",t),n.name=G;break;case 1018:p.log("进房成功",t),n.name=U,n.data="event enterRoom success",this.emitter.emit(m.LOCAL_JOIN);break;case 1019:p.log("退出房间",t,s),s.indexOf("reason[0]")>-1?(n.name=k,n.data="event exitRoom success"):(n.name=F,n.data="event abnormal exitRoom",this.emitter.emit(m.KICKED_OUT));break;case 2003:p.log("渲染首帧视频",t),n.name=x;break;case-1301:p.error("打开摄像头失败: ",t),n.name=A,n.data="event start camera failed",this.emitter.emit(m.ERROR,{code:t,message:s});break;case-1302:n.name=A,n.data="event start microphone failed",p.error("打开麦克风失败: ",t),this.emitter.emit(m.ERROR,{code:t,message:s});break;case-1303:p.error("视频编码失败: ",t),n.name=A,n.data="event video encode failed",this.emitter.emit(m.ERROR,{code:t,message:s});break;case-1304:p.error("音频编码失败: ",t),n.name=A,n.data="event audio encode failed",this.emitter.emit(m.ERROR,{code:t,message:s});break;case-1307:p.error("推流连接断开: ",t),n.name=A,n.data="event pusher stream failed",this.emitter.emit(m.ERROR,{code:t,message:s});break;case-100018:p.error("进房失败: userSig 校验失败,请检查 userSig 是否填写正确",t,s),n.name=A,n.data="event userSig is error",this.emitter.emit(m.ERROR,{code:t,message:s});break;case-3301:p.error("进房失败: ",t),n.name=A,n.data="enter room failed",this.emitter.emit(m.ERROR,{code:t,message:s});break;case 5e3:p.log("小程序被挂起: ",t),n.name=V,n.data="miniApp is hang";break;case 5001:p.log("小程序悬浮窗被关闭: ",t),n.name=$;break;case 1021:p.log("网络类型发生变化,需要重新进房",t);break;case 2007:p.log("本地视频播放loading: ",t);break;case 2004:p.log("本地视频播放开始: ",t);break;case 1031:case 1032:case 1033:case 1034:this._handleUserEvent(e)}C.log(n)}},{key:"_handleUserEvent",value:function(e){var t,s=e.detail.code,n=e.detail.message;if(!e.detail.message||"string"!=typeof n)return p.warn(te,"userEventHandler 数据格式错误"),!1;try{t=JSON.parse(e.detail.message)}catch(e){return p.warn(te,"userEventHandler 数据格式错误",e),!1}switch(this.emitter.emit(m.LOCAL_STATE_UPDATE,e),C.log({name:B,code:s,message:n,data:t}),s){case 1031:this.addUser(t);break;case 1032:this.removeUser(t);break;case 1033:this.updateUserVideo(t);break;case 1034:this.updateUserAudio(t)}}},{key:"addUser",value:function(e){var t=this,s=e.userlist;Array.isArray(s)&&s.length>0&&s.forEach(function(e){var s=e.userid,n=t.getUser(s);n||(n=new Z({userID:s}),t.userList.push({userID:s})),t.userMap.set(s,n),t.emitter.emit(m.REMOTE_USER_JOIN,{userID:s,userList:t.userList,playerList:t.getPlayerList()}),C.log({name:j,userID:s,userList:t.userList,playerList:t.getPlayerList()})})}},{key:"removeUser",value:function(e){var t=this,s=e.userlist;Array.isArray(s)&&s.length>0&&s.forEach(function(e){var s=e.userid,n=t.getUser(s);if(n&&n.streams){if(n.streams){var o,i,r=null===(o=n.streams)||void 0===o?void 0:o.main,a=null===(i=n.streams)||void 0===i?void 0:i.aux,c=function(e){var s,n;null!=e&&null!==(s=e.playerAttributes)&&void 0!==s&&s.hasVideo&&t.emitter.emit(m.REMOTE_VIDEO_REMOVE,{player:e.playerAttributes,userList:t.userList,playerList:t.getPlayerList()}),null!=e&&null!==(n=e.playerAttributes)&&void 0!==n&&n.hasAudio&&t.emitter.emit(m.REMOTE_AUDIO_REMOVE,{player:e.playerAttributes,userList:t.userList,playerList:t.getPlayerList()})};c(r),c(a)}t._removeUserAndStream(s),n.streams.main&&n.streams.main.reset(),n.streams.aux&&n.streams.aux.reset(),t.emitter.emit(m.REMOTE_USER_LEAVE,{userID:s,userList:t.userList,playerList:t.getPlayerList()}),C.log({name:H,userID:s,userList:t.userList,playerList:t.getPlayerList()}),n=void 0,t.userMap.delete(s)}})}},{key:"updateUserVideo",value:function(e){var t=this;p.log(te,"updateUserVideo",e);var s=e.userlist;Array.isArray(s)&&s.length>0&&s.forEach(function(e){var s=e.userid,n=e.streamtype,o="".concat(s,"_").concat(n),i=o,r=e.hasvideo,a=e.playurl,c=t.getUser(s);if(c){var u=c.streams[n];p.log(te,"updateUserVideo start",c,n,u),u?(u.setPlayerAttributes({hasVideo:r}),r||u.playerAttributes.hasAudio||t._removeStream(u)):(u=new ee({userID:s,streamID:o,hasVideo:r,src:a,streamType:n,id:i},t.ctx),c.streams[n]=u,t._addStream(u)),"aux"===n&&(r?(u.setPlayerAttributes({objectFit:"contain",muteAudio:!1}),t._addStream(u)):t._removeStream(u)),t.userList.find(function(e){if(e.userID===s)return e["has".concat(n.replace(/^\S/,function(e){return e.toUpperCase()}),"Video")]=r,!0}),p.log(te,"updateUserVideo end",c,n,u);var l=r?m.REMOTE_VIDEO_ADD:m.REMOTE_VIDEO_REMOVE;t.emitter.emit(l,{player:u.playerAttributes,userList:t.userList,playerList:t.getPlayerList()}),C.log({name:K,player:u.playerAttributes,userList:t.userList,playerList:t.getPlayerList()})}})}},{key:"updateUserAudio",value:function(e){var t=this,s=e.userlist;Array.isArray(s)&&s.length>0&&s.forEach(function(e){var s=e.userid,n="main",o="".concat(s,"_").concat(n),i=o,r=e.hasaudio,a=e.playurl,c=t.getUser(s);if(c){var u=c.streams.main;u?(u.setPlayerAttributes({hasAudio:r}),r||u.playerAttributes.hasVideo||t._removeStream(u)):(u=new ee({userID:s,streamID:o,hasAudio:r,src:a,streamType:n,id:i},t.ctx),c.streams.main=u,t._addStream(u)),t.userList.find(function(e){if(e.userID===s)return e["has".concat(n.replace(/^\S/,function(e){return e.toUpperCase()}),"Audio")]=r,!0});var l=r?m.REMOTE_AUDIO_ADD:m.REMOTE_AUDIO_REMOVE;t.emitter.emit(l,{player:u.playerAttributes,userList:t.userList,playerList:t.getPlayerList()}),C.log({name:W,player:u.playerAttributes,userList:t.userList,playerList:t.getPlayerList()})}})}},{key:"getUser",value:function(e){return this.userMap.get(e)}},{key:"getStream",value:function(e){var t=e.userID,s=e.streamType,n=this.userMap.get(t);if(n)return n.streams[s];if(1!==this.rtcConfig.enableinfiniteanchor)return null;var o=new Z({userID:t});this.userList.push({userID:t}),this.userMap.set(t,o);var i=new ee({userID:t,streamID:"".concat(t,"_").concat(s),src:"room://cloud.tencent.com/rtc?userid=".concat(t,"&streamtype=").concat(s),streamType:s,id:"".concat(t,"_").concat(s)},this.ctx);return o.streams[s]=i,this._addStream(i),i}},{key:"getUserList",value:function(){return this.userList}},{key:"getStreamList",value:function(){return this.streamList}},{key:"getPlayerList",value:function(){return this.getStreamList().map(function(e){return Object.assign({},e.playerAttributes)})}},{key:"reset",value:function(){return this.streamList.forEach(function(e){e.reset()}),this.streamList=[],this.userList=[],this.userMap.clear(),{userList:this.userList,streamList:this.streamList}}},{key:"_removeUserAndStream",value:function(e){this.streamList=this.streamList.filter(function(t){return t.playerAttributes.userID!==e&&""!==t.playerAttributes.userID}),this.userList=this.userList.filter(function(t){return t.userID!==e})}},{key:"_addStream",value:function(e){-1===this.streamList.findIndex(function(t){return t.playerAttributes.userID===e.playerAttributes.userID&&t.playerAttributes.streamType===e.playerAttributes.streamType})&&this.streamList.push(e)}},{key:"_removeStream",value:function(e){this.streamList=this.streamList.filter(function(t){return t.playerAttributes.userID!==e.playerAttributes.userID||t.playerAttributes.streamType!==e.playerAttributes.streamType}),this.getUser(e.playerAttributes.userID).streams[e.playerAttributes.streamType]=void 0}}]),e}(),ne=function(){function e(){t(this,e)}return n(e,[{key:"on",value:function(e,t,s){"function"==typeof t?(this._stores=this._stores||{},(this._stores[e]=this._stores[e]||[]).push({cb:t,ctx:s})):console.error("listener must be a function")}},{key:"emit",value:function(e){this._stores=this._stores||{};var t,s=this._stores[e];if(s){s=s.slice(0),(t=[].slice.call(arguments,1))[0]={eventCode:e,data:t[0]};for(var n=0,o=s.length;n<o;n++)s[n].cb.apply(s[n].ctx,t)}}},{key:"off",value:function(e,t){if(this._stores=this._stores||{},arguments.length){var s=this._stores[e];if(s)if(1!==arguments.length){for(var n=0,o=s.length;n<o;n++)if(s[n].cb===t){s.splice(n,1);break}}else delete this._stores[e]}else this._stores={}}}]),e}();return p.info("[version] trtc-wx loaded, version: ".concat('"1.1.15"')),function(){function e(s,n){var o=this;t(this,e),this.env="prod",this.ctx=s,this.eventEmitter=new ne,this.pusherInstance=null,this.userController=new se(this.eventEmitter,this.ctx),this.EVENT=m,this.TUIScene=null==n?void 0:n.TUIScene,"test"!==(null==n?void 0:n.env)?wx.getSystemInfo({success:function(e){return o.systemInfo=e}}):(this.env="test",C.log=function(){},p.log=function(){},p.warn=function(){})}return n(e,[{key:"initLog",value:function(e){C.setConfig({sdkAppId:e.sdkAppID,userId:e.userID,version:"wechat-mini",TUIScene:this.TUIScene,env:this.env})}},{key:"setLogLevel",value:function(e){p.setLogLevel(e)}},{key:"on",value:function(e,t,s){p.log("[on] 事件订阅: ".concat(e)),this.eventEmitter.on(e,t,s)}},{key:"off",value:function(e,t){p.log("[off] 取消订阅: ".concat(e)),this.eventEmitter.off(e,t)}},{key:"createPusher",value:function(e){return this.pusherInstance=new X(e,this.ctx),p.log("pusherInstance",this.pusherInstance),this.pusherInstance}},{key:"getPusherInstance",value:function(){return this.pusherInstance}},{key:"enterRoom",value:function(e){p.log("[apiLog] [enterRoom]",e);var t=g(e);return this.initLog(r(r({},e),{},{env:this.env})),this.userController.setRtcConfig(e),C.log({name:R}),t||(this.eventEmitter.emit(m.ERROR,{message:"进房参数错误"}),C.log({name:A,message:"进房参数错误",data:e})),this.pusherInstance.setPusherAttributes(r(r({},e),{},{url:t})),p.warn("[statusLog] [enterRoom]",this.pusherInstance.pusherAttributes),C.log({name:y,pusherConfig:this.pusherInstance.pusherAttributes}),this.getPusherAttributes()}},{key:"exitRoom",value:function(){this.userController.reset();var e=Object.assign({pusher:this.pusherInstance.reset()},{playerList:this.userController.getPlayerList()});return this.eventEmitter.emit(m.LOCAL_LEAVE),C.log({name:S,data:e}),e}},{key:"getPlayerList",value:function(){var e=this.userController.getPlayerList();return p.log("[apiLog][getPlayerList]",e),e}},{key:"setPusherAttributes",value:function(e){return p.log("[apiLog] [setPusherAttributes], ",e),this.pusherInstance.setPusherAttributes(e),p.warn("[statusLog] [setPusherAttributes]",this.pusherInstance.pusherAttributes),C.log({name:M,options:e,pusherConfig:this.pusherInstance.pusherAttributes}),this.pusherInstance.pusherAttributes}},{key:"getPusherAttributes",value:function(){return p.log("[apiLog] [getPusherConfig]"),this.pusherInstance.pusherAttributes}},{key:"setPlayerAttributes",value:function(e,t){p.log("[apiLog] [setPlayerAttributes] id",e,"options: ",t);var s=this._transformStreamID(e),n=s.userID,o=s.streamType,i=this.userController.getStream({userID:n,streamType:o});return i?(i.setPlayerAttributes(t),C.log({name:T,id:e,options:t,playerList:this.getPlayerList()}),this.getPlayerList()):this.getPlayerList()}},{key:"getPlayerInstance",value:function(e){var t=this._transformStreamID(e),s=t.userID,n=t.streamType;return p.log("[api][getPlayerInstance] id:",e),this.userController.getStream({userID:s,streamType:n})}},{key:"switchStreamType",value:function(e){p.log("[apiLog] [switchStreamType] id: ",e);var t=this._transformStreamID(e),s=t.userID,n=t.streamType,o=this.userController.getStream({userID:s,streamType:n});if(!o)return p.warn("[switchStreamType] stream not found for userID:",s,"streamType:",n),this.getPlayerList();var i=o.playerAttributes;return"main"===i._definitionType?(i.src=i.src.replace("main","small"),i._definitionType="small"):(i.src=i.src.replace("small","main"),i._definitionType="main"),this.getPlayerList()}},{key:"pusherEventHandler",value:function(e){this.userController.userEventHandler(e)}},{key:"pusherNetStatusHandler",value:function(e){var t=e.detail.info;this.pusherInstance.setPusherAttributes(r({netStatus:t},t)),this.eventEmitter.emit(m.LOCAL_NET_STATE_UPDATE,{pusher:this.pusherInstance.pusherAttributes})}},{key:"pusherErrorHandler",value:function(e){try{var t=e.detail.errCode,s=e.detail.errMsg;this.eventEmitter.emit(m.ERROR,{code:t,message:s}),C.log({name:A,code:t,message:s})}catch(t){p.error("pusher error data parser exception",e,t)}}},{key:"pusherBGMStartHandler",value:function(e){this.eventEmitter.emit(m.BGM_PLAY_START)}},{key:"pusherBGMProgressHandler",value:function(e){var t,s;this.eventEmitter.emit(m.BGM_PLAY_PROGRESS,{progress:null===(t=e.detail)||void 0===t?void 0:t.progress,duration:null===(s=e.detail)||void 0===s?void 0:s.duration})}},{key:"pusherBGMCompleteHandler",value:function(e){this.eventEmitter.emit(m.BGM_PLAY_COMPLETE)}},{key:"pusherAudioVolumeNotify",value:function(e){this.pusherInstance.pusherAttributes.volume=e.detail.volume,this.eventEmitter.emit(m.LOCAL_AUDIO_VOLUME_UPDATE,{pusher:this.pusherInstance.pusherAttributes})}},{key:"playerEventHandler",value:function(e){switch(p.log("[statusLog][playerStateChange]",e),e.detail.code){case 6002:case 6003:case 6004:case 6005:this.eventEmitter.emit(m.PLAYER_WARNING,e.detail);break;default:this.eventEmitter.emit(m.REMOTE_STATE_UPDATE,e.detail)}}},{key:"playerFullscreenChange",value:function(e){this.eventEmitter.emit(m.VIDEO_FULLSCREEN_UPDATE)}},{key:"playerNetStatus",value:function(e){var t=this._transformStreamID(e.currentTarget.dataset.streamid),s=t.userID,n=t.streamType,o=this.userController.getStream({userID:s,streamType:n});!o||o.videoWidth===e.detail.info.videoWidth&&o.videoHeight===e.detail.info.videoHeight||(o.setPlayerAttributes({netStatus:e.detail.info}),this.eventEmitter.emit(m.REMOTE_NET_STATE_UPDATE,{playerList:this.userController.getPlayerList()}))}},{key:"playerAudioVolumeNotify",value:function(e){try{var t=this._transformStreamID(e.currentTarget.dataset.streamid),s=t.userID,n=t.streamType,o=this.userController.getStream({userID:s,streamType:n});if(!o)return;var i=e.detail.volume;o.setPlayerAttributes({volume:i}),this.eventEmitter.emit(m.REMOTE_AUDIO_VOLUME_UPDATE,{playerList:this.userController.getPlayerList()})}catch(e){console.warn(e)}}},{key:"_transformStreamID",value:function(e){try{var t=e.lastIndexOf("_");return{userID:e.slice(0,t),streamType:e.slice(t+1)}}catch(t){throw p.error("transformStreamID error: streamID = ".concat(e,", error = ").concat(t)),t}}}]),e}()}()}(ie)),ie.exports}function ae(){return oe||(oe=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});var t,s,n,o,i,r,a,c,u,l,d,h,p=(Z||(Z=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function n(){}function o(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function i(e,t,n,i,r){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new o(n,i||e,r),c=s?s+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function r(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(s=!1)),a.prototype.eventNames=function(){var e,n,o=[];if(0===this._eventsCount)return o;for(n in e=this._events)t.call(e,n)&&o.push(s?n.slice(1):n);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=s?s+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,r=new Array(i);o<i;o++)r[o]=n[o].fn;return r},a.prototype.listenerCount=function(e){var t=s?s+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,o,i,r){var a=s?s+e:e;if(!this._events[a])return!1;var c,u,l=this._events[a],d=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),d){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,n),!0;case 4:return l.fn.call(l.context,t,n,o),!0;case 5:return l.fn.call(l.context,t,n,o,i),!0;case 6:return l.fn.call(l.context,t,n,o,i,r),!0}for(u=1,c=new Array(d-1);u<d;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var h,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),d){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,n);break;case 4:l[u].fn.call(l[u].context,t,n,o);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(e,t,s){return i(this,e,t,s,!1)},a.prototype.once=function(e,t,s){return i(this,e,t,s,!0)},a.prototype.removeListener=function(e,t,n,o){var i=s?s+e:e;if(!this._events[i])return this;if(!t)return r(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||o&&!a.once||n&&a.context!==n||r(this,i);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||o&&!a[c].once||n&&a[c].context!==n)&&u.push(a[c]);u.length?this._events[i]=1===u.length?u[0]:u:r(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&r(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=s,a.EventEmitter=a,e.exports=a}(se)),se.exports),g=re();function _(){_=function(){return e};var e={},t=Object.prototype,s=t.hasOwnProperty,n=Object.defineProperty||function(e,t,s){e[t]=s.value},o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",r=o.asyncIterator||"@@asyncIterator",a=o.toStringTag||"@@toStringTag";function c(e,t,s){return Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,s){return e[t]=s}}function u(e,t,s,o){var i=t&&t.prototype instanceof h?t:h,r=Object.create(i.prototype),a=new R(o||[]);return n(r,"_invoke",{value:y(e,s,a)}),r}function l(e,t,s){try{return{type:"normal",arg:e.call(t,s)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var d={};function h(){}function p(){}function g(){}var m={};c(m,i,function(){return this});var f=Object.getPrototypeOf,v=f&&f(f(A([])));v&&v!==t&&s.call(v,i)&&(m=v);var I=g.prototype=h.prototype=Object.create(m);function E(e){["next","throw","return"].forEach(function(t){c(e,t,function(e){return this._invoke(t,e)})})}function C(e,t){function o(n,i,r,a){var c=l(e[n],e,i);if("throw"!==c.type){var u=c.arg,d=u.value;return d&&"object"==typeof d&&s.call(d,"__await")?t.resolve(d.__await).then(function(e){o("next",e,r,a)},function(e){o("throw",e,r,a)}):t.resolve(d).then(function(e){u.value=e,r(u)},function(e){return o("throw",e,r,a)})}a(c.arg)}var i;n(this,"_invoke",{value:function(e,s){function n(){return new t(function(t,n){o(e,s,t,n)})}return i=i?i.then(n,n):n()}})}function y(e,t,s){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return O()}for(s.method=o,s.arg=i;;){var r=s.delegate;if(r){var a=S(r,s);if(a){if(a===d)continue;return a}}if("next"===s.method)s.sent=s._sent=s.arg;else if("throw"===s.method){if("suspendedStart"===n)throw n="completed",s.arg;s.dispatchException(s.arg)}else"return"===s.method&&s.abrupt("return",s.arg);n="executing";var c=l(e,t,s);if("normal"===c.type){if(n=s.done?"completed":"suspendedYield",c.arg===d)continue;return{value:c.arg,done:s.done}}"throw"===c.type&&(n="completed",s.method="throw",s.arg=c.arg)}}}function S(e,t){var s=t.method,n=e.iterator[s];if(void 0===n)return t.delegate=null,"throw"===s&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==s&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+s+"' method")),d;var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,d;var i=o.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,d):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,d)}function M(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(M,this),this.reset(!0)}function A(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,o=function t(){for(;++n<e.length;)if(s.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return o.next=o}}return{next:O}}function O(){return{value:void 0,done:!0}}return p.prototype=g,n(I,"constructor",{value:g,configurable:!0}),n(g,"constructor",{value:p,configurable:!0}),p.displayName=c(g,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===p||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,c(e,a,"GeneratorFunction")),e.prototype=Object.create(I),e},e.awrap=function(e){return{__await:e}},E(C.prototype),c(C.prototype,r,function(){return this}),e.AsyncIterator=C,e.async=function(t,s,n,o,i){void 0===i&&(i=Promise);var r=new C(u(t,s,n,o),i);return e.isGeneratorFunction(s)?r:r.next().then(function(e){return e.done?e.value:r.next()})},E(I),c(I,a,"Generator"),c(I,i,function(){return this}),c(I,"toString",function(){return"[object Generator]"}),e.keys=function(e){var t=Object(e),s=[];for(var n in t)s.push(n);return s.reverse(),function e(){for(;s.length;){var n=s.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=A,R.prototype={constructor:R,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!e)for(var t in this)"t"===t.charAt(0)&&s.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(s,n){return r.type="throw",r.arg=e,t.next=s,n&&(t.method="next",t.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],r=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=s.call(i,"catchLoc"),c=s.call(i,"finallyLoc");if(a&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&s.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var r=i?i.completion:{};return r.type=e,r.arg=t,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(r)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),d},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var s=this.tryEntries[t];if(s.finallyLoc===e)return this.complete(s.completion,s.afterLoc),T(s),d}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var s=this.tryEntries[t];if(s.tryLoc===e){var n=s.completion;if("throw"===n.type){var o=n.arg;T(s)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,s){return this.delegate={iterator:A(e),resultName:t,nextLoc:s},"next"===this.method&&(this.arg=void 0),d}},e}function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function f(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var s=0;s<t.length;s++){var n=t[s];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,R(n.key),n)}}function I(e,t,s){return t&&v(e.prototype,t),s&&v(e,s),Object.defineProperty(e,"prototype",{writable:!1}),e}function E(e,t,s){return(t=R(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function C(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var n,o,i,r,a=[],c=!0,u=!1;try{if(i=(s=s.call(e)).next,0===t);else for(;!(c=(n=i.call(s)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){u=!0,o=e}finally{try{if(!c&&null!=s.return&&(r=s.return(),Object(r)!==r))return}finally{if(u)throw o}}return a}}(e,t)||S(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(e){return function(e){if(Array.isArray(e))return M(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||S(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function S(e,t){if(e){if("string"==typeof e)return M(e,t);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?M(e,t):void 0}}function M(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,n=new Array(t);s<t;s++)n[s]=e[s];return n}function T(e,t){var s="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!s){if(Array.isArray(e)||(s=S(e))||t){s&&(e=s);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,r=!0,a=!1;return{s:function(){s=s.call(e)},n:function(){var e=s.next();return r=e.done,e},e:function(e){a=!0,i=e},f:function(){try{r||null==s.return||s.return()}finally{if(a)throw i}}}}function R(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var n=s.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}function A(e,t,s,n){return new(s||(s=Promise))(function(t,o){function i(e){try{a(n.next(e))}catch(e){o(e)}}function r(e){try{a(n.throw(e))}catch(e){o(e)}}function a(e){var n;e.done?t(e.value):(n=e.value,n instanceof s?n:new s(function(e){e(n)})).then(i,r)}a((n=n.apply(e,[])).next())})}"function"==typeof SuppressedError&&SuppressedError,e.TRTCAppScene=void 0,(t=e.TRTCAppScene||(e.TRTCAppScene={}))[t.TRTCAppSceneVideoCall=0]="TRTCAppSceneVideoCall",t[t.TRTCAppSceneLIVE=1]="TRTCAppSceneLIVE",t[t.TRTCAppSceneAudioCall=2]="TRTCAppSceneAudioCall",t[t.TRTCAppSceneVoiceChatRoom=3]="TRTCAppSceneVoiceChatRoom",e.TRTCRoleType=void 0,(s=e.TRTCRoleType||(e.TRTCRoleType={}))[s.TRTCRoleAnchor=20]="TRTCRoleAnchor",s[s.TRTCRoleAudience=21]="TRTCRoleAudience",e.TRTCVideoStreamType=void 0,(n=e.TRTCVideoStreamType||(e.TRTCVideoStreamType={}))[n.TRTCVideoStreamTypeBig=0]="TRTCVideoStreamTypeBig",n[n.TRTCVideoStreamTypeSmall=1]="TRTCVideoStreamTypeSmall",n[n.TRTCVideoStreamTypeSub=2]="TRTCVideoStreamTypeSub",e.TRTCVideoResolution=void 0,(o=e.TRTCVideoResolution||(e.TRTCVideoResolution={}))[o.TRTCVideoResolution_120_120=1]="TRTCVideoResolution_120_120",o[o.TRTCVideoResolution_160_160=3]="TRTCVideoResolution_160_160",o[o.TRTCVideoResolution_270_270=5]="TRTCVideoResolution_270_270",o[o.TRTCVideoResolution_480_480=7]="TRTCVideoResolution_480_480",o[o.TRTCVideoResolution_160_120=50]="TRTCVideoResolution_160_120",o[o.TRTCVideoResolution_240_180=52]="TRTCVideoResolution_240_180",o[o.TRTCVideoResolution_280_210=54]="TRTCVideoResolution_280_210",o[o.TRTCVideoResolution_320_240=56]="TRTCVideoResolution_320_240",o[o.TRTCVideoResolution_400_300=58]="TRTCVideoResolution_400_300",o[o.TRTCVideoResolution_480_360=60]="TRTCVideoResolution_480_360",o[o.TRTCVideoResolution_640_480=62]="TRTCVideoResolution_640_480",o[o.TRTCVideoResolution_960_720=64]="TRTCVideoResolution_960_720",o[o.TRTCVideoResolution_160_90=100]="TRTCVideoResolution_160_90",o[o.TRTCVideoResolution_256_144=102]="TRTCVideoResolution_256_144",o[o.TRTCVideoResolution_320_180=104]="TRTCVideoResolution_320_180",o[o.TRTCVideoResolution_480_270=106]="TRTCVideoResolution_480_270",o[o.TRTCVideoResolution_640_360=108]="TRTCVideoResolution_640_360",o[o.TRTCVideoResolution_960_540=110]="TRTCVideoResolution_960_540",o[o.TRTCVideoResolution_1280_720=112]="TRTCVideoResolution_1280_720",o[o.TRTCVideoResolution_1920_1080=114]="TRTCVideoResolution_1920_1080",e.TRTCVideoResolutionMode=void 0,(i=e.TRTCVideoResolutionMode||(e.TRTCVideoResolutionMode={}))[i.TRTCVideoResolutionModeLandscape=0]="TRTCVideoResolutionModeLandscape",i[i.TRTCVideoResolutionModePortrait=1]="TRTCVideoResolutionModePortrait",e.TRTCVideoRotation=void 0,(r=e.TRTCVideoRotation||(e.TRTCVideoRotation={}))[r.TRTCVideoRotation0=0]="TRTCVideoRotation0",r[r.TRTCVideoRotation90=1]="TRTCVideoRotation90",r[r.TRTCVideoRotation180=2]="TRTCVideoRotation180",r[r.TRTCVideoRotation270=3]="TRTCVideoRotation270",e.TRTCVideoFillMode=void 0,(a=e.TRTCVideoFillMode||(e.TRTCVideoFillMode={}))[a.TRTCVideoFillMode_Fill=0]="TRTCVideoFillMode_Fill",a[a.TRTCVideoFillMode_Fit=1]="TRTCVideoFillMode_Fit",e.TRTCVideoMirrorType=void 0,(c=e.TRTCVideoMirrorType||(e.TRTCVideoMirrorType={}))[c.TRTCVideoMirrorType_Auto=0]="TRTCVideoMirrorType_Auto",c[c.TRTCVideoMirrorType_Enable=1]="TRTCVideoMirrorType_Enable",c[c.TRTCVideoMirrorType_Disable=2]="TRTCVideoMirrorType_Disable",e.TRTCAudioQuality=void 0,(u=e.TRTCAudioQuality||(e.TRTCAudioQuality={}))[u.TRTCAudioQualitySpeech=1]="TRTCAudioQualitySpeech",u[u.TRTCAudioQualityDefault=2]="TRTCAudioQualityDefault",u[u.TRTCAudioQualityMusic=3]="TRTCAudioQualityMusic",e.TRTCBeautyStyle=void 0,(l=e.TRTCBeautyStyle||(e.TRTCBeautyStyle={}))[l.TRTCBeautyStyleSmooth=0]="TRTCBeautyStyleSmooth",l[l.TRTCBeautyStyleNature=1]="TRTCBeautyStyleNature",e.TRTCAudioRoute=void 0,(d=e.TRTCAudioRoute||(e.TRTCAudioRoute={}))[d.TRTC_AUDIO_ROUTE_SPEAKER=0]="TRTC_AUDIO_ROUTE_SPEAKER",d[d.TRTC_AUDIO_ROUTE_EARPIECE=1]="TRTC_AUDIO_ROUTE_EARPIECE",function(e){e.setPusher="setPusher",e.setPlayer="setPlayer"}(h||(h={}));var O,D,b={enterRoom:{priority:0,type:h.setPusher},switchRole:{priority:1,type:h.setPusher},startLocalPreview:{priority:0,type:h.setPusher},stopLocalPreview:{priority:0,type:h.setPusher},muteLocalVideo:{priority:1,type:h.setPusher},setVideoEncoderParam:{priority:0,type:h.setPusher},setLocalRenderParams:{priority:0,type:h.setPusher},startLocalAudio:{priority:0,type:h.setPusher},stopLocalAudio:{priority:0,type:h.setPusher},muteLocalAudio:{priority:1,type:h.setPusher},switchCamera:{priority:0,type:h.setPusher},setBeautyStyle:{priority:0,type:h.setPusher},exitRoom:{priority:9,type:h.setPusher},startRemoteView:{priority:0,type:h.setPlayer},updateRemoteView:{priority:0,type:h.setPlayer},stopAllRemoteView:{priority:1,type:h.setPlayer},muteRemoteVideoStream:{priority:1,type:h.setPlayer},muteAllRemoteVideoStreams:{priority:1,type:h.setPlayer},setRemoteRenderParams:{priority:0,type:h.setPlayer},muteRemoteAudio:{priority:1,type:h.setPlayer},muteAllRemoteAudio:{priority:1,type:h.setPlayer}},L=function(){function e(t){var s;f(this,e);var n=t.priority,o=void 0===n?0:n,i=t.action,r=t.args,a=t.resolve,c=t.reject,u=t.ctx,l=t.name;this.ctx=u,this.priority=o,this.action=i,this.args=r,this.resolve=a,this.reject=c,this.name=l,this.single=this.whetherSingle(l),this.type=(null===(s=b[l])||void 0===s?void 0:s.type)||h.setPusher,this.sequenceNumber=e.nextSequenceNumber++}return I(e,[{key:"whetherSingle",value:function(e){return"enterRoom"===e}}]),e}();L.nextSequenceNumber=0,function(e){e.IDLE="idle",e.PENDING="pending",e.PROCESS="process"}(O||(O={})),function(e){e.SET="SET",e.SETPROCESS="SETPROCESS",e.SETDONE="SETDONE"}(D||(D={}));var N,w,P,G=new(function(){function e(){f(this,e),this.isProcessing=!1,this.pusherDomReady=!1,this.pusherTaskQueue=[],this.playerTasks={},this.state=O.IDLE}return I(e,[{key:"reset",value:function(){for(var e in this.state=O.IDLE,this.resetPusherTasks(),this.playerTasks)this.playerTasks[e]&&this.resetPlayerTasks(e);this.playerTasks={}}},{key:"resetPusherTasks",value:function(){this.isProcessing=!1,this.pusherTaskQueue.forEach(function(e){e.resolve()}),this.pusherTaskQueue.length=0}},{key:"resetPlayerTasks",value:function(e){this.playerTasks[e]&&(this.playerTasks[e].taskQueue.forEach(function(e){e.resolve()}),this.playerTasks[e].taskQueue.length=0,this.playerTasks[e].isProcessing=!1,this.playerTasks[e].domReady=!1)}},{key:"setPusherDomReady",value:function(e){return this.pusherDomReady=e,e||this.resetPusherTasks(),this.pusherDomReady}},{key:"setPlayerDomReady",value:function(e,t){this.playerTasks[e]||(this.playerTasks[e]={taskQueue:[],isProcessing:!1,domReady:!1}),this.playerTasks[e].domReady=t,t?this.processPlayerTasks(e):this.resetPlayerTasks(e)}},{key:"send",value:function(e,t){switch(this.state){case O.IDLE:e===D.SET&&(this.state=O.PENDING,t?this.processPlayerTasks(t):this.processPusherTasks());break;case O.PENDING:e===D.SETPROCESS&&(t?this.processPlayerTasks(t):this.processPusherTasks()),e===D.SETDONE&&(this.state=O.IDLE);break;case O.PROCESS:e===D.SETDONE&&(this.state=O.IDLE)}}},{key:"addTask",value:function(e){e.type===h.setPusher?this.addPusherTask(e):this.addPlayerTask(e.args.view,e)}},{key:"addPusherTask",value:function(e){this.addTaskToQueue(e,this.pusherTaskQueue),this.state!==O.PROCESS||this.isProcessing?this.state===O.IDLE?this.send(D.SET):this.state===O.PENDING&&this.send(D.SETPROCESS):this.processPusherTasks()}},{key:"addPlayerTask",value:function(e,t){this.playerTasks[e]||(this.playerTasks[e]={taskQueue:[],isProcessing:!1,domReady:!1}),this.addTaskToQueue(t,this.playerTasks[e].taskQueue),this.state!==O.PROCESS||this.playerTasks[e].isProcessing?this.state===O.IDLE?this.send(D.SET,e):this.state===O.PENDING&&this.send(D.SETPROCESS,e):this.processPlayerTasks(e)}},{key:"addTaskToQueue",value:function(e,t){t.push(e),t.sort(function(e,t){return e.priority!==t.priority?e.priority-t.priority:e.sequenceNumber-t.sequenceNumber})}},{key:"processTasks",value:function(e,t,s,n,o){return A(this,0,void 0,_().mark(function i(){var r,a,c,u,l,d,p,g,m,f,v,I,E,C,S,M=this;return _().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(!t&&s&&0!==e.length){i.next=2;break}return i.abrupt("return");case 2:n(!0),this.state=O.PROCESS,r=y(e),e.length=0,a=r.filter(function(e){return e.single}),c=r.filter(function(e){return!e.single}),u=T(a),i.prev=9,u.s();case 11:if((l=u.n()).done){i.next=24;break}return d=l.value,i.prev=13,i.next=16,d.action.call(d.ctx,d.args,d.name,b[d.name].type);case 16:d.result=i.sent,i.next=22;break;case 19:i.prev=19,i.t0=i.catch(13),d.err=i.t0;case 22:i.next=11;break;case 24:i.next=29;break;case 26:i.prev=26,i.t1=i.catch(9),u.e(i.t1);case 29:return i.prev=29,u.f(),i.finish(29);case 32:if(p=c.reduce(function(e,t){var s=t.args.params;return Object.assign(Object.assign({},e),"function"==typeof s?s():s)},{}),g=c[0],m=r.sort(function(e,t){return e.sequenceNumber-t.sequenceNumber}),i.prev=35,f=null,!g){i.next=47;break}if(!o){i.next=44;break}return i.next=41,g.action.call(g.ctx,{params:p,streamId:g.args.streamId,view:o},g.name,h.setPlayer);case 41:f=i.sent,i.next=47;break;case 44:return i.next=46,g.action.call(g.ctx,{params:p},g.name,h.setPusher);case 46:f=i.sent;case 47:v=T(m);try{for(v.s();!(I=v.n()).done;)(E=I.value).err?E.reject(E.err):E.resolve(E.result||f)}catch(e){v.e(e)}finally{v.f()}i.next=55;break;case 51:i.prev=51,i.t2=i.catch(35),C=T(m);try{for(C.s();!(S=C.n()).done;)S.value.reject(i.t2)}catch(e){C.e(e)}finally{C.f()}case 55:n(!1),this.send(D.SETDONE,o),e.length>0&&Promise.resolve().then(function(){M.processTasks(e,t,s,n,o)}).catch(console.error);case 58:case"end":return i.stop()}},i,this,[[9,26,29,32],[13,19],[35,51]])}))}},{key:"processPusherTasks",value:function(){return A(this,0,void 0,_().mark(function e(){var t=this;return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.processTasks(this.pusherTaskQueue,this.isProcessing,this.pusherDomReady,function(e){t.isProcessing=e});case 2:case"end":return e.stop()}},e,this)}))}},{key:"processPlayerTasks",value:function(e){return A(this,0,void 0,_().mark(function t(){var s=this;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.playerTasks[e]){t.next=2;break}return t.abrupt("return");case 2:return t.next=4,this.processTasks(this.playerTasks[e].taskQueue,this.playerTasks[e].isProcessing,this.playerTasks[e].domReady,function(t){s.playerTasks[e].isProcessing=t},e);case 4:case"end":return t.stop()}},t,this)}))}}]),e}()),U=function(e){switch(e){case 0:return"videocall";case 1:return"live";case 2:return"audiocall";case 3:return"voicechatroom";default:return""}},k=function(e){switch(e){case 0:return"main";case 1:return"small";case 2:return"aux";default:return""}},F=function(e,t){return"".concat(e,"_").concat(k(t))},x=(E(N={},e.TRTCVideoResolution.TRTCVideoResolution_120_120,[120,120]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_160_160,[160,160]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_270_270,[270,270]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_480_480,[480,480]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_160_120,[160,120]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_240_180,[240,180]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_280_210,[280,210]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_320_240,[320,240]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_400_300,[400,300]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_480_360,[480,360]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_640_480,[640,480]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_960_720,[960,720]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_160_90,[160,90]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_256_144,[256,144]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_320_180,[320,180]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_480_270,[480,270]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_640_360,[640,360]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_960_540,[960,540]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_1280_720,[1280,720]),E(N,e.TRTCVideoResolution.TRTCVideoResolution_1920_1080,[1920,1080]),N),V=function(e){var t=C(x[e],2),s=t[0],n=void 0===s?0:s,o=t[1];return{videoWidth:n,videoHeight:void 0===o?0:o}},$=function(t){switch(t){case e.TRTCVideoRotation.TRTCVideoRotation0:return"vertical";case e.TRTCVideoRotation.TRTCVideoRotation90:return"horizontal";default:return""}},q=function(t){switch(t){case e.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto:return"auto";case e.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable:return"enable";case e.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable:return"disable";default:return""}},B=function(t){switch(t){case e.TRTCAudioRoute.TRTC_AUDIO_ROUTE_SPEAKER:return"speaker";case e.TRTCAudioRoute.TRTC_AUDIO_ROUTE_EARPIECE:return"ear";default:return""}},j=(E(w={},e.TRTCBeautyStyle.TRTCBeautyStyleSmooth,"smooth"),E(w,e.TRTCBeautyStyle.TRTCBeautyStyleNature,"nature"),w),H=function(e){return j[e]},K=(E(P={},e.TRTCVideoFillMode.TRTCVideoFillMode_Fill,"fillCrop"),E(P,e.TRTCVideoFillMode.TRTCVideoFillMode_Fit,"contain"),P),W=function(e){return K[e]};var Y=function(){var e=(new Date).getTime(),t=new Date(e),s=t.getHours(),n=t.getMinutes(),o=t.getSeconds(),i=t.getMilliseconds();return s=s<10?"0".concat(s):s,n=n<10?"0".concat(n):n,o=o<10?"0".concat(o):o,"".concat(s,":").concat(n,":").concat(o,".").concat(i)},z=0,J=1,Q=2,X=3,ee=4,te=function(){function e(t){f(this,e),this.logLevel=0,this.TAG_NAME="",this.TAG_NAME=t||"[TRTCCloud-WX]"}return I(e,[{key:"setInfo",value:function(e){var t=e.sdkAppId,s=e.userId,n=e.roomId;this.sdkAppId=t,this.userId=s,this.roomId=n}},{key:"setLogLevel",value:function(e){this.logLevel=e}},{key:"log",value:function(){if(this.logLevel===z){for(var e,t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];(e=console).log.apply(e,[this.TAG_NAME,Y()].concat(s))}}},{key:"info",value:function(){if(this.logLevel<=J){for(var e,t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];(e=console).info.apply(e,[this.TAG_NAME,Y()].concat(s))}}},{key:"warn",value:function(){if(this.logLevel<=X){for(var e,t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];(e=console).warn.apply(e,[this.TAG_NAME,Y()].concat(s))}}},{key:"error",value:function(){if(this.logLevel<=ee){for(var e,t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];(e=console).error.apply(e,[this.TAG_NAME,Y()].concat(s))}}},{key:"debug",value:function(){if(this.logLevel<=Q){for(var e,t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];(e=console).debug.apply(e,[this.TAG_NAME,Y()].concat(s))}}}]),e}(),ne=new te,oe="1.0.9",ie=function(){function t(){f(this,t),this.version=oe,this.InterfaceEventEmitter=new p,this.EventEmitter=new p,this.role=e.TRTCRoleType.TRTCRoleAnchor,this.userId="",this.isEnterRoom=!1,this.isVideoMuted=!1,this.isOpenCamera=!1,this.currentSoundMode=e.TRTCAudioRoute.TRTC_AUDIO_ROUTE_SPEAKER,this.audioVolumeEvaluation=0,this.encsmall=0,this.enableinfiniteanchor=0,this.allTimer={},this.renderMap=new Map,this.pusherIsReady=!1,this.logger=ne,this.init()}return I(t,[{key:"createSubCloud",value:function(){return t.getTRTCShareInstance()}},{key:"getSDKVersion",value:function(){return this.version}},{key:"destroy",value:function(){this.offTRTCEvent(),this.EventEmitter.removeAllListeners(),this.InterfaceEventEmitter.removeAllListeners(),this.trtc.exitRoom()}},{key:"init",value:function(){this.trtc=new g(this),this.trtc.setLogLevel(3),this.TRTC_EVENT=this.trtc.EVENT,this.bindTRTCEvent(),this.bindComponentEvent(),this.handleNetworkQuality=this.getHandleNetworkQuality(2e3)}},{key:"reset",value:function(){var t=this;this.role=e.TRTCRoleType.TRTCRoleAnchor,this.userId="",this.isEnterRoom=!1,this.isVideoMuted=!1,this.isOpenCamera=!1,this.currentSoundMode=e.TRTCAudioRoute.TRTC_AUDIO_ROUTE_SPEAKER,this.encsmall=0,this.enableinfiniteanchor=0,G.reset(),Object.keys(this.allTimer).forEach(function(e){clearInterval(t.allTimer[e]),t.allTimer[e]=null})}},{key:"bindComponentEvent",value:function(){var e=this;this.InterfaceEventEmitter.on("pusherDomReady",function(t){e.pusherIsReady=t,G.setPusherDomReady(t),t?(e.trtc.createPusher({}),G.send(D.SETPROCESS)):(e.isEnterRoom&&e.exitRoom(),G.send(D.SETDONE))}),this.InterfaceEventEmitter.on("playerDomReady",function(e){var t=e.isReady,s=e.view;G.setPlayerDomReady(s,t),t?G.send(D.SETPROCESS,s):G.send(D.SETDONE,s)})}},{key:"bindTRTCEvent",value:function(){var e=this;this.trtc.on(this.TRTC_EVENT.LOCAL_LEAVE,function(e){}),this.trtc.on(this.TRTC_EVENT.PLAYER_WARNING,function(t){var s=t.data,n=s.code,o=s.message;e.emit("onWarnning",n,o)}),this.trtc.on(this.TRTC_EVENT.ERROR,function(t){var s=t.data,n=s.code,o=s.message;e.emit("onError",n,o)}),this.trtc.on(this.TRTC_EVENT.REMOTE_USER_JOIN,function(t){var s=t.data.userID;e.emit("onRemoteUserEnterRoom",s)}),this.trtc.on(this.TRTC_EVENT.REMOTE_USER_LEAVE,function(t){var s=t.data,n=s.userID;s.playerList,e.InterfaceEventEmitter.emit("onRemoteUserLeaveRoom",n,0),e.emit("onUserVideoAvailable",n,0),e.emit("onUserSubStreamAvailable",n,0),e.emit("onRemoteUserLeaveRoom",n,0)}),this.trtc.on(this.TRTC_EVENT.REMOTE_VIDEO_ADD,function(t){var s=t.data.player;e.emit("aux"===s.streamType?"onUserSubStreamAvailable":"onUserVideoAvailable",s.userID,1)}),this.trtc.on(this.TRTC_EVENT.REMOTE_VIDEO_REMOVE,function(t){var s=t.data.player;e.emit("aux"===s.streamType?"onUserSubStreamAvailable":"onUserVideoAvailable",s.userID,0)}),this.trtc.on(this.TRTC_EVENT.REMOTE_AUDIO_ADD,function(t){var s=t.data.player;e.emit("onUserAudioAvailable",s.userID,1)}),this.trtc.on(this.TRTC_EVENT.REMOTE_AUDIO_REMOVE,function(t){var s=t.data.player;e.emit("onUserAudioAvailable",s.userID,0)}),this.trtc.on(this.TRTC_EVENT.REMOTE_AUDIO_VOLUME_UPDATE,function(t){var s=t.data.playerList.map(function(e){return{userId:e.userID,volume:e.volume}});e.handleAudioVolumeUpdate(s)}),this.trtc.on(this.TRTC_EVENT.LOCAL_AUDIO_VOLUME_UPDATE,function(t){var s=t.data.pusher,n=[{userId:s.userID,volume:s.volume}];e.handleAudioVolumeUpdate(n)}),this.trtc.on(this.TRTC_EVENT.LOCAL_NET_STATE_UPDATE,function(t){var s=t.data.pusher;e.handleNetworkQuality({pusher:s})}),this.trtc.on(this.TRTC_EVENT.REMOTE_NET_STATE_UPDATE,function(t){var s=t.data.playerList;e.handleNetworkQuality({playerList:s})})}},{key:"offTRTCEvent",value:function(){this.trtc.off(this.TRTC_EVENT.LOCAL_LEAVE),this.trtc.off(this.TRTC_EVENT.ERROR),this.trtc.off(this.TRTC_EVENT.REMOTE_USER_JOIN),this.trtc.off(this.TRTC_EVENT.REMOTE_USER_LEAVE),this.trtc.off(this.TRTC_EVENT.REMOTE_VIDEO_ADD),this.trtc.off(this.TRTC_EVENT.REMOTE_VIDEO_REMOVE),this.trtc.off(this.TRTC_EVENT.REMOTE_AUDIO_ADD),this.trtc.off(this.TRTC_EVENT.REMOTE_AUDIO_REMOVE),this.trtc.off(this.TRTC_EVENT.REMOTE_AUDIO_VOLUME_UPDATE),this.trtc.off(this.TRTC_EVENT.REMOTE_NET_STATE_UPDATE)}},{key:"getHandleAudioVolumeUpdate",value:function(e){var t,s=this;if((null===(t=this.allTimer)||void 0===t?void 0:t.AudioVolume)&&(clearInterval(this.allTimer.AudioVolume),this.allTimer.AudioVolume=null),0===e)return function(){};var n=[];return this.InterfaceEventEmitter.off("onRemoteUserLeaveRoom"),this.InterfaceEventEmitter.on("onRemoteUserLeaveRoom",function(e){n=n.filter(function(t){return t.userId!==e})},this.getHandleAudioVolumeUpdate),function(t){var o,i,r;if(o=[].concat(y(t),y(n)),i="userId",r=new Map,n=o.filter(function(e){return!r.has(e[i])&&r.set(e[i],1)}),!s.allTimer.AudioVolume){var a=setInterval(function(){s.emit("onUserVoiceVolume",n,n.length,0)},e);s.allTimer.AudioVolume=a}}}},{key:"handleAudioVolumeUpdate",value:function(e){}},{key:"getHandleNetworkQuality",value:function(e){var t,s=this;if((null===(t=this.allTimer)||void 0===t?void 0:t.networkQuality)&&(clearInterval(this.allTimer.networkQuality),this.allTimer.networkQuality=null),0===e)return function(){};var n={localQuality:null,remoteQuality:[]};return this.on("onRemoteUserLeaveRoom",function(e){n.remoteQuality=n.remoteQuality.filter(function(t){return t.userId!==e})},this),function(t){var o=t.pusher,i=t.playerList;if(o&&(n.localQuality={userId:o.userID,quality:o.netStatus}),i&&(n.remoteQuality=i.map(function(e){return{userId:e.userID,quality:e.netStatus}})),!s.allTimer.networkQuality){var r=setInterval(function(){s.emit("onNetworkQuality",n.localQuality,n.remoteQuality)},e);s.allTimer.networkQuality=r}}}},{key:"handleNetworkQuality",value:function(e){}},{key:"on",value:function(e,t,s){this.EventEmitter.on(e,t,s)}},{key:"off",value:function(e,t,s){this.EventEmitter.off(e,t,s)}},{key:"emit",value:function(e){for(var t,s=arguments.length,n=new Array(s>1?s-1:0),o=1;o<s;o++)n[o-1]=arguments[o];(t=this.EventEmitter).emit.apply(t,[e].concat(n))}},{key:"enterRoom",value:function(t,s){return A(this,0,void 0,_().mark(function n(){var o,i,r,a,c,u,l,d,h=this;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(!this.isEnterRoom){n.next=3;break}return ne.warn("You are already in the room, please exit the current room first."),n.abrupt("return");case 3:return this.trtc.createPusher({}),o=(new Date).getTime(),i=t.sdkAppId,r=t.userId,a=t.userSig,c=t.roomId,u=t.strRoomId,l=t.role,d=t.privateMapKey,ne.setInfo({sdkAppId:i,userId:r,roomId:u}),ne.info("enterRoom with options: ",JSON.stringify(t),s),this.userId=r,this.isEnterRoom=!0,n.prev=10,n.next=13,this.setAttributes({params:{sdkAppID:i,userID:r,userSig:a,roomID:c,strRoomID:u,role:l,privateMapKey:d,scene:U(s),enableMic:!1,enableCamera:!1,videoPreview:!1,encsmall:this.encsmall,enableinfiniteanchor:this.enableinfiniteanchor,recvMode:this.enableinfiniteanchor?2:1}},"enterRoom");case 13:n.next=20;break;case 15:n.prev=15,n.t0=n.catch(10),this.isEnterRoom=!1,ne.info("enterRoom fail"),this.emit("onEnterRoom",-1);case 20:this.trtc.getPusherInstance().start({success:function(){return A(h,0,void 0,_().mark(function t(){var n;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(ne.info("enterRoom success"),this.scene=s,n=(new Date).getTime(),this.emit("onEnterRoom",n-o),!0!==this.trtc.getPusherAttributes().videoPreview){t.next=8;break}return t.next=7,this.setAttributes({params:{videoPreview:!1,enableCamera:!0}},"other");case 7:this.emit("onSendFirstLocalVideoFrame",e.TRTCVideoStreamType.TRTCVideoStreamTypeBig);case 8:case"end":return t.stop()}},t,this)}))},fail:function(){h.isEnterRoom=!1,ne.info("enterRoom fail"),h.emit("onEnterRoom",-1)}});case 21:case"end":return n.stop()}},n,this,[[10,15]])}))}},{key:"exitRoom",value:function(){var e=this;ne.info("exitRoom");var t=this.trtc.exitRoom().pusher;this.reset(),this.pusherIsReady?this.InterfaceEventEmitter.emit("pusherAttributesChange",{pusher:t,callback:function(){ne.info("exitRoom success"),e.emit("onExitRoom",0)}}):(ne.info("exitRoom success"),this.emit("onExitRoom",0))}},{key:"switchRoom",value:function(){}},{key:"switchRole",value:function(t){return A(this,0,void 0,_().mark(function s(){var n;return _().wrap(function(s){for(;;)switch(s.prev=s.next){case 0:if(ne.info("switchRole with options: ",t),n=this.role,this.role=t,n!==t&&t!==e.TRTCRoleType.TRTCRoleAnchor){s.next=7;break}return ne.info("switchRole success"),this.emit("onSwitchRole",0,""),s.abrupt("return");case 7:return s.next=9,this.setAttributes({params:{enableCamera:!1,enableMic:!1}},"switchRole");case 9:ne.info("switchRole success"),this.emit("onSwitchRole",0,"");case 11:case"end":return s.stop()}},s,this)}))}},{key:"connectOtherRoom",value:function(){}},{key:"disconnectOtherRoom",value:function(){}},{key:"setDefaultStreamRecvMode",value:function(){}},{key:"useVirtualBackground",value:function(){}},{key:"startLocalPreview",value:function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return A(this,0,void 0,_().mark(function s(){var n,o=this;return _().wrap(function(s){for(;;)switch(s.prev=s.next){case 0:if(ne.info("startLocalPreview with options: ",t),this.role===e.TRTCRoleType.TRTCRoleAnchor){s.next=3;break}return s.abrupt("return");case 3:return s.next=5,this.setAttributes({params:function(){return{videoPreview:!o.isEnterRoom||o.isVideoMuted,enableCamera:!!o.isEnterRoom&&!o.isVideoMuted,frontCamera:t?"front":"back"}}},"startLocalPreview");case 5:n=s.sent,ne.info("startLocalPreview success"),this.emit("onFirstVideoFrame","",e.TRTCVideoStreamType.TRTCVideoStreamTypeBig,n.videoWidth,n.videoHeight),this.isEnterRoom&&this.emit("onSendFirstLocalVideoFrame",e.TRTCVideoStreamType.TRTCVideoStreamTypeBig),this.isOpenCamera=!0;case 10:case"end":return s.stop()}},s,this)}))}},{key:"stopLocalPreview",value:function(){return A(this,0,void 0,_().mark(function e(){return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ne.info("stopLocalPreview"),e.next=3,this.setAttributes({params:{videoPreview:!1,enableCamera:!1}},"stopLocalPreview");case 3:ne.info("stopLocalPreview success"),this.isOpenCamera=!1,this.emit("onUserVideoAvailable",this.userId,0);case 6:case"end":return e.stop()}},e,this)}))}},{key:"updateLocalView",value:function(e){ne.info("updateLocalView with options: ",e),null===e?this.stopLocalPreview():this.startLocalPreview()}},{key:"muteLocalVideo",value:function(t,s){return A(this,0,void 0,_().mark(function n(){return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(ne.info("muteLocalVideo called with options: ",t,s),this.isOpenCamera){n.next=4;break}return ne.info("muteLocalVideo early exit: isOpenCamera is false"),n.abrupt("return");case 4:n.t0=s,n.next=n.t0===e.TRTCVideoStreamType.TRTCVideoStreamTypeBig||n.t0===e.TRTCVideoStreamType.TRTCVideoStreamTypeSub?7:20;break;case 7:return this.isVideoMuted=t,ne.info("muteLocalVideo: isVideoMuted set to ",t),n.prev=9,n.next=12,this.setAttributes({params:{videoPreview:t,enableCamera:!t}},"muteLocalVideo");case 12:ne.info("muteLocalVideo: setAttributes success"),n.next=18;break;case 15:n.prev=15,n.t1=n.catch(9),ne.error("muteLocalVideo: setAttributes failed with error ",n.t1);case 18:return ne.info("muteLocalVideo success"),n.abrupt("break",21);case 20:ne.info("muteLocalVideo: streamType not supported ",s);case 21:case"end":return n.stop()}},n,this,[[9,15]])}))}},{key:"startRemoteView",value:function(e,t,s){return A(this,0,void 0,_().mark(function n(){var o;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return ne.info("startRemoteView with options: ",e,t,s),o=F(e,s),this.renderMap.set(o,t),n.next=5,this.setAttributes({params:{muteVideo:!1,stopVideo:!1},streamId:o,view:t},"startRemoteView");case 5:this.updateAudioRoute(),ne.info("startRemoteView success"),this.emit("onFirstVideoFrame",e,s,0,0);case 8:case"end":return n.stop()}},n,this)}))}},{key:"stopRemoteView",value:function(e,t){return A(this,0,void 0,_().mark(function s(){var n;return _().wrap(function(s){for(;;)switch(s.prev=s.next){case 0:return ne.info("stopRemoteView with options: ",e,t),n=F(e,t),s.next=4,this.setAttributes({params:{muteVideo:!0,stopVideo:!0},streamId:n,view:this.renderMap.get(n)},"stopRemoteView");case 4:ne.info("stopRemoteView success");case 5:case"end":return s.stop()}},s,this)}))}},{key:"updateRemoteView",value:function(e,t,s){return A(this,0,void 0,_().mark(function n(){return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(ne.info("updateRemoteView with options: ",e,t,s),null===t){n.next=5;break}return n.next=4,this.startRemoteView(e,t,s);case 4:return n.abrupt("return");case 5:return n.next=7,this.stopRemoteView(e,s);case 7:case"end":return n.stop()}},n,this)}))}},{key:"stopAllRemoteView",value:function(){return A(this,0,void 0,_().mark(function e(){var t=this;return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:ne.info("stopAllRemoteView"),this.trtc.getPlayerList().forEach(function(e){return A(t,0,void 0,_().mark(function t(){var s;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return s=e.streamID,t.next=3,this.setAttributes({params:{muteVideo:!0,stopVideo:!0},streamId:s,view:this.renderMap.get(s)},"stopAllRemoteView");case 3:case"end":return t.stop()}},t,this)}))}),ne.info("stopAllRemoteView success");case 4:case"end":return e.stop()}},e,this)}))}},{key:"muteRemoteVideoStream",value:function(e,t,s){return A(this,0,void 0,_().mark(function n(){var o;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return ne.info("muteRemoteVideoStream"),o=F(e,s),n.next=4,this.setAttributes({params:{muteVideo:t},streamId:o,view:this.renderMap.get(o)},"muteRemoteVideoStream");case 4:ne.info("muteRemoteVideoStream success");case 5:case"end":return n.stop()}},n,this)}))}},{key:"muteAllRemoteVideoStreams",value:function(e){return A(this,0,void 0,_().mark(function t(){var s=this;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:ne.info("muteAllRemoteVideoStreams with options: ",e),this.trtc.getPlayerList().forEach(function(t){return A(s,0,void 0,_().mark(function s(){var n;return _().wrap(function(s){for(;;)switch(s.prev=s.next){case 0:return n=t.streamID,s.next=3,this.setAttributes({params:{muteVideo:e},streamId:n,view:this.renderMap.get(n)},"muteAllRemoteVideoStreams");case 3:case"end":return s.stop()}},s,this)}))}),ne.info("muteAllRemoteVideoStreams success");case 4:case"end":return t.stop()}},t,this)}))}},{key:"setTRTCPlayerAttributes",value:function(e,t){var s;return ne.info("setTRTCPlayerAttributes with options: ",e,t),this.trtc.setPlayerAttributes(e,t),(null===(s=this.trtc.getPlayerInstance(e))||void 0===s?void 0:s.playerAttributes)||{}}},{key:"setVideoEncoderParam",value:function(e){return A(this,0,void 0,_().mark(function t(){var s,n,o,i,r,a;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return ne.info("setVideoEncoderParam with options: ",JSON.stringify(e)),s=e.videoResolution,e.resMode,n=e.videoFps,e.videoBitrate,o=e.minVideoBitrate,i=V(s),r=i.videoWidth,a=i.videoHeight,t.next=5,this.setAttributes({params:{videoWidth:r,videoHeight:a,fps:n,minBitrate:o}},"setVideoEncoderParam");case 5:ne.info("setVideoEncoderParam success");case 6:case"end":return t.stop()}},t,this)}))}},{key:"setLocalRenderParams",value:function(e){return A(this,0,void 0,_().mark(function t(){var s,n,o,i;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return ne.info("setLocalRenderParams with options: ",JSON.stringify(e)),s=e.rotation,e.fillMode,n=e.mirrorType,o=$(s),i=q(n),t.next=6,this.setAttributes({params:{videoOrientation:o,localMirror:i}},"setLocalRenderParams");case 6:ne.info("setLocalRenderParams success");case 7:case"end":return t.stop()}},t,this)}))}},{key:"setRemoteRenderParams",value:function(e,t,s){return A(this,0,void 0,_().mark(function n(){var o,i,r;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return ne.info("setRemoteRenderParams with options: ",e,t,JSON.stringify(s)),o=s.fillMode,i=s.rotation,s.mirrorType,r=F(e,t),n.next=5,this.setAttributes({params:{objectFit:W(o),orientation:$(i)},streamId:r,view:this.renderMap.get(r)},"setRemoteRenderParams");case 5:ne.info("setRemoteRenderParams success");case 6:case"end":return n.stop()}},n,this)}))}},{key:"startLocalAudio",value:function(t){return A(this,0,void 0,_().mark(function s(){var n;return _().wrap(function(s){for(;;)switch(s.prev=s.next){case 0:if(ne.info("startLocalAudio with options: ",t),this.role===e.TRTCRoleType.TRTCRoleAnchor){s.next=3;break}throw new Error("Current role is audience, unable to access mic. Call switchRole to become a host.");case 3:return n=function(t){return t===e.TRTCAudioQuality.TRTCAudioQualitySpeech?"low":"high"},s.next=6,this.setAttributes({params:{enableMic:!0,audioQuality:n(t)}},"startLocalAudio");case 6:ne.info("startLocalAudio success"),this.emit("onMicDidReady"),this.enterRoom&&this.emit("onSendFirstLocalAudioFrame");case 9:case"end":return s.stop()}},s,this)}))}},{key:"stopLocalAudio",value:function(){return A(this,0,void 0,_().mark(function e(){return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ne.info("stopLocalAudio"),e.next=3,this.setAttributes({params:{enableMic:!1}},"stopLocalAudio");case 3:ne.info("stopLocalAudio success");case 4:case"end":return e.stop()}},e,this)}))}},{key:"muteLocalAudio",value:function(e){return A(this,0,void 0,_().mark(function t(){return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return ne.info("muteLocalAudio called with options: ",e),t.prev=1,t.next=4,this.setAttributes({params:{muted:e}},"muteLocalAudio");case 4:ne.info("setAttributes executed successfully"),t.next=11;break;case 7:throw t.prev=7,t.t0=t.catch(1),ne.error("Error in setAttributes: ",t.t0),t.t0;case 11:t.prev=11,this.emit("onUserAudioAvailable",this.userId,!0===e?0:1),ne.info("onUserAudioAvailable event emitted successfully"),t.next=20;break;case 16:throw t.prev=16,t.t1=t.catch(11),ne.error("Error in emitting onUserAudioAvailable event: ",t.t1),t.t1;case 20:ne.info("muteLocalAudio execution finished");case 21:case"end":return t.stop()}},t,this,[[1,7],[11,16]])}))}},{key:"setAudioRoute",value:function(e){return A(this,0,void 0,_().mark(function t(){var s;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return ne.info("setAudioRoute with options: ",e),this.currentSoundMode=e,s=B(e),t.prev=3,t.next=6,this.playerAudioRouteChange({soundMode:s});case 6:ne.info("setAudioRoute success"),t.next=13;break;case 9:throw t.prev=9,t.t0=t.catch(3),ne.error("Error in setAttributes: ",t.t0),t.t0;case 13:case"end":return t.stop()}},t,this,[[3,9]])}))}},{key:"updateAudioRoute",value:function(){return A(this,0,void 0,_().mark(function e(){var t;return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ne.info("updateAudioRoute with options: ",this.currentSoundMode),t=B(this.currentSoundMode),e.prev=2,e.next=5,this.playerAudioRouteChange({soundMode:t});case 5:e.next=11;break;case 7:throw e.prev=7,e.t0=e.catch(2),ne.error("Error in setAttributes: ",e.t0),e.t0;case 11:case"end":return e.stop()}},e,this,[[2,7]])}))}},{key:"muteRemoteAudio",value:function(t,s){return A(this,0,void 0,_().mark(function n(){var o;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return ne.info("muteRemoteAudio with options: ",t,s),o=F(t,e.TRTCVideoStreamType.TRTCVideoStreamTypeBig),n.next=4,this.setAttributes({params:{muteAudio:s},streamId:o,view:this.renderMap.get(o)},"muteRemoteAudio");case 4:ne.info("muteRemoteAudio success");case 5:case"end":return n.stop()}},n,this)}))}},{key:"muteAllRemoteAudio",value:function(e){return A(this,0,void 0,_().mark(function t(){var s=this;return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:ne.info("muteAllRemoteAudio with options: ",e),this.trtc.getPlayerList().forEach(function(t){return A(s,0,void 0,_().mark(function s(){var n;return _().wrap(function(s){for(;;)switch(s.prev=s.next){case 0:return n=t.streamID,s.next=3,this.setAttributes({params:{muteAudio:e},streamId:n,view:this.renderMap.get(n)},"muteRemoteAudio");case 3:case"end":return s.stop()}},s,this)}))}),ne.info("muteAllRemoteAudio success");case 4:case"end":return t.stop()}},t,this)}))}},{key:"enableAudioVolumeEvaluation",value:function(e){ne.info("enableAudioVolumeEvaluation with options: ",e),this.handleAudioVolumeUpdate=this.getHandleAudioVolumeUpdate(e)}},{key:"switchCamera",value:function(e){var t=this;ne.info("switchCamera with options: ",e);var s=this.trtc.getPusherInstance();return e===("front"===s.pusherAttributes.frontCamera)?Promise.resolve():new Promise(function(s,n){wx.createLivePusherContext().switchCamera({success:function(n){return A(t,0,void 0,_().mark(function t(){return _().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.setAttributes({params:{frontCamera:e?"front":"back"}},"switchCamera");case 2:ne.info("switchCamera success"),s(n);case 4:case"end":return t.stop()}},t,this)}))},fail:function(e){ne.info("switchCamera fail"),n(e)}})})}},{key:"setBeautyStyle",value:function(e,t,s,n){return A(this,0,void 0,_().mark(function o(){return _().wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return ne.info("setBeautyStyle with options: ",e,t,s,n),o.next=3,this.setAttributes({params:{beautyStyle:H(e),beautyLevel:t,whitenessLevel:s}},"setBeautyStyle");case 3:ne.info("setBeautyStyle success");case 4:case"end":return o.stop()}},o,this)}))}},{key:"sendSEIMsg",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return ne.info("sendSEIMsg with options: ",e,t),new Promise(function(t,s){wx.createLivePusherContext().sendMessage({msg:e,success:function(e){ne.info("sendSEIMsg success"),t(e)},fail:function(e){ne.info("sendSEIMsg fail"),s(e)}})})}},{key:"startPlayMusic",value:function(e,t){return ne.info("startPlayMusic with options: ",JSON.stringify(e)),new Promise(function(t,s){var n=e.path,o=e.startTimeMS,i=void 0===o?0:o,r=e.endTimeMS,a=void 0===r?0:r;wx.createLivePusherContext().playBGM({url:n,startTimeMs:i,endTimeMs:a,success:function(e){ne.info("startPlayMusic success"),t(e)},fail:function(e){ne.info("startPlayMusic fail"),s(e)}})})}},{key:"stopPlayMusic",value:function(){return ne.info("stopPlayMusic"),new Promise(function(e,t){wx.createLivePusherContext().stopBGM({success:function(t){ne.info("stopPlayMusic success"),e(t)},fail:function(e){ne.info("stopPlayMusic fail"),t(e)}})})}},{key:"pausePlayMusic",value:function(){return ne.info("pausePlayMusic"),new Promise(function(e,t){wx.createLivePusherContext().pauseBGM({success:function(t){ne.info("pausePlayMusic success"),e(t)},fail:function(e){ne.info("pausePlayMusic fail"),t(e)}})})}},{key:"resumePlayMusic",value:function(){return ne.info("resumePlayMusic"),new Promise(function(e,t){wx.createLivePusherContext().resumeBGM({success:function(t){ne.info("resumePlayMusic success"),e(t)},fail:function(e){ne.info("resumePlayMusic fail"),t(e)}})})}},{key:"setAllMusicVolume",value:function(e){return ne.info("setAllMusicVolume with options: ",e),new Promise(function(t,s){var n=(e/200).toString();wx.createLivePusherContext().setBGMVolume({volume:n,success:function(e){ne.info("setAllMusicVolume success"),t(e)},fail:function(e){ne.info("setAllMusicVolume fail"),s(e)}})})}},{key:"enableSmallVideoStream",value:function(e,t){ne.info("enableSmallVideoStream with options: ",e,JSON.stringify(t)),this.encsmall=e?1:0}},{key:"callExperimentalAPI",value:function(e){ne.info("callExperimentalAPI with options: ",e);var t=function(e){if("string"!=typeof e)return e;var t;try{var s=JSON.parse(e);t="object"===m(s)&&s?s:e}catch(s){t=e}return t}(e);if(t!==e){var s=t.api,n=t.params;if(s&&n)switch(s){case"setFramework":this.handleSetFrameWork(n);break;case"enableInfiniteAnchor":this.enableinfiniteanchor=(null==n?void 0:n.enable)?1:0}}}},{key:"handleSetFrameWork",value:function(e){var t=e.component;if("number"==typeof t)try{wx&&(wx.TUIScene=t,wx.setStorageSync("TUIScene",String(t)))}catch(e){throw e}}},{key:"pusherAttributesChange",value:function(e){var t=this;return new Promise(function(s){t.InterfaceEventEmitter.emit("pusherAttributesChange",{pusher:e,callback:function(){s(e)}})})}},{key:"playerAttributesChange",value:function(e){var t=this,s=e.streamId,n=e.playerAttributes;return new Promise(function(e){t.InterfaceEventEmitter.emit("playerAttributesChange",{streamId:s,view:t.renderMap.get(s),playerAttributes:n,callback:function(){e(n)}})})}},{key:"playerAudioRouteChange",value:function(e){var t=this,s=e.soundMode;return new Promise(function(e){t.InterfaceEventEmitter.emit("playerAudioRouteChange",{soundMode:s,callback:function(){e(s)}})})}},{key:"setAttributes",value:function(e,t,s){return A(this,0,void 0,_().mark(function n(){var o,i,r,a,c=this;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return i=e.params,r=e.streamId,E(o={},h.setPlayer,function(){return A(c,0,void 0,_().mark(function e(){var t;return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.playerAttributesChange({playerAttributes:this.setTRTCPlayerAttributes(r,i),streamId:r});case 2:return t=e.sent,e.abrupt("return",t);case 4:case"end":return e.stop()}},e,this)}))}),E(o,h.setPusher,function(){return A(c,0,void 0,_().mark(function e(){var s,n;return _().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("enterRoom"!==t){e.next=5;break}return e.next=3,this.pusherAttributesChange(this.trtc.enterRoom(i));case 3:return s=e.sent,e.abrupt("return",s);case 5:return e.next=7,this.pusherAttributesChange(this.trtc.setPusherAttributes(i));case 7:return n=e.sent,e.abrupt("return",n);case 9:case"end":return e.stop()}},e,this)}))}),a=o,n.abrupt("return",this.retryWithTimeout(function(){return a[s]?a[s]():Promise.reject(Object.assign(new Error("setAttributes fail"),{errorCode:-1}))},2e3,3));case 5:case"end":return n.stop()}},n,this)}))}},{key:"retryWithTimeout",value:function(e,t,s){return A(this,0,void 0,_().mark(function n(){var o,i,r;return _().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:o=null,i=0;case 2:if(!(i<s)){n.next=19;break}return n.prev=3,ne.info("setAttributes ".concat(i+1,"st retry")),n.next=7,Promise.race([e(),new Promise(function(e,s){return setTimeout(function(){return s(new Error("setAttributes timed out"))},t)})]);case 7:return r=n.sent,n.abrupt("return",r);case 11:if(n.prev=11,n.t0=n.catch(3),-1!==(null===n.t0||void 0===n.t0?void 0:n.t0.errorCode)){n.next=15;break}return n.abrupt("return",n.t0);case 15:o=n.t0;case 16:i++,n.next=2;break;case 19:throw o;case 20:case"end":return n.stop()}},n,null,[[3,11]])}))}}],[{key:"getTRTCShareInstance",value:function(){return t.instance||(t.instance=new t),t.instance}},{key:"destroyTRTCShareInstance",value:function(){t.instance&&(t.instance.destroy(),t.instance=null)}}]),t}();!function(e,t,s,n){var o,i=arguments.length,r=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,s):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,s,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(r=(i<3?o(r):i>3?o(t,s,r):o(t,s))||r);i>3&&r&&Object.defineProperty(t,s,r)}([function(e,t,s){var n=s.value;return s.value=function(){for(var e=this,t=arguments.length,s=new Array(t),o=0;o<t;o++)s[o]=arguments[o];var i=s[0],r=s[1];return new Promise(function(t,s){var o;try{G.addTask(new L({ctx:e,priority:(null===(o=b[r])||void 0===o?void 0:o.priority)||0,action:n,args:i,name:r,resolve:t,reject:s}))}catch(e){s(e)}})},s}],ie.prototype,"setAttributes",null),e.TRTCCloud=ie,e.default=ie,e.translateBeautyStyle=H,e.translateTRTCAppScene=U,e.translateTRTCAudioRoute=B,e.translateTRTCStreamId=F,e.translateTRTCVideoMirrorType=q,e.translateTRTCVideoResolution=V,e.translateTRTCVideoResolutionMode=function(t){switch(t){case e.TRTCVideoResolutionMode.TRTCVideoResolutionModeLandscape:return"horizontal";case e.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait:return"vertical";default:return""}},e.translateTRTCVideoRotation=$,e.translateTRTCVideoStreamType=k,e.translateVideoFillMod=W}(te)),te}!function(e){e.exports=function(e){var t={};function s(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,s),o.l=!0,o.exports}return s.m=e,s.c=t,s.d=function(e,t,n){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(s.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)s.d(n,o,function(t){return e[t]}.bind(null,o));return n},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=3)}([function(e,t){e.exports=ae()},,,function(e,t,s){t.__esModule=!0;var n=s(0);Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return n[e]}})});var o,i=(o=n)&&o.__esModule?o:{default:o};t.default=i.default}])}(ee);var ce=X(ee.exports),ue={exports:{}};!function(e){e.exports=function(){const e=e=>void 0===e,t=e=>"string"==typeof e,s=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},n=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===s(e),o=e=>null!==e&&"object"==typeof e,i=e=>n(e)||o(e),r=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},a=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function c(e=99999999){return Math.round(Math.random()*e)}const u=(t,s,n,o)=>{if(!i(t)||!i(s))return 0;let r=0;const a=Object.keys(s);let c;for(let l=0,d=a.length;l<d;l++)if(c=a[l],!(e(s[c])||n&&n.includes(c)))if(i(t[c])&&i(s[c]))r+=u(t[c],s[c],n,o);else{if(o&&o.includes(s[c]))continue;t[c]!==s[c]&&(t[c]=s[c],r+=1)}return r};function l(e){let t,s,n=e;e.length%8!=0&&(n="0".repeat(8-e.length%8)+e);let o="";for(let e=0,{length:i}=n;e<i;e+=8)t=parseInt(n.slice(e,e+4),2),s=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(t)+base16Map.get(s);return o}const d={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},h=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var p;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE"}(p||(p={}));const g="LiteChat",_={[p.DEBUG]:console.debug,[p.INFO]:console.info,[p.WARN]:console.warn,[p.ERROR]:console.error},m={[p.INFO]:4,[p.WARN]:5,[p.ERROR]:6},f=1e3,v=2,I=5e3,E=50,C={CHINA:"CHINA",OVERSEA:"OVERSEA",SINGAPORE:"SINGAPORE",KOREA:"KOREA",GERMANY:"GERMANY",IND:"IND",JPN:"JPN",USA:"USA",INDONESIA:"INDONESIA",KSA:"KSA"},y={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"},KSA:{DEFAULT:"wss://wssksa-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",IPV6:"wss://wsssgpv6.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4s.my-cpaas.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",IPV6:"wss://wsskrv6.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4k.my-cpaas.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",IPV6:"wss://wssgerv6.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4g.my-cpaas.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",IPV6:"wss://wssindv6.im.qcloud.com",BACKUP:"wss://wssind.im.qcloud.com",BACKUP_WEB_ONLY:"wss://*w4i.my-cpaas.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.19.46"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",IPV6:"wss://wssjpnv6.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4j.my-cpaas.com",STAT:"https://apijpn.my-imcloud.com",ANYCAST:"wss://162.14.13.254"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",IPV6:"wss://wssusav6.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4u.my-cpaas.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",IPV6:"wss://wssidnv6.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4y.my-cpaas.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"},KSA:{INITIAL:"wss://*w4a.my-imcloud.com",DEFAULT:"wss://wssksa.im.qcloud.com",IPV6:"wss://wssksav6.im.qcloud.com",BACKUP:"wss://wssksa.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4a.my-cpaas.com",STAT:"https://apiksa.my-imcloud.com",ANYCAST:"wss://43.164.68.251"}}};var S;!function(e){e[e.CONV_DELETED=1]="CONV_DELETED",e[e.CONV_PINED=2]="CONV_PINED",e[e.CONV_UNPINED=3]="CONV_UNPINED",e[e.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",e[e.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",e[e.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",e[e.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED"}(S||(S={}));var M=Object.freeze({__proto__:null,ACCESS_ENVIRONMENT:C,CONSOLE_METHOD:_,CloudConfigReportLevelMap:m,get ConvModifyPushType(){return S},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:E,DEFAULT_GLOBAL_THROTTLE_TIME:I,DEFAULT_SINGLE_MAX_TOTAL_COUNT:v,DEFAULT_SINGLE_THROTTLE_TIME:f,ENUM_PLATFORM:d,HOST_CONFIG:y,IS_TOPIC_MESSAGE:2,get LogLevel(){return p},NOT_NEED_CRC_SERVCMD:h,SDK_NAME:g});const T="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform)&&void 0===wx.getSystemInfoSync().uniPlatform,R="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||T,A=R&&"function"==typeof wx.createGamePortal,O="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),D="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),b=D&&"function"==typeof tt.onShow,L="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),w="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,P="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,G=R&&"object"==typeof wx.miniapp,U="undefined"!=typeof uni,k=D&&"function"==typeof tt.enterChat,F=R||O||D||L||N||P||w,x="undefined"==typeof window&&!F&&void 0!==Q&&void 0!==Q.NativeScriptGlobals,V=void 0!==Q&&(void 0!==Q.nativeModuleProxy||void 0!==Q.ReactNative),$="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),q="undefined"!=typeof uni?!F:"undefined"!=typeof window&&!F&&!V,B=O?qq:D?tt:L?swan:N?my:R?wx:P?uni:w?jd:{},j=q&&window&&window.navigator&&window.navigator.userAgent||"",H=/(micromessenger|webbrowser)/i.test(j),K=function(){let e="WEB";return H?e="WEB":O?e="QQ_MP":D?e="TT_MP":L?e="BAIDU_MP":N?e="ALI_MP":R?e=G?"DONUT_NATIVE_APP":"WX_MP":P?e="UNI_NATIVE_APP":x?e="NS_NATIVE_APP":V&&(e="RN_NATIVE_APP"),d[e]}(),W=/iPad/i.test(j),Y=/iPhone/i.test(j)&&!W,z=/iPod/i.test(j),J=Y||W||z,X=function(){const e=j.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),Z=/Android/i.test(j),ee=function(){const e=j.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),s=e[2]&&parseFloat(e[2]);return t&&s?parseFloat(`${e[1]}.${e[2]}`):t||null}(),te=/Firefox/i.test(j),se=/Edge/i.test(j),ne=!se&&/Chrome/i.test(j),oe=/MSIE/.test(j)||j.indexOf("Trident")>-1&&j.indexOf("rv:11.0")>-1,ie=function(){const e=/MSIE\s(\d+)\.\d/.exec(j);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(j)&&/rv:11.0/.test(j)&&(t=11),t}(),re=/Safari/i.test(j)&&!ne&&!Z&&!se,ae=/Windows/i.test(j),ce=/MAC OS X/i.test(j),ue=q&&"undefined"!=typeof Worker&&!oe,le=Z||J,de=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!J||e||re)}();function he(){let e="unknown";if(ce&&(e="mac"),ae&&(e="windows"),J&&(e="ios"),Z&&(e="android"),F)try{const{platform:t}=B.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const pe="undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&"undefined"==typeof window;function ge(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}function _e(e,t,s,n){return new(s||(s=Promise))(function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(r,a)}c((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const me=2800,fe=2801,ve=3e3,Ie="application/x-www-form-urlencoded;charset=UTF-8";function Ee(e){return _e(this,arguments,void 0,function*({method:e,url:t,data:s,timeout:n=ve}){return F?new Promise((o,i)=>{B.request({url:t,data:s,method:e,timeout:n,header:{"content-type":Ie},success:e=>o(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${me}}`))})}):pe?void 0:new Promise((o,i)=>{const r=new XMLHttpRequest,a=setTimeout(()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${fe}}`))},n);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{o(r.responseText?JSON.parse(r.responseText):null)}catch(e){o(r.responseText)}else i(new Error(`{"message":"Network error","code":${me}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",Ie),r.send(s||null)})})}function Ce(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(a(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return("[object Map]"===Object.prototype.toString.call(e)||"[object Set]"===Object.prototype.toString.call(e)||"[object File]"===Object.prototype.toString.call(e))&&0===e.size}function ye(e,t){if(null===e||"object"!=typeof e)return e;const s=t||new WeakMap;if(s.has(e))return s.get(e);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const t=new Map;return s.set(e,t),e.forEach((e,n)=>{t.set(ye(n,s),ye(e,s))}),t}if(e instanceof Set){const t=new Set;return s.set(e,t),e.forEach(e=>{t.add(ye(e,s))}),t}if(Array.isArray(e)){const t=[];return s.set(e,t),e.forEach(e=>{t.push(ye(e,s))}),t}const n=Object.getPrototypeOf(e),o=Object.create(n);return s.set(e,o),[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach(t=>{if("__ob__"===t||"__v_skip"===t||"__v_isRef"===t||"__v_isReadonly"===t)return;const n=Object.getOwnPropertyDescriptor(e,t);n&&(n.get||n.set?Object.defineProperty(o,t,n):o[t]=ye(e[t],s))}),o}function Se(e,t,s){const n=new WeakSet,o=(e,s)=>{if(t&&(s=t(e,s)),void 0===s)return"undefined";if(null===s)return null;if(Number.isNaN(s))return"NaN";if(s===1/0)return"Infinity";if(s===-1/0)return"-Infinity";if("function"==typeof s)return`[Function: ${s.name||"anonymous"}]`;if("symbol"==typeof s)return s.toString();if("bigint"==typeof s)return`${s.toString()}n`;if("object"==typeof s&&null!==s){if(n.has(s))return"[Circular]";n.add(s)}return s instanceof Date?s.toISOString():s instanceof Error?{name:s.name,message:s.message,stack:s.stack}:s instanceof Map?{dataType:"Map",value:Array.from(s.entries())}:s instanceof Set?{dataType:"Set",value:Array.from(s.values())}:s};try{return JSON.stringify(e,o,s)}catch(e){return console.error("Failed to stringify:",e),""}}function Me(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}var Te,Re=Object.freeze({__proto__:null,ANDROID_VERSION:ee,IE_VERSION:ie,IN_ALIPAY_MINI_APP:N,IN_BAIDU_MINI_APP:L,IN_BROWSER:q,IN_DONUT_NATIVE_APP:G,IN_FEISHU_MINI_APP:k,IN_JD_MINI_APP:w,IN_MINI_APP:F,IN_NODE:pe,IN_NS_NATIVE_APP:x,IN_QQ_MINI_APP:O,IN_RN_APP:V,IN_TT_MINI_APP:D,IN_TT_MINI_GAME:b,IN_UNI_APP:U,IN_UNI_NATIVE_APP:P,IN_WX_MINI_APP:R,IN_WX_MINI_APP_DESK:T,IN_WX_MINI_GAME:A,IN_WX_MINI_PLUGIN:$,IOS_VERSION:X,IS_ANDROID:Z,IS_CHROME:ne,IS_EDGE:se,IS_FIREFOX:te,IS_IE:oe,IS_IOS:J,IS_IPAD:W,IS_IPHONE:Y,IS_IPOD:z,IS_MAC:ce,IS_SAFARI:re,IS_WECHAT:H,IS_WIN:ae,IS_WORKER_AVAILABLE:ue,MINI_APP_NAMESPACE:B,USER_AGENT:j,base16EncodeBinaryString:l,deepCopyWithMethods:ye,deepMerge:u,generatePromise:Me,getPlatformType:he,getType:s,httpRequest:Ee,isArray:n,isArrayOrObject:i,isEmpty:Ce,isH5:le,isIOSWebView:de,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:o,isPlainObject:a,isString:t,isUndefined:e,isUniIOSApp:function(){return P&&"ios"===uni.getDeviceInfo().platform.toLocaleLowerCase()},isValidRequestKey:r,platform:K,randomInt:c,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let s=32;s>0;--s)t+=e[Math.floor(62*Math.random())];return t},safeStringify:Se});class Ae{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,t,s){var n;t&&(this.listeners[e]=null===(n=this.listeners[e])||void 0===n?void 0:n.filter(e=>{const n=e.fn===t,o=!s||e.context===s;return!(n&&o)}))}emit(e,...t){const s=this.listeners[e];s&&s.forEach(s=>{const{fn:n,context:o}=s;try{n.apply(o,t)}catch(t){console.warn(`Error in event handler for ${e} error: ${Se(t)}`)}})}once(e,t,s){const n=(...o)=>{t.apply(s,o),this.off(e,n)};this.on(e,n)}}!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="c2c_realtime_message",e.C2C_MESSAGE_MODIFIED="c2c_message_modified",e.C2C_REVOKED_MESSAGE="c2c_message_revoked",e.GROUP_REALTIME_MESSAGE="group_realtime_message",e.GROUP_MESSAGE_MODIFIED="group_message_modified",e.GROUP_MESSAGE_REVOKED="group_message_revoked",e.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",e.MESSAGE_REACTION_UPDATED="message_reaction_updated",e.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",e.GROUP_AT_TIPS="group_at_tips",e.USER_STATUS_UPDATE="user_status_update",e.FRIEND_LIST_MODIFIED="friend_list_modified",e.PROFILE_MODIFIED="profile_modified",e.CONV_MODIFIED="conversation_modified",e.GROUP_TIPS_NOTIFICATION="group_tips_notification",e.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",e.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",e.GROUP_SYSTEM_NOTIFICATION="group_system_notification",e.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",e.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",e.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",e.FOLLOW_LIST_UPDATED="follow_list_updated",e.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",e.ALL_MESSAGE_READ="all_message_read",e.CONVERSATION_MARK_UPDATED="conversation_mark_updated",e.CONVERSATION_GROUP_ADD="conversation_group_add",e.CONVERSATION_GROUP_DELETED="conversation_group_deleted",e.CONVERSATION_GROUP_UPDATED="conversation_group_updated",e.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",e.TOPIC_AT_TIPS="topic_at_tips",e.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",e.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",e.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",e.TOPIC_LATEST_MESSAGE="topic_latest_message",e.GROUP_MESSAGE_PINNED="group_message_pinned"}(Te||(Te={}));const Oe=[16,17];function De(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach(e=>{var t;2===e.GroupInfo.MillionGroupFlag?s.push(Te.TOPIC_TIPS_NOTIFICATION):Oe.includes(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.OpType)?s.push(Te.GROUP_MESSAGE_PINNED):s.push(Te.GROUP_TIPS_NOTIFICATION)}),s}const be=[{conditions:[{type:"event",value:100}],subType:Te.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Te.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Te.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Te.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Te.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Te.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Te.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Te.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Te.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Te.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.C2cNotifyMsgArray)||void 0===t||t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(Te.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(Te.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(Te.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(Te.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:De},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(Te.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(Te.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(Te.TOPIC_MESSAGE_READ_SYNC):s.push(Te.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(Te.TOPIC_SYSTEM_NOTIFICATION):s.push(Te.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:De},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach(e=>{const{GroupAtTips:{TopicId:t}}=e;t?s.push(Te.TOPIC_AT_TIPS):s.push(Te.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach(e=>{switch(e.PushType){case S.CONV_MARK_UPDATED:s.push(Te.CONVERSATION_MARK_UPDATED);break;case S.CONV_GROUP_ADDED:s.push(Te.CONVERSATION_GROUP_ADD);break;case S.CONV_GROUP_DELETED:s.push(Te.CONVERSATION_GROUP_DELETED);break;case S.CONV_GROUP_UPDATED:s.push(Te.CONVERSATION_GROUP_UPDATED);break;default:s.push(Te.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Te.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Te.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Te.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Te.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Te.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Te.ALL_MESSAGE_READ}];var Le;function Ne(e){var t;const s=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],n=[];return s.forEach(t=>{t.Flag=e.body.Flag;const s=be.find(e=>e.conditions.every(e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}));if(!s)return null;let o=[];"function"==typeof s.subTypeParser?o=s.subTypeParser(t):s.subType&&(o=s.subType),Array.isArray(o)?o.forEach(e=>{n.push({type:`${Le.SERVER_PUSH_MESSAGE}:${e}`,data:t})}):n.push({type:`${Le.SERVER_PUSH_MESSAGE}:${o}`,data:t})}),n}!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",e.ERROR="error"}(Le||(Le={}));const we={[Le.SERVER_PUSH_MESSAGE]:Ne,[Le.SERVER_PUSH_MESSAGE_MULTIPLE]:Ne,[Le.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}},Pe=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Ae,this._innerEventEmitter=new Ae,this.InnerEventSubType=Te}subscribeInnerEvent(e,t,s,n,o){var i;let r,a,c,u;["string","number"].includes(typeof t)?(c=`${e}:${t}`,u=s,a=n,r=o):(c=e,u=t,a=s,r="function"==typeof n?n:void 0),r?this._subscribeWithFilter(c,u,a,r):null===(i=this._innerEventEmitter)||void 0===i||i.on(c,u,a)}emitInnerEvent(e,t){var s,n;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(we).includes(e)){const s=null===(n=we[e])||void 0===n?void 0:n.call(we,t);null==s||s.forEach(e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))})}}subscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.off(e,t,s)}unSubscribeInnerEvent(e,t,s,n){if(["string","number"].includes(typeof t)){const o=s,i=`${e}:${t}`;this._unsubscribeEvent(i,o,n)}else{const n=t;this._unsubscribeEvent(e,n,s)}}emitOuterEvent(e,t){var s;null===(s=this._outerEventEmitter)||void 0===s||s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(e,t,s,n){var o;const i=e=>{n.call(s,e)&&t.call(s,e)};this._filteredCallbackMap.has(e)||this._filteredCallbackMap.set(e,[]),this._filteredCallbackMap.get(e).push({originalCallback:t,filteredCallback:i,filter:n,context:s}),null===(o=this._innerEventEmitter)||void 0===o||o.on(e,i,s)}_unsubscribeEvent(e,t,s){var n,o;const i=this._filteredCallbackMap.get(e);if(i){const o=i.findIndex(e=>e.originalCallback===t&&e.context===s);if(-1!==o){const{filteredCallback:t}=i[o];return null===(n=this._innerEventEmitter)||void 0===n||n.off(e,t,s),i.splice(o,1),void(0===i.length&&this._filteredCallbackMap.delete(e))}}null===(o=this._innerEventEmitter)||void 0===o||o.off(e,t,s)}};class Ge{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,s;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=n,this._socket.onerror=o,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Ue{constructor(e){this._onError=e.onError}connectSocket(e){const t=this;return this._socket=B.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{},fail:e=>t._onError(e)}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.onClose(n),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(o),this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const ke="CONNECT",Fe="SEND",xe="DISCONNECT",Ve="OPEN",$e="MESSAGE",qe="CLOSE",Be="ERROR",je="SEND_FAIL";class He{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){const t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:ke,url:e})}send(e){var t,s;try{null===(t=this._worker)||void 0===t||t.postMessage({type:Fe,data:e})}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;if(this._worker){const e={[Ve]:t,[$e]:s,[qe]:n,[Be]:o,[je]:i};this._onSendFail=i,this._worker.onmessage=t=>{var s;const{type:n}=(null==t?void 0:t.data)||{};"function"==typeof e[n]&&(null===(s=e[n])||void 0===s||s.call(e,null==t?void 0:t.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:xe}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class Ke{}var We,Ye=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return F?N?my.getStorageSync({key:e}).data:B.getStorageSync(e):this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){F?N?my.setStorageSync({key:e,data:JSON.stringify(t)}):B.setStorageSync(e,JSON.stringify(t)):this._canUseLocalStorage()&&localStorage.setItem(e,JSON.stringify(t))}clear(e){"string"==typeof e?this._store.set(e,{}):this._store.clear()}clearLocalStorage(e){this._canUseLocalStorage()&&("string"==typeof e?localStorage.setItem(e,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return"undefined"!=typeof window&&navigator&&navigator.cookieEnabled&&localStorage}};class ze{connectSocket(e){return this._socket=B.connectSocket({url:e,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.onClose(n),this._socket.onOpen(t),this._socket.onMessage(e=>s(null==e?void 0:e.data)),this._socket.onError(()=>o),this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(We||(We={}));class Je{constructor(e){this._url="",this._readyState=We.DISCONNECTED,this._url=e,this._id=c(),this._emitter=new Ae,N?this._socket=new ze:R||P||D||O||w||L?this._socket=new Ue({onError:this._onError.bind(this)}):pe?this._socket=new Ke:this._canUseWebWorker()?this._socket=new He:this._socket=new Ge,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[We.CONNECTED,We.CONNECTING].includes(this._readyState)||(this._readyState=We.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==We.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[We.CONNECTED,We.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(e,t,s){this._emitter.on(e,t,s)}off(e,t,s){this._emitter.off(e,t,s)}isConnected(){return this._readyState===We.CONNECTED}disconnect(){this._readyState=We.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===We.CONNECTING&&(this._readyState=We.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=We.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=We.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=We.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const t=Ye.get("cloudConfig")||{};return(e(t.isWorkerEnabled)||"1"===t.isWorkerEnabled)&&ue}}const Qe={[C.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[C.KOREA]:[[3e7,4e7],[173e7,174e7]],[C.GERMANY]:[[4e7,5e7],[174e7,175e7]],[C.IND]:[[5e7,6e7],[175e7,176e7]],[C.JPN]:[[6e7,7e7],[176e7,177e7]],[C.USA]:[[7e7,8e7],[177e7,178e7]],[C.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[C.KSA]:[[9e7,1e8],[179e7,18e8]]};function Xe(e){var t;if(null===(t=Ye.get("instance"))||void 0===t?void 0:t.oversea)return C.OVERSEA;for(const t of Object.keys(Qe))for(const[s,n]of Qe[t])if(e>=s&&e<n)return t;return C.CHINA}var Ze,et="1.6.15";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",e.BACKUP_CN="BACKUP_CN",e.ANYCAST="ANYCAST",e.IPV6="IPV6"}(Ze||(Ze={}));let st=Ze.INITIAL;function nt(){const e=Math.random();return 0===e?nt():e}function ot(e,t){const{isBinary:s=!1}=t||{},n=Ye.get("instance"),{sdkAppId:o,instanceId:i}=n,r=nt(),a=he(),c=function(){const e=he();let t=-1;return"ios"===e?t=X||-1:"android"===e&&(t=ee||-1),t}(),u=(l={sdkappid:o,instanceid:i,random:r,platform:K,host:a,version:c,sdkversion:et},Object.keys(l).map(e=>`${e}=${l[e]}`).join("&"));var l;return s?`${e}/binfo?${u}&compress=gzip`:`${e}/info?${u}`}function it(e){const t=Ye.get("instance"),{sdkAppId:s,testEnv:n,proxyServer:o}=t,i=Xe(s);if(n)return ot(y.TEST[i].DEFAULT,{isBinary:e});if(!Ce(o))return ot(o,{isBinary:e});const r=y.PRODUCTION[i],a=q&&r.ANYCAST,c=q,u=!!r.BACKUP_CN;return ot({[Ze.INITIAL]:()=>(st=Ze.DEFAULT,r.DEFAULT),[Ze.DEFAULT]:()=>(st=Ze.IPV6,r.IPV6),[Ze.IPV6]:()=>(st=Ze.BACKUP,r.BACKUP),[Ze.BACKUP]:()=>c?(st=Ze.BACKUP_WEB_ONLY,function(e){const t=Math.floor(10001*Math.random())+1e4;return e.replace("*",String(t))}(r.BACKUP_WEB_ONLY)):u?(st=Ze.BACKUP_CN,r.BACKUP_CN):a?(st=Ze.ANYCAST,r.ANYCAST):r.DEFAULT,[Ze.BACKUP_WEB_ONLY]:()=>u?(st=Ze.BACKUP_CN,r.BACKUP_CN):a?(st=Ze.ANYCAST,r.ANYCAST):r.DEFAULT,[Ze.BACKUP_CN]:()=>(st=a?Ze.ANYCAST:Ze.DEFAULT,r[st]),[Ze.ANYCAST]:()=>(st=Ze.DEFAULT,r.ANYCAST="",r.DEFAULT)}[st](),{isBinary:e})}var rt=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const s=Date.now(),n=s-e;this._timeOffsetWithServer=t+n-s}};const at=16;var ct=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:s,context:n,isOnce:o=!1,intervalMs:i=at}=e,r=Math.max(i,at);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:n,isOnce:o}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex(t=>t.id===e);t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const s=this._taskMap.get(e);s&&(s.intervalMs=t,s.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((e,t)=>e.nextExecuteTime-t.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function ut(e){const t=[];for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n>=55296&&n<=56319){const o=e.charCodeAt(++s)-56320+(n-55296<<10)+65536;t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}else n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function lt(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&r(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=lt(e[s]));return t}function dt(e,t){if(h.includes(e))return 0;const s=ut(JSON.stringify(t));let n=4294967295;const{length:o}=s;for(let e=0;e<o;e++){n^=s[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return(4294967295^n)>>>0}function ht(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ye.get("login")||{},s=Ye.get("instance")||{};return{servcmd:e,ver:"v4",platform:K,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:478343027,sdkability_ext:l(""),cappid:s.applicationID||0,tjgID:"",seq:_t(),cs:0}}(t),o=lt(s);return n.cs=dt(t,o),{head:n,body:o}}function pt(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ye.get("login")||{},s=Ye.get("instance")||{};return{servcmd:e,ver:"v4",platform:K,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:478343027,sdkability_ext:l(""),cappid:s.applicationID||0,seq:_t(),cs:0}}(t),o=lt(s);return n.cs=dt(t,o),{head:n,body:o}}let gt=c();function _t(){return gt=gt<2415919103?gt+1:c(),gt}function mt(){var e;const t=Ye.get("login")||{},s=Ye.get("instance")||{};return{sdk_type:30,sdk_app_id:s.sdkAppId,sdk_version:"1.6.15",tiny_id:Number(t.tinyID),user_id:t.userId||(null===(e=Ye.get("webPush"))||void 0===e?void 0:e.userId),platform:K,instance_id:s.instanceId,trace_id:(new Date).getTime()}}var ft,vt=Object.freeze({__proto__:null,calcBodyCRC:dt,filterProtocolDataInvalidFields:lt,generateCosSpecifiedData:function(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ye.get("login")||{},s=Ye.get("instance")||{};return{servcmd:e,ver:"v4",platform:K,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:478343027,sdkability_ext:l(""),cappid:s.applicationID||0,seq:_t(),cs:0}}(t),o=lt(s);return n.cs=dt(t,o),{head:n,body:o}},generateProtocolData:ht,generateSSOLogProtocolData:pt,generateSequence:_t,getCommonHead:mt,getHostSite:Xe,taskScheduler:ct,timeManager:rt});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(ft||(ft={}));const It={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class Et{constructor(e){this.level=ft.info,this._canSendLog=!0,this._logCreatedAt=rt.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:t,eventType:s=0,message:n="",costTime:o=0,error:i,uiPlatform:r,moreMessage:a="",code:c=0}=e||{};this.eventType=s,this.method=t,this.message=n,this.costTime=o,this.moreMessage=a,this.code=c,i&&this.setError(i),Ce(r)||(this.uiPlatform=r)}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=rt.getTimeOffsetWithServer()}end(e=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=rt.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),e&&this._ssoLogModule.uploadSSOLogData())}setError(e){var t;return e instanceof Error?this._canSendLog?((null===(t=Ye.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=ft.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(e){return Object.keys(e).forEach(t=>{Object.keys(It).includes(t)&&(this[t]=e[t])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach(t=>{const s=t;It[s]&&(e[It[s]]=this[s])}),e}_getUiPlatform(){var e;const t=null===(e=Ye.get("instance"))||void 0===e?void 0:e.scene;if("string"==typeof t){const e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null===(e=Ye.get("instance"))||void 0===e?void 0:e.sdkEdition}}var Ct;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(Ct||(Ct={}));var yt=Ct;const St=20,Mt=6e4,Tt=[4,5,6],Rt="report-logger";var At=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=St,this._maxThreshold=100,this._waitingTime=Mt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=p.DEBUG,this._throttleConfig={global:{throttleTime:I,maxCount:E},single:{throttleTime:f,maxCount:v}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,Pe.subscribeInnerEvent(yt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ct.addTask({id:Rt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=St,evt_rpt_waiting:s=Mt,evt_rpt_level:n=Tt,evt_rpt_sdkappid_bl:o="",evt_rpt_tinyid_wl:i="",evt_rpt_global_throttle_time:r=I,evt_rpt_global_throttle_count:a=E,evt_rpt_single_throttle_time:c=f,evt_rpt_single_throttle_count:u=v}=e||{};this._sdkAppIdBlackList=o.split(",").map(e=>Number(e)),this._waitingTime=Number(s),this._minThreshold=t,this._reportLevel=n,this._tinyIdWhiteList=i.split(","),this._throttleConfig={global:{throttleTime:r,maxCount:a},single:{throttleTime:c,maxCount:u}}}createSSOLogData(e){const t=new Et(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(e){[p.DEBUG,p.ERROR,p.INFO,p.NONE,p.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(p.DEBUG,e,t,s)}info(e,t="",s){this._log(p.INFO,e,t,s)}warn(e,t="",s){this._log(p.WARN,e,t,s)}error(e,t="",s){this._log(p.ERROR,e,t,s)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return _e(this,void 0,void 0,function*(){try{if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const s={Header:mt(),Event:t};Ce(s.Header.user_id)||(yield function(e){const t="imopenstat.tim_web_report_v2",s=pt({servcmd:t,data:e}),n=`${s.head.seq}${t}`;return Yt.sendPacket(s,{requestId:n})}(s)),this._lastReportAt=Date.now()}catch(e){this.debug("uploadSSOLogData",Se(e))}})}_savePlatFormInfo(){var e,t;if(R){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;Ye.set("instance",{appId:e,envVersion:t})}}else q&&Ye.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Ye.get("login")||{},{sdkAppId:s}=Ye.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}_checkThrottle(e){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(e)}_checkGlobalThrottle(){const e=Date.now();if(e-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=e;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(e){const t=Date.now(),s=this._singleThrottleMap.get(e);return s?t-s.startTime>=this._throttleConfig.single.throttleTime?(s.count=1,s.startTime=t,!1):s.count>=this._throttleConfig.single.maxCount||(s.count++,!1):(this._singleThrottleMap.set(e,{count:1,startTime:t}),!1)}_shouldLog(e){return e>=this._logLevel&&this._logLevel!==p.NONE}_shouldReport(e){return this._reportLevel.includes(m[e])}_formatLog(e,t,s){const n=new Date,o=`${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}:${n.getMilliseconds()}`,i=`<${p[e]}>`;return oe||F?[`${g} [${o}] ${i} [${t}] ${s}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",g,"",`[${o}] ${i} [${t}] ${s}`]}_log(e,t,s,n){if(!this._shouldLog(e))return;const o=this._formatLog(e,t,s);if(_[e].apply(console,o),this._shouldReport(e)){const e=this._getThrottleKey(t,s,n);this._checkThrottle(e)||this.createSSOLogData(Object.assign(Object.assign({message:s},n),{method:t})).end()}}_getThrottleKey(e,t,s){const n=`${e}${t}${Se(Object.assign(Object.assign({},s),{costTime:""}))}`,o=ut(JSON.stringify(n));let i=4294967295;const{length:r}=o;for(let e=0;e<r;e++){i^=o[e];for(let e=0;e<8;e++)1&~i?i>>>=1:i=i>>>1^3988292384}return`${(4294967295^i)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),ct.removeTask(Rt),Pe.unSubscribeInnerEvent(yt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=St,this._maxThreshold=100,this._waitingTime=Mt,this._logQueue=[],this._logLevel=p.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Ot=15e3,Dt="Channel",bt="channel_schedule_task",Lt="channel_reconnect_task",Nt="connected",wt="connecting",Pt="disconnected",Gt=1e3,Ut="network_status_change",kt="activity_status_change",Ft="send_fail",xt="reconnect_failed",Vt="socket_error",$t="socket_close";function qt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Bt(e){return Bt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Bt(e)}function jt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ht,Kt={exports:{}},Wt=(Ht||(Ht=1,function(e){e.exports=function e(t,s,n){function o(r,a){if(!s[r]){if(!t[r]){if(!a&&jt)return jt(r);if(i)return i(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=s[r]={exports:{}};t[r][0].call(u.exports,function(e){return o(t[r][1][e]||e)},u,u.exports,e,t,s,n)}return s[r].exports}for(var i=jt,r=0;r<n.length;r++)o(n[r]);return o}({1:[function(e,t,s){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t,s,n=Array.prototype.slice.call(arguments,1);n.length;){var o=n.shift();if(o){if("object"!=Bt(o))throw new TypeError(o+"must be non-object");for(var i in o)t=o,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=o[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,s,n,o){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+n),o);else for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){var t,s,n,o,i,r;for(t=n=0,s=e.length;t<s;t++)n+=e[t].length;for(r=new Uint8Array(n),t=o=0,s=e.length;t<s;t++)i=e[t],r.set(i,o),o+=i.length;return r}},i={arraySet:function(e,t,s,n,o){for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,o)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(n)},{}],2:[function(e,t,s){var n=e("./common"),o=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var r=new n.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&o))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}r[254]=r[254]=1,s.string2buf=function(e){var t,s,o,i,r,a=e.length,c=0;for(i=0;i<a;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),c+=s<128?1:s<2048?2:s<65536?3:4;for(t=new n.Buf8(c),i=r=0;r<c;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),s<128?t[r++]=s:(s<2048?t[r++]=192|s>>>6:(s<65536?t[r++]=224|s>>>12:(t[r++]=240|s>>>18,t[r++]=128|s>>>12&63),t[r++]=128|s>>>6&63),t[r++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new n.Buf8(e.length),s=0,o=t.length;s<o;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,n,o,i,a=t||e.length,u=new Array(2*a);for(s=n=0;s<a;)if((o=e[s++])<128)u[n++]=o;else if(4<(i=r[o]))u[n++]=65533,s+=i-1;else{for(o&=2===i?31:3===i?15:7;1<i&&s<a;)o=o<<6|63&e[s++],i--;1<i?u[n++]=65533:o<65536?u[n++]=o:(o-=65536,u[n++]=55296|o>>10&1023,u[n++]=56320|1023&o)}return c(u,n)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+r[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,n){for(var o=65535&e,i=e>>>16&65535,r=0;0!==s;){for(s-=r=2e3<s?2e3:s;i=i+(o=o+t[n++]|0)|0,--r;);o%=65521,i%=65521}return o|i<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var n=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,o){var i=n,r=o+s;e^=-1;for(var a=o;a<r;a++)e=e>>>8^i[255&(e^t[a])];return-1^e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,n,o,i,r,a,c,u,l,d,h,p,g,_,m,f,v,I,E,C,y,S,M,T,R;s=e.state,n=e.next_in,T=e.input,o=n+(e.avail_in-5),i=e.next_out,R=e.output,r=i-(t-e.avail_out),a=i+(e.avail_out-257),c=s.dmax,u=s.wsize,l=s.whave,d=s.wnext,h=s.window,p=s.hold,g=s.bits,_=s.lencode,m=s.distcode,f=(1<<s.lenbits)-1,v=(1<<s.distbits)-1;e:do{g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),I=_[p&f];t:for(;;){if(p>>>=E=I>>>24,g-=E,0==(E=I>>>16&255))R[i++]=65535&I;else{if(!(16&E)){if(!(64&E)){I=_[(65535&I)+(p&(1<<E)-1)];continue t}if(32&E){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}C=65535&I,(E&=15)&&(g<E&&(p+=T[n++]<<g,g+=8),C+=p&(1<<E)-1,p>>>=E,g-=E),g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),I=m[p&v];s:for(;;){if(p>>>=E=I>>>24,g-=E,!(16&(E=I>>>16&255))){if(!(64&E)){I=m[(65535&I)+(p&(1<<E)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(y=65535&I,g<(E&=15)&&(p+=T[n++]<<g,(g+=8)<E&&(p+=T[n++]<<g,g+=8)),c<(y+=p&(1<<E)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(p>>>=E,g-=E,(E=i-r)<y){if(l<(E=y-E)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(M=h,(S=0)===d){if(S+=u-E,E<C){for(C-=E;R[i++]=h[S++],--E;);S=i-y,M=R}}else if(d<E){if(S+=u+d-E,(E-=d)<C){for(C-=E;R[i++]=h[S++],--E;);if(S=0,d<C){for(C-=E=d;R[i++]=h[S++],--E;);S=i-y,M=R}}}else if(S+=d-E,E<C){for(C-=E;R[i++]=h[S++],--E;);S=i-y,M=R}for(;2<C;)R[i++]=M[S++],R[i++]=M[S++],R[i++]=M[S++],C-=3;C&&(R[i++]=M[S++],1<C&&(R[i++]=M[S++]))}else{for(S=i-y;R[i++]=R[S++],R[i++]=R[S++],R[i++]=R[S++],2<(C-=3););C&&(R[i++]=R[S++],1<C&&(R[i++]=R[S++]))}break}}break}}while(n<o&&i<a);n-=C=g>>3,p&=(1<<(g-=C<<3))-1,e.next_in=n,e.next_out=i,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=i<a?a-i+257:257-(i-a),s.hold=p,s.bits=g}},{}],8:[function(e,t,s){var n=e("../utils/common"),o=e("./adler32"),i=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,u=2,l=0,d=-2,h=1,p=852,g=592;function _(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(p),t.distcode=t.distdyn=new n.Buf32(g),t.sane=1,t.back=-1,l):d}function v(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,f(e)):d}function I(e,t){var s,n;return e&&e.state?(n=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?d:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=s,n.wbits=t,v(e))):d}function E(e,t){var s,n;return e?(n=new m,(e.state=n).window=null,(s=I(e,t))!==l&&(e.state=null),s):d}var C,y,S=!0;function M(e){if(S){var t;for(C=new n.Buf32(512),y=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,C,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(u,e.lens,0,32,y,0,e.work,{bits:5}),S=!1}e.lencode=C,e.lenbits=9,e.distcode=y,e.distbits=5}function T(e,t,s,o){var i,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new n.Buf8(r.wsize)),o>=r.wsize?(n.arraySet(r.window,t,s-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(o<(i=r.wsize-r.wnext)&&(i=o),n.arraySet(r.window,t,s-o,i,r.wnext),(o-=i)?(n.arraySet(r.window,t,s-o,o,0),r.wnext=o,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}s.inflateReset=v,s.inflateReset2=I,s.inflateResetKeep=f,s.inflateInit=function(e){return E(e,15)},s.inflateInit2=E,s.inflate=function(e,t){var s,p,g,m,f,v,I,E,C,y,S,R,A,O,D,b,L,N,w,P,G,U,k,F,x=0,V=new n.Buf8(4),$=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;12===(s=e.state).mode&&(s.mode=13),f=e.next_out,g=e.output,I=e.avail_out,m=e.next_in,p=e.input,v=e.avail_in,E=s.hold,C=s.bits,y=v,S=I,U=l;e:for(;;)switch(s.mode){case h:if(0===s.wrap){s.mode=13;break}for(;C<16;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(2&s.wrap&&35615===E){V[s.check=0]=255&E,V[1]=E>>>8&255,s.check=i(s.check,V,2,0),C=E=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&E)<<8)+(E>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&E)){e.msg="unknown compression method",s.mode=30;break}if(C-=4,G=8+(15&(E>>>=4)),0===s.wbits)s.wbits=G;else if(G>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<G,e.adler=s.check=1,s.mode=512&E?10:12,C=E=0;break;case 2:for(;C<16;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(s.flags=E,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=E>>8&1),512&s.flags&&(V[0]=255&E,V[1]=E>>>8&255,s.check=i(s.check,V,2,0)),C=E=0,s.mode=3;case 3:for(;C<32;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}s.head&&(s.head.time=E),512&s.flags&&(V[0]=255&E,V[1]=E>>>8&255,V[2]=E>>>16&255,V[3]=E>>>24&255,s.check=i(s.check,V,4,0)),C=E=0,s.mode=4;case 4:for(;C<16;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}s.head&&(s.head.xflags=255&E,s.head.os=E>>8),512&s.flags&&(V[0]=255&E,V[1]=E>>>8&255,s.check=i(s.check,V,2,0)),C=E=0,s.mode=5;case 5:if(1024&s.flags){for(;C<16;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}s.length=E,s.head&&(s.head.extra_len=E),512&s.flags&&(V[0]=255&E,V[1]=E>>>8&255,s.check=i(s.check,V,2,0)),C=E=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(v<(R=s.length)&&(R=v),R&&(s.head&&(G=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),n.arraySet(s.head.extra,p,m,R,G)),512&s.flags&&(s.check=i(s.check,p,R,m)),v-=R,m+=R,s.length-=R),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===v)break e;for(R=0;G=p[m+R++],s.head&&G&&s.length<65536&&(s.head.name+=String.fromCharCode(G)),G&&R<v;);if(512&s.flags&&(s.check=i(s.check,p,R,m)),v-=R,m+=R,G)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===v)break e;for(R=0;G=p[m+R++],s.head&&G&&s.length<65536&&(s.head.comment+=String.fromCharCode(G)),G&&R<v;);if(512&s.flags&&(s.check=i(s.check,p,R,m)),v-=R,m+=R,G)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;C<16;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(E!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}C=E=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;C<32;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}e.adler=s.check=_(E),C=E=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=f,e.avail_out=I,e.next_in=m,e.avail_in=v,s.hold=E,s.bits=C,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){E>>>=7&C,C-=7&C,s.mode=27;break}for(;C<3;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}switch(s.last=1&E,C-=1,3&(E>>>=1)){case 0:s.mode=14;break;case 1:if(M(s),s.mode=20,6!==t)break;E>>>=2,C-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}E>>>=2,C-=2;break;case 14:for(E>>>=7&C,C-=7&C;C<32;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if((65535&E)!=(E>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&E,C=E=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(R=s.length){if(v<R&&(R=v),I<R&&(R=I),0===R)break e;n.arraySet(g,p,m,R,f),v-=R,m+=R,I-=R,f+=R,s.length-=R;break}s.mode=12;break;case 17:for(;C<14;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(s.nlen=257+(31&E),E>>>=5,C-=5,s.ndist=1+(31&E),E>>>=5,C-=5,s.ncode=4+(15&E),E>>>=4,C-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;C<3;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}s.lens[$[s.have++]]=7&E,E>>>=3,C-=3}for(;s.have<19;)s.lens[$[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,k={bits:s.lenbits},U=a(0,s.lens,0,19,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;b=(x=s.lencode[E&(1<<s.lenbits)-1])>>>16&255,L=65535&x,!((D=x>>>24)<=C);){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(L<16)E>>>=D,C-=D,s.lens[s.have++]=L;else{if(16===L){for(F=D+2;C<F;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(E>>>=D,C-=D,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}G=s.lens[s.have-1],R=3+(3&E),E>>>=2,C-=2}else if(17===L){for(F=D+3;C<F;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}C-=D,G=0,R=3+(7&(E>>>=D)),E>>>=3,C-=3}else{for(F=D+7;C<F;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}C-=D,G=0,R=11+(127&(E>>>=D)),E>>>=7,C-=7}if(s.have+R>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;R--;)s.lens[s.have++]=G}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,k={bits:s.lenbits},U=a(c,s.lens,0,s.nlen,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,k={bits:s.distbits},U=a(u,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,k),s.distbits=k.bits,U){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=v&&258<=I){e.next_out=f,e.avail_out=I,e.next_in=m,e.avail_in=v,s.hold=E,s.bits=C,r(e,S),f=e.next_out,g=e.output,I=e.avail_out,m=e.next_in,p=e.input,v=e.avail_in,E=s.hold,C=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;b=(x=s.lencode[E&(1<<s.lenbits)-1])>>>16&255,L=65535&x,!((D=x>>>24)<=C);){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(b&&!(240&b)){for(N=D,w=b,P=L;b=(x=s.lencode[P+((E&(1<<N+w)-1)>>N)])>>>16&255,L=65535&x,!(N+(D=x>>>24)<=C);){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}E>>>=N,C-=N,s.back+=N}if(E>>>=D,C-=D,s.back+=D,s.length=L,0===b){s.mode=26;break}if(32&b){s.back=-1,s.mode=12;break}if(64&b){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&b,s.mode=22;case 22:if(s.extra){for(F=s.extra;C<F;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}s.length+=E&(1<<s.extra)-1,E>>>=s.extra,C-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;b=(x=s.distcode[E&(1<<s.distbits)-1])>>>16&255,L=65535&x,!((D=x>>>24)<=C);){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(!(240&b)){for(N=D,w=b,P=L;b=(x=s.distcode[P+((E&(1<<N+w)-1)>>N)])>>>16&255,L=65535&x,!(N+(D=x>>>24)<=C);){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}E>>>=N,C-=N,s.back+=N}if(E>>>=D,C-=D,s.back+=D,64&b){e.msg="invalid distance code",s.mode=30;break}s.offset=L,s.extra=15&b,s.mode=24;case 24:if(s.extra){for(F=s.extra;C<F;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}s.offset+=E&(1<<s.extra)-1,E>>>=s.extra,C-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===I)break e;if(R=S-I,s.offset>R){if((R=s.offset-R)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}R>s.wnext?(R-=s.wnext,A=s.wsize-R):A=s.wnext-R,R>s.length&&(R=s.length),O=s.window}else O=g,A=f-s.offset,R=s.length;for(I<R&&(R=I),I-=R,s.length-=R;g[f++]=O[A++],--R;);0===s.length&&(s.mode=21);break;case 26:if(0===I)break e;g[f++]=s.length,I--,s.mode=21;break;case 27:if(s.wrap){for(;C<32;){if(0===v)break e;v--,E|=p[m++]<<C,C+=8}if(S-=I,e.total_out+=S,s.total+=S,S&&(e.adler=s.check=s.flags?i(s.check,g,S,f-S):o(s.check,g,S,f-S)),S=I,(s.flags?E:_(E))!==s.check){e.msg="incorrect data check",s.mode=30;break}C=E=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;C<32;){if(0===v)break e;v--,E+=p[m++]<<C,C+=8}if(E!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}C=E=0}s.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return d}return e.next_out=f,e.avail_out=I,e.next_in=m,e.avail_in=v,s.hold=E,s.bits=C,(s.wsize||S!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&T(e,e.output,e.next_out,S-e.avail_out)?(s.mode=31,-4):(y-=e.avail_in,S-=e.avail_out,e.total_in+=y,e.total_out+=S,s.total+=S,s.wrap&&S&&(e.adler=s.check=s.flags?i(s.check,g,S,e.next_out-S):o(s.check,g,S,e.next_out-S)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0===y&&0===S||4===t)&&U===l&&(U=-5),U)},s.inflateEnd=function(e){if(!e||!e.state)return d;var t=e.state;return t.window&&(t.window=null),e.state=null,l},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,l):d},s.inflateSetDictionary=function(e,t){var s,n=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?d:11===s.mode&&o(1,t,n,0)!==s.check?-3:T(e,t,n,n)?(s.mode=31,-4):(s.havedict=1,l):d},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var n=e("../utils/common"),o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,c,u,l,d,h){var p,g,_,m,f,v,I,E,C,y=h.bits,S=0,M=0,T=0,R=0,A=0,O=0,D=0,b=0,L=0,N=0,w=null,P=0,G=new n.Buf16(16),U=new n.Buf16(16),k=null,F=0;for(S=0;S<=15;S++)G[S]=0;for(M=0;M<c;M++)G[t[s+M]]++;for(A=y,R=15;1<=R&&0===G[R];R--);if(R<A&&(A=R),0===R)return u[l++]=20971520,u[l++]=20971520,h.bits=1,0;for(T=1;T<R&&0===G[T];T++);for(A<T&&(A=T),S=b=1;S<=15;S++)if(b<<=1,(b-=G[S])<0)return-1;if(0<b&&(0===e||1!==R))return-1;for(U[1]=0,S=1;S<15;S++)U[S+1]=U[S]+G[S];for(M=0;M<c;M++)0!==t[s+M]&&(d[U[t[s+M]]++]=M);if(0===e?(w=k=d,v=19):1===e?(w=o,P-=257,k=i,F-=257,v=256):(w=r,k=a,v=-1),S=T,f=l,D=M=N=0,_=-1,m=(L=1<<(O=A))-1,1===e&&852<L||2===e&&592<L)return 1;for(;;){for(I=S-D,d[M]<v?(E=0,C=d[M]):d[M]>v?(E=k[F+d[M]],C=w[P+d[M]]):(E=96,C=0),p=1<<S-D,T=g=1<<O;u[f+(N>>D)+(g-=p)]=I<<24|E<<16|C,0!==g;);for(p=1<<S-1;N&p;)p>>=1;if(0!==p?(N&=p-1,N+=p):N=0,M++,0==--G[S]){if(S===R)break;S=t[s+d[M]]}if(A<S&&(N&m)!==_){for(0===D&&(D=A),f+=T,b=1<<(O=S-D);O+D<R&&!((b-=G[O+D])<=0);)O++,b<<=1;if(L+=1<<O,1===e&&852<L||2===e&&592<L)return 1;u[_=N&m]=A<<24|O<<16|f-l}}return 0!==N&&(u[f+N]=S-D<<24|64<<16),h.bits=A,0}},{"../utils/common":1}],10:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,s){var n=e("./zlib/inflate"),o=e("./utils/common"),i=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),l=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var s=n.inflateInit2(this.strm,t.windowBits);if(s!==r.Z_OK)throw new Error(a[s]);if(this.header=new u,n.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=i.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=n.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[s])}function h(e,t){var s=new d(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}d.prototype.push=function(e,t){var s,a,c,u,d,h=this.strm,p=this.options.chunkSize,g=this.options.dictionary,_=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=i.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new o.Buf8(p),h.next_out=0,h.avail_out=p),(s=n.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(s=n.inflateSetDictionary(this.strm,g)),s===r.Z_BUF_ERROR&&!0===_&&(s=r.Z_OK,_=!1),s!==r.Z_STREAM_END&&s!==r.Z_OK)return this.onEnd(s),!(this.ended=!0);h.next_out&&(0!==h.avail_out&&s!==r.Z_STREAM_END&&(0!==h.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=i.utf8border(h.output,h.next_out),u=h.next_out-c,d=i.buf2string(h.output,c),h.next_out=u,h.avail_out=p-u,u&&o.arraySet(h.output,h.output,c,u,0),this.onData(d)):this.onData(o.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(_=!0)}while((0<h.avail_in||0===h.avail_out)&&s!==r.Z_STREAM_END);return s===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(s=n.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(h.avail_out=0))},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=d,s.inflate=h,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},s.ungzip=h},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")}(Kt)),Kt.exports),Yt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=Gt,this._currentConnectState=Nt,this._beforeSendInterceptors=[]}init(){ct.addTask({id:bt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Ye.get("instance"),{sdkAppId:s,testEnv:n,disableIndependentDomain:o,proxyServer:i}=t,r=Xe(s);let a="";return n?a=y.TEST[r].DEFAULT:Ce(i)?o?(a=y.PRODUCTION[r].DEFAULT,st=Ze.DEFAULT):a=y.PRODUCTION[r].INITIAL.replace("*",`${s}`):a=i,ot(a,{isBinary:e})}(this._isBinarySupported),Pe.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),Pe.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:n,timeout:o=Ot,canResend:i=!0,shouldRejectOnError:r=!0}=t||{};if(Ce(e))return At.warn("sendPacket",`${Dt}.sendPacket: packet is empty `),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===Pt&&this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Ft});const a=JSON.stringify(e);let c=null;if(n){const{resolve:t,reject:s,promise:u}=Me();c=u,this._pendingRequests.set(n,{resolve:t,reject:s,timestamp:Date.now(),uplinkData:a,timeout:o,canResend:i,requestHead:null==e?void 0:e.head,shouldRejectOnError:r})}const u=this._isBinarySupported?ut(a).buffer:a;return null===(s=this._socketAdapter)||void 0===s||s.send(u),c}connect(){var e;this._socketAdapter=new Je(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${Dt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._connectionId=t,this._ssoLog({method:"connect",message:s})}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),n=`${Dt}.disconnect socketID:${s}`;this._ssoLog({method:"disconnect",message:n}),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Dt}.dispose`),ct.removeTask(bt),ct.removeTask(Lt),Pe.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),Pe.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=Gt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===wt&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return _e(this,void 0,void 0,function*(){const e=`${Dt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=it(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:xt}),At.warn(`${Dt}.reconnect failed: ${Se(e)}`)}}})}_addEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.on("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.on("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.off("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.off("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},n=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,o=`${Dt}.onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${n} code: ${null==s?void 0:s.code} reason: ${null==s?void 0:s.reason}`;this._ssoLog({method:"onClose",message:o}),t===this._connectionId&&this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:$t}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:s}=e||{},n=`${Dt}.onError sourceSocketID: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(s)}`;this._ssoLog({method:"onError",message:n}),t===this._connectionId&&this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Vt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:s}=e||{},n=`${Dt}.onSendFail sendFailSocketId: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${Se(s)}`;this._ssoLog({method:"onSendFail",message:n}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,s;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let s;try{s=Wt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s})(e.data):function(e){const t=new Uint8Array(e);let s="",n=0;const{length:o}=t;for(;n<o;){let e=t[n],i=0,r=0;if(e<=127?(i=0,r=255&e):e<=223?(i=1,r=31&e):e<=239?(i=2,r=15&e):e<=244&&(i=3,r=7&e),o-n-i>0)for(let s=0;s<i;s+=1)e=t[n+s+1],r=r<<6|63&e;else r=65533,i=o-n;s+=String.fromCodePoint(r),n+=i+1}return s}(e.data):e.data,s=JSON.parse(t)}catch(t){const s=`event.data: ${Se(e.data)} error: ${Se(t)}`;return void this._ssoLog({method:"jsonParseError",message:s})}if(!s||!s.head)return;const{seq:n,servcmd:o}=s.head,i=`${n}${o}`;this._pendingRequests.has(i)?this._handleRequestResponse(s):this._handlePushMessage(s)}_handleRequestResponse(e){var t,s;const{seq:n,servcmd:o}=e.head,{int32_error_code:i,str_error_message:r}=(null==e?void 0:e.body)||{},a=(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.ErrorCode)||i,c=(null===(s=null==e?void 0:e.body)||void 0===s?void 0:s.ErrorInfo)||r,u=`${n}${o}`,{resolve:l,reject:d,timestamp:h,headSeq:p,requestHead:g,shouldRejectOnError:_=!0}=this._pendingRequests.get(u);if(this._pendingRequests.delete(u),a&&0!==a&&_)return Pe.emitInnerEvent("error",{errorCode:a,errorInfo:c,requestHead:g}),void d({errorCode:a,errorInfo:c});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:n}=e.body;1===s&&this._sendAck(n),Pe.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;At.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach((e,t)=>{var s;const{uplinkData:n,canResend:o,resolve:i,reject:r,timeout:a}=e;if(o){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:n,timeout:a,canResend:o});const e=this._isBinarySupported?ut(n).buffer:n;null===(s=this._socketAdapter)||void 0===s||s.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){const{socketId:t,event:s={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const n=Date.now()-this._connectionStartTime,o=`${Dt}.onConnect cost:${n} ms. socketID:${t} res:${JSON.stringify(s)}`;if(this._ssoLog({method:"onConnect",message:o}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${Dt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),Pe.emitInnerEvent(yt.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Nt,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){const t=ht({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return _e(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return _e(this,void 0,void 0,function*(){var e;const t=ht({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=Ye.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,n=`${Dt}.sendHeartbeat failed. isNetWorkOnline:${s} error: ${Se(t)}`;this._ssoLog({method:"sendHeartbeatError",message:n}),this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return _e(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=P?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${Dt}.networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t});const{isNetworkOnline:s,networkType:n}=e;s&&"none"!==n?this._handleConnectStateChange({state:Nt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Ut}):this._handleConnectStateChange({state:Pt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Ut})}isPrivateNetWork(){const e=Ye.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,shouldAttemptReconnect:s,shouldEmitEvent:n,reason:o}=e,i=`${Dt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${s} shouldEmitEvent: ${n} reason: ${o}`;this._currentConnectState!==t&&(this._ssoLog({method:"handleConnectStateChange",message:i}),n&&(At.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${t}`),Pe.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),this._currentConnectState=t,t===Pt&&Pe.emitInnerEvent(yt.SOCKET_DISCONNECTED)),s&&(this._resetReconnectDelay(),ct.addTask({id:Lt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(e){var t,s;const n=null===(s=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===s?void 0:s.readyState,o=`${Dt}.activityStatusChange ${JSON.stringify(e)} readyState: ${n}`;At.debug("activityStatusChange",o),3===n&&this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:kt})}_resetReconnectDelay(){var e;At.debug(`${Dt}._resetReconnectDelay`),ct.removeTask(Lt);const t=null===(e=Ye.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Gt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=Ye.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(Gt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const s=(new Date).toTimeString().slice(0,8),n=`${Dt}.scheduleReconnectWithBackoff timeStr: ${s} intendedDelay: ${this._intendedDelay}`;At.debug(n),this.reconnect(),ct.updateTaskInterval(Lt,this._intendedDelay)}_ssoLog(e){const{method:t,message:s}=e;At.info(t,s)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){_e(this,void 0,void 0,function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const s=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Ee({method:"GET",url:s,data:{}})}catch(e){At.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${e.message}`)}})}(this._url),function(e){_e(this,void 0,void 0,function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Ee({method:"GET",url:t,data:{}})}catch(e){At.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${e.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:n,timeout:o}=t;Date.now()-n>=o&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:fe,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Ye.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=he();if((N||R&&"windows"===t||k)&&(this._isBinarySupported=!1),P){const{uniRuntimeVersion:e=""}=B.getSystemInfoSync();(function(e){const t=e.split(".").map(Number),[s=0,n=0,o=0]=t;return s>2||!(s<2)&&(n>2||!(n<2)&&o>=6)})(e)||(this._isBinarySupported=!1)}}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const zt={init:function(e){Ye.set("instance",e),Yt.init()},destroy:function(){Yt.dispose(),Ye.clear(),ct.dispose()},notificationCenter:Pe,channel:Yt,store:Ye,ssoLog:At,utils:Re,common:vt,constants:M},Jt=e=>"function"==typeof e;function Qt(e,t,s){const n=s||[];if(!e||!t)return!1;const o=Object.keys(e).filter(e=>!n.includes(e)),i=Object.keys(t).filter(e=>!n.includes(e));return o.length===i.length&&o.every(n=>!!t.hasOwnProperty(n)&&("object"==typeof e[n]&&null!==e[n]?Qt(e[n],t[n],s):e[n]===t[n]))}var Xt;!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",e.SERVER_CONFIG_UPDATED="onServerConfigUpdated",e.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",e.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",e.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",e.RICH_STATUS_CHANGED="onRichStatusChanged"}(Xt||(Xt={}));var Zt,es=Xt;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated",e.TOPIC_MESSAGE_DELETED="topic_message_deleted",e.TOPIC_MESSAGE_REVOKED="topic_message_revoked",e.TOPIC_MESSAGE_MODIFIED="topic_message_modified",e.TOPIC_NEW_MESSAGE="topic_new_message",e.QUALITY_STAT="quality_stat",e.SYNC_CONVERSATION_LIST="sync_conversation_list",e.HISTORY_MESSAGE_FETCHED="history_message_fetched"}(Zt||(Zt={}));var ts,ss=Zt;!function(e){e.NEW_INVITATION_RECEIVED="newInvitationReceived",e.INVITEE_ACCEPTED="ts_invitee_accepted",e.INVITEE_REJECTED="ts_invitee_rejected",e.INVITATION_CANCELLED="ts_invitation_cancelled",e.INVITATION_TIMEOUT="ts_invitation_timeout",e.INVITATION_MODIFIED="ts_invitation_modified"}(ts||(ts={}));var ns=ts;const os=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),is={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var rs;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(rs||(rs={}));const as={modify:ss.MESSAGE_MODIFIED,delete:ss.MESSAGE_DELETED,revoke:ss.MESSAGE_REVOKED};var cs;!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(cs||(cs={}));const us=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},is),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:rs,Direction:cs}),ls={[as.modify]:ss.TOPIC_MESSAGE_MODIFIED,[as.delete]:ss.TOPIC_MESSAGE_DELETED,[as.revoke]:ss.TOPIC_MESSAGE_REVOKED},ds={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},hs=Object.assign({},ds),ps={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},gs=Object.assign(Object.assign(Object.assign(Object.assign({},ps),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),_s=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),ms={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},fs={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},vs={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},Is=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ms),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:fs,GROUP_TIPS_OPERATION_TYPE:vs}),Es={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Cs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},os),us),hs),gs),_s),Is),Es),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ys={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},Ss={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Ms={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Ts={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Rs={[Ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Ts.USER_STATUS_UPDATE},{stepId:Ts.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Ts.UNREAD_MESSAGE_SYNC,dependency:Ts.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Ts.CONVERSATION_RECOVER},{stepId:Ts.HISTORY_MESSAGE_RECOVER,dependency:Ts.CONVERSATION_RECOVER},{stepId:Ts.BLACKLIST_RECOVER},{stepId:Ts.FRIEND_RECOVER},{stepId:Ts.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Ts.GROUP_REVOKED_NOTICE_RECOVER,dependency:Ts.HISTORY_MESSAGE_RECOVER},{stepId:Ts.GROUP_TIPS_RECOVER,dependency:Ts.HISTORY_MESSAGE_RECOVER},{stepId:Ts.TOPIC_REQUEST_INFO_RESET},{stepId:Ts.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Ts.UNREAD_MESSAGE_SYNC},{stepId:Ts.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Ts.UNREAD_MESSAGE_SYNC},{stepId:Ts.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ts.UNREAD_MESSAGE_SYNC,Ts.CONVERSATION_RECOVER]},{stepId:Ts.EMIT_C2C_MESSAGE_EVENT,dependency:[Ts.UNREAD_MESSAGE_SYNC,Ts.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Ts.C2C_HISTORY_MESSAGE_RECOVER,dependency:Ts.CONVERSATION_RECOVER},{stepId:Ts.STREAM_MESSAGE_RECOVER}],[Ms.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Ts.COMMERCIAL_CONFIG_UPDATE},{stepId:Ts.CLOUD_CONFIG_SYNC},{stepId:Ts.USER_PROFILE_SYNC},{stepId:Ts.UNREAD_MESSAGE_SYNC},{stepId:Ts.FRIEND_AND_BLACKLIST_SYNC},{stepId:Ts.GROUP_LIST_SYNC},{stepId:Ts.CONVERSATION_LIST_SYNC},{stepId:Ts.SIGNALING_MESSAGE_RECOVER,dependency:Ts.UNREAD_MESSAGE_SYNC},{stepId:Ts.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ts.UNREAD_MESSAGE_SYNC]},{stepId:Ts.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ts.UNREAD_MESSAGE_SYNC,Ts.CONVERSATION_LIST_SYNC]},{stepId:Ts.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Ts.GROUP_LIST_SYNC,Ts.CONVERSATION_LIST_SYNC]},{stepId:Ts.CONVERSATION_GROUP_LIST_SYNC},{stepId:Ts.CONVERSATION_GROUP_UPDATE,dependency:[Ts.CONVERSATION_LIST_SYNC,Ts.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Ts.QUALITY_REPORT}],[Ms.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Ts.HANDLE_C2C_NEW_MESSAGE},{stepId:Ts.UNREAD_MESSAGE_SYNC},{stepId:Ts.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ts.HANDLE_C2C_NEW_MESSAGE},{stepId:Ts.EMIT_C2C_MESSAGE_EVENT,dependency:[Ts.HANDLE_C2C_NEW_MESSAGE,Ts.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Ts.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ts.UNREAD_MESSAGE_SYNC]}],[Ms.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Ts.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ts.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ts.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ts.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Ts.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ts.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Ts.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ts.EMIT_GROUP_MESSAGE_EVENT,dependency:[Ts.HANDLE_GROUP_NEW_MESSAGE,Ts.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Ms.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Ts.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ts.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ts.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ts.EMIT_GROUP_TIPS_EVENT,dependency:[Ts.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Ts.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},As={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Os={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},Ds=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var bs,Ls,Ns,ws=Object.freeze({__proto__:null,ERROR_CODE:ys,InnerEvent:ss,NEED_LOG_API:Ds,OuterConstant:Cs,OuterEvent:es,PUSH:Es,QUALITY_METRICS:As,SDK_EDITION:Ss,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Os,SignalingEvent:ns,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Rs,WORKFLOW_NAME:Ms,WORKFLOW_STEP:Ts});!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(bs||(bs={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Ls||(Ls={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(Ns||(Ns={}));const Ps={[Ls.multipleAccount]:"multipleAccount",[Ls.multipleDevice]:"multipleDevice",[Ls.restApi]:"REST_API_Kick",[Ns.multipleAccount]:"multipleAccount",[Ns.multipleDevice]:"multipleDevice",[Ns.restApi]:"REST_API_Kick",[Ns.usersigExpired]:"userSigExpired"},Gs="login_online_presence_task",{ERROR:Us,DESTROY:ks,FORCE_OFFLINE:Fs}=ss,{KICKED_OUT_MULT_ACCOUNT:xs,KICKED_OUT_MULT_DEVICE:Vs,KICKED_OUT_REST_API:$s,ACCOUNT_A2KEY_EXPIRED:qs,MSG_A2KEY_EXPIRED:Bs}=ys;class js{init(){const{notificationCenter:e}=zt;e.subscribeInnerEvent(Fs,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Us,Bs,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),e.subscribeInnerEvent(Us,qs,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),e.subscribeInnerEvent(Us,xs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Us,Vs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Us,$s,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(ks,this._dispose,this)}_handleForceOfflineFromServerPush(e){var t;if(!0===(null===(t=zt.store.get("login"))||void 0===t?void 0:t.isLoggedIn)){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach(e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:s,Instid:n}}=e;this._isCurrentInstanceKickedOut(n)&&this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:s})})}}_extractKickedOutMessages(e){return e.reduce((e,t)=>[...e,...t.C2cNotifyMsgArray||[]],[]).filter(e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)})}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return _e(this,void 0,void 0,function*(){const{kickedOutReasonCode:t}=e,{ssoLog:s,utils:{safeStringify:n}}=zt;try{this._logKickedOutEvent(e),this._shouldLogoutAfterKickedOut(t)?yield zt.login.loginAction.logout(bs.KICKED_OUT):zt.login.loginAction.handleLogoutCompleted()}catch(e){s.debug("_processKickedOutReasonInfo",` fail ${n(e)}`)}finally{zt.notificationCenter.emitOuterEvent(es.KICKED_OUT,{data:{type:Ps[t]},name:es.KICKED_OUT})}})}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,n=`type:${Ps[t]} newInstanceInfo: ${JSON.stringify(s)}`;zt.ssoLog.warn("kickedOut",n)}_isKickedOut(e){return[Ls.multipleAccount,Ls.multipleDevice,Ls.restApi].includes(e)}_isChatLoginEvent(e){const{requestHead:t}=e||{};return 1!==(null==t?void 0:t.idtype)}_shouldLogoutAfterKickedOut(e){return![Ns.usersigExpired,Ls.restApi].includes(e)}_isCurrentInstanceKickedOut(e){const{isLoggedIn:t,statusInstanceId:s}=zt.store.get("login")||{};return!0===t&&e===s}_dispose(){const{notificationCenter:e}=zt;e.unSubscribeInnerEvent(Fs,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Us,qs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Us,Bs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Us,xs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Us,Vs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Us,$s,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(ks,this._dispose,this)}}function Hs(e){return _e(this,void 0,void 0,function*(){const t="im_open_status.wslogin",s=zt.common.generateProtocolData({servcmd:t,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:e}}),n=`${s.head.seq}${t}`,o=yield zt.channel.sendPacket(s,{timeout:9e4,requestId:n});if(o){const{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:n,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:u,ErrorInfo:l,ActionStatus:d}=o;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:n,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:u,errorInfo:l,actionStatus:d}}})}function Ks(){const{store:e}=zt;return Xe(e.get("instance").sdkAppId)!==C.CHINA}function Ws(e){var t;try{const s=Ye.getStorage("errorMessage");if(!e||!s)return"";const n=(null===(t=JSON.parse(s))||void 0===t?void 0:t.errorMessage)||{},{code:o,replacement1:i="",replacement2:r=""}=e;if(!o)return"";const a=Ks()?`${o}_en`:`${o}_cn`;let c=n[n[a]?a:o]||"";return c&&(i&&(c=c.replace("$replacement1",i)),r&&(c=c.replace("$replacement2",r))),c}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Ys extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:n="",data:o="",moreMessage:i=""}=e;let r=n;s&&!n&&(r=Ws(e));let a=s?`${t} failed. error: {"message": ${r}, "code": ${s}}`:`${t} failed. error: {"message": ${r}}`;a=`${a} ${i}`,super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=a,this.data=o}}function zs(e,t){var s;if(e&&!0!==(null===(s=zt.store.get("login"))||void 0===s?void 0:s.isLoggedIn))throw new Ys({code:ys.USER_NOT_LOGGED_IN,functionName:t})}function Js(e,t,s){if(Array.isArray(e))for(let n=0;n<e.length;n++)Qs.call(this,Object.assign(Object.assign({},e[n]),{value:t[n],name:s}));else for(const n in e)Qs.call(this,Object.assign(Object.assign({},e[n]),{value:t[0][n],name:s,key:n}))}function Qs({required:e,rules:t,range:s,value:n,allowEmpty:o,name:i,key:r,customValidator:a}){if(void 0===n){if(e)throw new Ys({functionName:i,message:`[${i}] Missing required params: "${r}"`});return}let c="";if(!t.some(e=>{return e===(t=n,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t})){for(let e=0;e<t.length;e++){let s=t[e];s=s.replace(s[0],s[0].toUpperCase()),c+=`${s}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(n)}.`;throw new Ys({functionName:i,message:e})}if(!1===o){if(Array.isArray(n)&&(0===n.length||"string"==typeof n[0]&&""===n[0].trim()))throw new Ys({functionName:i,message:`${r} can not be empty.`});if("string"==typeof n&&""===n.trim())throw new Ys({functionName:i,message:`${r} can not be empty.`})}if(a&&"function"==typeof a){const e=a(n);if(!0!==e)throw new Ys({functionName:i,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}const Xs=[],Zs={},en={};function tn(e,t){zs(Zs[e],e),Js(en[e],t,e),function(e){Xs.forEach(t=>{const{interceptor:s,context:n}=t;s.apply(n,[e])})}(e)}function sn(e,t){Xs.push({interceptor:e,context:t})}function nn(e){const{params:t,auth:s}=e;t&&"object"==typeof t&&Object.assign(en,t),s&&"object"==typeof s&&Object.assign(Zs,s)}function on(e){return zt.store.get("commercialConfig").get(e)}class rn{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const s=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,s),zt.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at ${new Date(s).toISOString()}`)):(this._workflowStartTimes.set(e,s),zt.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at ${new Date(s).toISOString()}`))},success:(e,t)=>{const s=Date.now();if(t){const n=this._stepStartTimes.get(`${e}-${t}`),o=n?s-n:0;this._stepStartTimes.delete(`${e}-${t}`),zt.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} completed successfully at ${new Date(s).toISOString()} (${o}ms)`)}else{const t=this._workflowStartTimes.get(e),n=t?s-t:0;this._workflowStartTimes.delete(e),zt.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] completed successfully at ${new Date(s).toISOString()} (${n}ms)`)}},error:(e,t,s)=>{const{ssoLog:n,utils:{safeStringify:o}}=zt,i=Date.now();if(t){const r=this._stepStartTimes.get(`${e}-${t}`),a=r?i-r:0;this._stepStartTimes.delete(`${e}-${t}`),n.error("_executeWorkflowStep",`[Workflow ${e}] Step ${t} failed at ${new Date(i).toISOString()} (${a}ms) ${o(s)}`,{error:s})}else{const t=this._workflowStartTimes.get(e),r=t?i-t:0;this._workflowStartTimes.delete(e),n.error("_executeWorkflowStep",`[Workflow ${e}] failed at ${new Date(i).toISOString()} (${r}ms) ${o(s)}`,{error:s})}}}}static getInstance(){return rn._instance||(rn._instance=new rn),rn._instance}static setInstance(e){rn._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,n){if(!this._handlers.has(e))return void zt.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`);if(!Rs[e].find(e=>e.stepId===t))return void zt.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`);const o=this._handlers.get(e);o.has(t)||o.set(t,n?s.bind(n):s)}executeWorkflow(e,t){return _e(this,void 0,void 0,function*(){if(!this._validateWorkflow(e))return;zt.ssoLog.debug("executeWorkflow",`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const s=Rs[e],n={},o={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:o});try{const i=new Map;s.forEach(e=>{i.set(e.stepId,e)});const r={workflowName:e,pendingSteps:new Set(s.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:i,stepResults:n,data:t,cancelToken:o};yield new Promise((t,s)=>{const n=()=>{o.cancelled?t():this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter(e=>!r.runningSteps.has(e)).forEach(o=>{r.completedSteps.has(o)||r.runningSteps.has(o)||this._executeWorkflowStep(o,r,{onComplete:()=>{0!==r.pendingSteps.size?0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter(e=>!r.runningSteps.has(e)).length&&0===r.runningSteps.size&&(zt.ssoLog.debug("executeWorkflow",`Workflow ${e} completed with some steps skipped due to dependency failures`),t()):t()},onError:s,onStepComplete:n})})};n()}),zt.ssoLog.debug("executeWorkflow",`[Workflow ${e}] Completed execution at ${(new Date).toISOString()}`)}catch(t){zt.ssoLog.error("executeWorkflow",`[Workflow ${e}] Failed execution at ${(new Date).toISOString()}`,{error:t})}finally{this._activeWorkflows.delete(e)}})}_executeWorkflowStep(e,s,n){return _e(this,void 0,void 0,function*(){const{workflowName:o,runningSteps:i,stepMap:r,stepResults:a,data:c}=s;i.add(e),this._logWorkflowExecution(o,e,"start");try{const n=r.get(e);let i=null;(null==n?void 0:n.dependency)&&(t(n.dependency)?i=a[n.dependency]:Array.isArray(n.dependency)&&(i={},n.dependency.forEach(e=>{i[e]=a[e]})));const u=this._handlers.get(o).get(e);if(u){const t=yield Promise.resolve(u({data:c,result:i}));a[e]=t,this._logWorkflowExecution(o,e,"success")}s.completedSteps.add(e)}catch(t){const s=`[Workflow].${o}.${e}`,{errorCode:i,errorInfo:r=`${s} failed`}=t||{},a=new Ys({functionName:s,code:i,message:r});zt.ssoLog.error(s,r,{error:a}),this._logWorkflowExecution(o,e,"error",t),n.onError(t)}finally{i.delete(e),s.pendingSteps.delete(e),n.onStepComplete(),n.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Rs).forEach(e=>{this._handlers.has(e)||this._handlers.set(e,new Map)})}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:s}=t;s.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(Rs).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return!!Rs[e]&&!!this._handlers.get(e)}_getExecutableSteps(e){const{pendingSteps:s,completedSteps:o,stepMap:i,workflowName:r}=e;return Array.from(s).filter(e=>{const s=i.get(e)||{},{dependency:a,skipIfDependencyMissing:c=!0}=s;if(!a)return!0;if(t(a))return this._isStepRegistered({workflowName:r,stepId:a})?o.has(a):!c;if(n(a)){if(a.filter(e=>!this._isStepRegistered({workflowName:r,stepId:e})).length>0&&c)return!1;for(const e of a)if(!o.has(e))return!1;return!0}return!1})}_isStepRegistered(e){var t;const{workflowName:s,stepId:n}=e;return null===(t=this._handlers.get(s))||void 0===t?void 0:t.has(n)}_logWorkflowExecution(e,t,s,n){this._logHandlers[s](e,t)}}const an=new Map,cn=({type:e,groupID:t})=>e===Cs.GRP_COMMUNITY||`${t}`.startsWith(fs.COMMUNITY)&&!`${t}`.includes(fs.TOPIC),un=(e="")=>{const t=e.startsWith("GROUP")?e.replace("GROUP",""):e;return t.startsWith(fs.COMMUNITY)&&`${t}`.includes(fs.TOPIC)},ln="openim",dn="million_group_open_http_svc";function hn(e){return _e(this,void 0,void 0,function*(){const{servcmd:t,data:s}=function(e){const{data:t}=e;return pn(t)||gn(t)}(e)?function(e){let{servcmd:t,data:s}=e;return gn(s)?function(e){const{servcmd:t,data:s}=e;let{GroupId:n=""}=s;const o=n;return[n]=o.split(fs.TOPIC),{servcmd:_n(t),data:Object.assign(Object.assign({},s),{GroupId:n,TopicId:o})}}(e):(pn(s)&&(t=_n(t)),{servcmd:t,data:s})}(e):e,n=zt.common.generateProtocolData({servcmd:t,data:s}),o=`${n.head.seq}${t}`;return zt.channel.sendPacket(n,{requestId:o,timeout:e.timeout})})}function pn(e){const{Type:t,GroupId:s,GroupIdList:n=[]}=e,o=s||n[0]||"";return cn({type:t,groupID:o})}function gn(e){const{GroupId:t=""}=e;return un(t)}function _n(e){if(e.includes(ln))return e;const t=e.split(".")[1];return`${dn}.${t}`}function mn(){var e;return null===(e=zt.store.get("login"))||void 0===e?void 0:e.userId}const fn=e=>n(e)||o(e),vn=(t,s,n,o)=>{if(!fn(t)||!fn(s))return 0;let i=0;const r=Object.keys(s);let a;for(let c=0,u=r.length;c<u;c++)if(a=r[c],!(e(s[a])||n&&n.includes(a)))if(fn(t[a])&&fn(s[a]))i+=vn(t[a],s[a],n,o);else{if(o&&o.includes(s[a]))continue;t[a]!==s[a]&&(t[a]=s[a],i+=1)}return i},In={zh:{MSG_IMAGE:"[图片]",MSG_LOCATION:"[位置]",MSG_AUDIO:"[语音]",MSG_VIDEO:"[视频]",MSG_FILE:"[文件]",MSG_CUSTOM:"[自定义消息]",MSG_GRP_TIP:"[群提示消息]",MSG_GRP_SYS_NOTICE:"[群系统通知]",MSG_FACE:"[动画表情]",MSG_MERGER:"[聊天记录]",MSG_STREAM:"[流式消息]",CREATE_GROUP:"创建群组",CREATE_COMMUNITY:"创建社群"},en:{MSG_IMAGE:"[Image]",MSG_LOCATION:"[Location]",MSG_AUDIO:"[Voice]",MSG_VIDEO:"[Video]",MSG_FILE:"[File]",MSG_CUSTOM:"[Custom Messages]",MSG_GRP_TIP:"[Group Notification]",MSG_GRP_SYS_NOTICE:"[Group System Message]",MSG_FACE:"[Animated Sticker]",MSG_MERGER:"[Chat Record]",MSG_STREAM:"[Stream Message]",CREATE_GROUP:"Create Group",CREATE_COMMUNITY:"Create Community"}};function En(e){var t;const s=Ks()?"en":"zh";return(null===(t=In[s])||void 0===t?void 0:t[e])||e}const Cn={[Cs.MSG_IMAGE]:"MSG_IMAGE",[Cs.MSG_LOCATION]:"MSG_LOCATION",[Cs.MSG_AUDIO]:"MSG_AUDIO",[Cs.MSG_VIDEO]:"MSG_VIDEO",[Cs.MSG_FILE]:"MSG_FILE",[Cs.MSG_CUSTOM]:"MSG_CUSTOM",[Cs.MSG_GRP_TIP]:"MSG_GRP_TIP",[Cs.MSG_GRP_SYS_NOTICE]:"MSG_GRP_SYS_NOTICE",[Cs.MSG_FACE]:"MSG_FACE",[Cs.MSG_MERGER]:"MSG_MERGER",[Cs.MSG_STREAM]:"MSG_STREAM"},yn=(t,s)=>{if(e(s))return"";if(t===Cs.MSG_TEXT)return s.text||"";const n=Cn[t];return n?En(n):""},Sn=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],Mn="im_sdk_config_mgr.fetch_config",Tn="im_sdk_config_mgr.push_configv2",Rn="cloud-config",An=2996,On=new class{init(e){this.core=e}};function Dn(e){return _e(this,void 0,void 0,function*(){const{sdkAppId:t}=On.core.store.get("instance")||{},s=On.core.helper.generateProtocolData({servcmd:Mn,data:{uint32_sdkappid:t,uint64_version:e}}),n=`${s.head.seq}${Mn}`;return On.core.channel.sendPacket(s,{requestId:n})})}var bn=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},channel:r}=e;t.subscribeInnerEvent(Tn,this._handlePushedConfig,this),n.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Sn),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){return _e(this,void 0,void 0,function*(){var t;const s={code:0,data:""};return e?(s.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",s):s})}checkMethodCallOverLimit(e){if(!this._cmdFrequencyLimitMap.has(e))return;if(!this._methodCallFrequencyMap.has(e))return void this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});const{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e);let{startTime:n,methodCallCounter:o}=this._methodCallFrequencyMap.get(e);if(Date.now()-n>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(o+=1,this._methodCallFrequencyMap.set(e,{startTime:n,methodCallCounter:o}),o>t)throw new this._core.helper.ChatError({code:An,replacement1:e})}_handlePushedConfig(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;t.info("_handlePushedConfig",s(e)),yield this._updateCloudConfig(e)})}_handleLoginSuccess(){return _e(this,void 0,void 0,function*(){const{ssoLog:e,utils:{safeStringify:t}}=this._core;try{if(this._canFetch()){const s=yield Dn(this._version);e.info("_fetchCloudConfigIfLogin",t(s)),yield this._updateCloudConfig(s)}this._core.helper.taskScheduler.addTask({id:Rn,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(s){e.debug("_fetchCloudConfigIfLogin",t(s))}})}_fetchCloudConfigIfReady(){return _e(this,void 0,void 0,function*(){const{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._canFetch())try{const s=yield Dn(this._version);e.info("_fetchCloudConfigIfReady",t(s)),yield this._updateCloudConfig(s)}catch(s){e.error("_fetchCloudConfigIfReady",t(s))}})}_updateCloudConfig(e){return _e(this,void 0,void 0,function*(){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:t}}))})}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:s,str_json_config:n,uint32_expired_time:o,uint32_sdkappid:i,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(n),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*o}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){return _e(this,void 0,void 0,function*(){var e;let t=null===(e=yield this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;const{isEmpty:s}=this._core.utils;if(!s(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}})}_updateCmdFreqLimitMap(e){e.forEach(e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,count:e.count})})}_reset(){this._core.helper.taskScheduler.removeTask(Rn),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Sn),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Tn,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Ln{constructor(e=0,t=0){this.high=e,this.low=t}equal(e){return null!==e&&this.low===e.low&&this.high===e.high}toString(){const e=Number(this.high).toString(16);let t=Number(this.low).toString(16);if(t.length<8){let e=8-t.length;for(;e;)t=`0${t}`,e--}return e+t}}const Nn={SEARCH_GRP_SNS:new Ln(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Ln(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Ln(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Ln(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Ln(0,Math.pow(2,6)).toString(),USER_STATUS:new Ln(0,Math.pow(2,7)).toString(),CONV_MARK:new Ln(0,Math.pow(2,9)).toString(),CONV_GROUP:new Ln(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Ln(0,Math.pow(2,11)).toString(),MSG_EXT:new Ln(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Ln(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Ln(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Ln(Math.pow(2,7)).toString(),PLUGIN_CS:new Ln(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Ln(Math.pow(2,9)).toString(),PLUGIN_BOT:new Ln(Math.pow(2,10)).toString(),MSG_REACTION:new Ln(Math.pow(2,16)).toString(),FOLLOW:new Ln(Math.pow(2,20)).toString()},wn="CommercialConfig",Pn="commercial-config";var Gn,Un,kn=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){this._core=e;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:o,InnerEvent:i}}=e;s.subscribeInnerEvent(i.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(i.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(i.DESTROY,this._dispose,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,o.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return _e(this,void 0,void 0,function*(){const t=parseInt(e,10).toString(2),{length:s}=t;let n,o=!0;for(let e=s-1,i=0;e>=0;e--,i++)if("1"===t.charAt(e)&&(n=i<32?new Ln(0,2**i).toString():new Ln(2**(i-32),0).toString(),!this._featureMap.get(n))){o=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${wn}.isFeatureEnabled decimalNumber:${e} key:${n} ret:${o}`),{code:0,data:{enabled:o}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return _e(this,void 0,void 0,function*(){var e;const{ssoLog:t,utils:{safeStringify:s},common:{buildAndSendPacket:n}}=this._core;try{this._isFetching=!0;const t=yield n({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}});t&&(this._parseCommercialConfig(t),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){t.error("_fetchAndParseCommercialConfig",s(e))}finally{this._isFetching=!1}})}_syncCommercialConfig(e){return _e(this,void 0,void 0,function*(){const{purchaseBits:t}=(null==e?void 0:e.data)||{};t&&(this._parsePurchaseBits(t),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Pn,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,s=Date.now()>=this._expirationTime;return t&&!this._isFetching&&s}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return _e(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){const{ssoLog:t}=this._core;if("object"!=typeof e)return;const{int32_error_code:s,str_error_message:n,str_purchase_bits:o,uint32_expired_time:i}=e;0===s?(this._parsePurchaseBits(o),this._expirationTime=Date.now()+1e3*i):void 0===s?(t.warn("_parseCommercialConfig",`${wn}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(t.warn("_parseCommercialConfig",`${wn}._parseCommercialConfig errorCode:${s} errorMessage:${n}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){const{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._isValidPurchaseBits(e)){this._purchaseBits=e,this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let s=e.length-1,n=0;s>=0;s--,n++)if(t=n<32?new Ln(0,2**n).toString():new Ln(2**(n-32),0).toString(),"1"===e[s]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Nn,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Nn,t);e&&this._methodKeyMap.set(e,!1)}}else t.warn("_parsePurchaseBits",`${wn}.parsePurchaseBits invalid purchases:${s(e)}`)}_getKeyByValue(e,t){const s=Object.entries(e).find(([e,s])=>s===t);return s?s[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Pn),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},Fn=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,channel:n}=this._core;t.subscribeInnerEvent(s.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:s}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(e)}_handleOverLoadPush(e){const{OverLoadServCmd:t,DelaySecs:s}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:s})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}},xn=new class{constructor(){this.name="ConfigCenter"}install(e){On.init(e),bn.install(e),kn.install(e),Fn.install(e)}},Vn=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return _e(this,void 0,void 0,function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}})}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return _e(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}})}_isExpired(e){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),s={},n=new RegExp(/'/g);for(let e=0;e<t.length;e++){const o=t[e].indexOf(":"),i=t[e].slice(0,o);let r=t[e].slice(o+1);if(!i.startsWith("//")){if(""===r)continue;r=r.replace(n,""),s[i]=r}}return s}}};function $n(e,t){return _e(this,void 0,void 0,function*(){const{cookie:s,syncFlag:n,syncTriggerEvent:o}=e,i="openim.getmsg",r=t.helper.generateProtocolData({servcmd:i,data:{Cookie:s,SyncFlag:n,IsOnlineSync:o,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${i}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:s,C2CRemainingUnreadCount:n,EventArray:o}=e,{unreadMessageList:i,revokedMessageList:c}=function(e,t){const s=[],n=[];return null==e||e.forEach(e=>{var o,i,r;const a=function(e,t){const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,IsNeedReadReceipt:i,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:u,MsgTimeStamp:l,SendMsgControl:d,SupportMessageExtension:h,To_Account:p,TinyId:g,MsgCheckResult:_,CloudCustomData:m,IsPeerRead:f,MsgFlagBits:v,MsgVersion:I,EventArray:E}=e;return{from:s,avatar:n,nick:o,needReadReceipt:1===i,readReceiptSentByPeer:f,clientTime:a,messageFlagBits:v,random:c,sequence:u,time:l,messageControlInfo:d,isSupportExtension:h,to:p,tinyID:g,checkResult:_,cloudCustomData:m,messageVersion:I,eventArray:E,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(i=null===(o=null==e?void 0:e.EventArray)||void 0===o?void 0:o[0])||void 0===i?void 0:i.hasOwnProperty)||void 0===r?void 0:r.call(i,"C2cNotifyMsgArray"))n.push(...function(e){var t;const s=[];return null===(t=e.EventArray)||void 0===t||t.forEach(e=>{var t,n;const{C2cNotifyMsgArray:o}=e,i=null===(n=null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===n?void 0:n.C2cWithdrawInfoArray;Array.isArray(i)&&s.push(...i)}),s}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:n}=a;e.setElement(n),s.push(e)}}),{unreadMessageList:s,revokedMessageList:n}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:c,unreadCountList:s,overflowUnreadCountList:n,cookie:null==e?void 0:e.Cookie,groupTipList:o}}catch(e){console.warn(e)}})}!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(Gn||(Gn={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Un||(Un={}));var qn=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(e){this._core=e;const{constants:t}=e;e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(e){return _e(this,void 0,void 0,function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:s=!1,isAfterLogin:n=!1}=e||{};let o=Gn.START_SYNC;const i=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:o});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:o,syncTriggerEvent:s?Un.NEW_MESSAGE_RECEIVED:Un.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:n=[],revokedMessageList:u=[],overflowUnreadCountList:l,unreadCountList:d,groupTipList:h}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",o=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(n),a.push(...u),this._updateConversationUnreadOptions({unreadCountList:d,overflowUnreadCountList:l,conversationUpdateFieldList:i}),Array.isArray(h)&&r.push(...h),t){const{messages:e}=this._handleNewMessageList(n);c.push(...e)}}return t?{conversationUpdateFieldList:i,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:i,isInstantMessage:!n,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}})}_syncUnreadDBMessageAfterLogin(){return _e(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return _e(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:n}=e,{constants:{OuterConstant:{CONV_C2C:o,CONV_SYSTEM:i}}}=this._core;null==t||t.forEach(e=>{const{From_Account:t,UnreadCount:s}=e;if(t!==i){const e=n.find(({conversationID:e})=>e===`${o}${t}`);e?e.unreadCount=s:n.push({conversationID:`${o}${t}`,unreadCount:s,type:o})}}),null==s||s.forEach(e=>{const{From_Account:t,LastMsgTime:s}=e;t!==i&&(n.find(({conversationID:e})=>e===`${o}${t}`)||n.push({conversationID:`${o}${t}`,type:o,lastMsgTime:s}))})}_syncUnreadDBMessageAfterReOnline(){return _e(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(e){var t;const{messageDataHandler:s}=this._core.message||{},n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a=""}=e;if(o!==n){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:n,avatar:o}=t;i&&r?i===n&&r===o||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}):(e.nick=n,e.avatar=o)}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},s=new Map,n=[];return e.forEach(e=>{this._updateMessageProfile(e);let o=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=o:o=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||n.push(e);else if(this._shouldStoreUnreadMessage(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;s.has(t)?(s.get(t).lastMessage=c,"in"===i&&(r||s.get(t).unreadCount++)):s.set(t,{conversationID:t,type:n,subType:o,unreadCount:r||"in"!==i?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!o||n.push(e)}}),{messages:n,conversationOptions:s}}_shouldStoreUnreadMessage(e){var t;const{conversationID:s}=e,{message:n,appStore:o,utils:{isEmpty:i}}=this._core||{},r=Array.from((null===(t=o.conversationStore.getConversationMap())||void 0===t?void 0:t.keys())||[]),a=this._getLocalLastMessageTime(s);return!n.messageDataHandler.isInMessageList(e)&&r.includes(s)&&this._localConversationIDListBeforeDisconnect.includes(s)&&!i(a)}_fetchUnreadDBMessage(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;try{const n="unread-message-synchronizer._fetchUnreadDBMessage";t.debug("_fetchUnreadDBMessage",`${n} options:${s(e)}`);const o=yield $n(e,this._core);if(!o)return null;const{syncFlag:i,unreadMessageList:r,revokedMessageList:a,cookie:c,unreadCountList:u,overflowUnreadCountList:l,groupTipList:d}=o;return this._parseAndSaveUnreadMessageList(r),{syncFlag:i,cookie:c,unreadMessageList:r,revokedMessageList:a,unreadCountList:u,overflowUnreadCountList:l,groupTipList:d}}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){var s;return t===Gn.START_SYNC||t===Gn.SYNCING&&!(null===(s=this._core)||void 0===s?void 0:s.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach(e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)})}_handleDisconnect(){var e;const{appStore:t}=this._core;this._localConversationIDListBeforeDisconnect=Array.from((null===(e=t.conversationStore.getConversationMap())||void 0===e?void 0:e.keys())||[])}_getLocalLastMessageTime(e){const{message:t}=this._core,s=t.messageDataHandler.getLocalMessageList(e),n=s[s.length-1];return null==n?void 0:n.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Bn=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===document||void 0===document||document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const s="visible"===(null===document||void 0===document?void 0:document.visibilityState);null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:s}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:s})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){null===document||void 0===document||document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},jn=new class{init(e){var t;this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var e,t,s,n,o;const{MINI_APP_NAMESPACE:i,IN_TT_MINI_GAME:r,IN_WX_MINI_GAME:a}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};r||a?(null===(t=null==i?void 0:i.onShow)||void 0===t||t.call(i,()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null===(s=null==i?void 0:i.onHide)||void 0===s||s.call(i,()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):(null===(n=null==i?void 0:i.onAppShow)||void 0===n||n.call(i,()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null===(o=null==i?void 0:i.onAppHide)||void 0===o||o.call(i,()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},Hn=new class{init(e){const{IN_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?jn.init(e):Bn.init(e))}};const Kn="none",Wn="online";var Yn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return _e(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Wn})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Kn})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}},zn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return _e(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:e}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),e.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}})}_deactivateNetworkMonitoring(){if(null!==this._mpNetworkStatusCallback){const{utils:{MINI_APP_NAMESPACE:e}}=this._core;e.offNetworkStatusChange&&e.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(e){var t,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Jn=new class{init(e){const{IN_MINI_APP:t}=e.utils;t?zn.init(e):Yn.init(e)}},Qn=new class{constructor(){this.name="SystemStateMonitor"}install(e){Hn.init(e),Jn.init(e)}};const Xn=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),Zn="tui_room_svr.*";var eo=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Xn}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n}=e;t.subscribeInnerEvent(s.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),n.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),n.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return _e(this,void 0,void 0,function*(){const t="transferBusinessCommand";try{const{serviceCommand:s=Zn}=e||{};if(!this._isValidTransferredCommand(s))throw new this._core.helper.ChatError({code:2995,functionName:t});const n=yield function(e,t){return _e(this,void 0,void 0,function*(){const{helper:s,channel:n}=t,{serviceCommand:o=Zn,data:i}=e||{};let r={};try{r="string"==typeof i?JSON.parse(i):i}catch(e){console.warn(e)}const a=s.generateProtocolData({servcmd:o,data:r}),c=`${a.head.seq}${o}`;return n.sendPacket(a,{requestId:c,shouldRejectOnError:!1})})}(e,this._core);return{code:0,data:n||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}})}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:s}=this._core,{MsgContent:n}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:o}=t;s.emitOuterEvent(o,{name:o,data:n})}_reset(){this._transferredCommands=Xn}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const to=1,so=2,no=3,oo=4,io=5,ro="TIMCustomElem",ao="C2C",co="GROUP",uo="invite",lo="accept",ho="cancel",po="reject",go="modifyInvitation",_o="signaling",mo=8010,fo="signaling-timeout";function vo(e){return e.filter(e=>{if(e.type===ro){const{cloudCustomData:t="",payload:{data:s=""}={}}=e,n=t.match(/"type":"tsignaling"/),o=s.match(/inviteID/),i=s.match(/actionType/);return n||o&&i}return!1})}function Io(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function Eo(e,t){return e.toString(16).padStart(t,"0")}function Co(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var yo=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${_o}.isInvitationValid`,{inviteID:s,groupID:n,inviter:o}=e,i=o===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(s))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(s);if(console.log(`${t} inviteID:${s} inviteeList:${r} groupID:${n}`),n){if(i)return r.length>0;const e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){const t=`${_o}.updateSignaling`,{inviteID:s,inviter:n,inviteeList:o,groupID:i}=e;if(console.log(`${t} inviteID:${s} inviter:${n} groupID:${i}`),i&&this.hasSignaling(s)){const e=o[0],{inviteeList:n}=this._onlineSignalingMap.get(s);n.includes(e)&&(n.splice(n.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${n.length}`)),0===n.length&&this.removeSignaling(s)}else this.removeSignaling(s)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},So=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),s=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:n,inviteeList:o}=s,i=n||o[0];return{signaling:this._createSignaling(s,i),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:s,inviter:n}=t,o=s||n;return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:s,inviteeList:n}=t,o=s||n[0];return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:s,inviter:n}=t,o=s||n;return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,s=this._createTimeoutSignalingData(e),{groupID:n,inviteeList:o,inviter:i}=s,r=n||(t?o[0]:i);return{signaling:this._createSignaling(s,r),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}_createSignalingExtensionOptions(e){var t,s;const{data:n="",onlineUserOnly:o,inviteID:i="",offlinePushInfo:r,actionType:a}=e,c=(null===(s=null===(t=yo.getSignaling(i))||void 0===t?void 0:t.signaling)||void 0===s?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:o||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(n,a)}}_createMessageControlInfo(e,t){const s=t===io&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),n=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:s||n,excludedFromLastMessage:s||n}}_createInviteSignalingData(e){const t=`${_o}._createInviteSignalingData`,{userID:s,timeout:n=0,groupID:o="",inviteeList:i=[]}=e,r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:to,inviter:r,inviteeList:o?i:[s],timeout:n});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${_o}._createAcceptSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviter:o,groupID:i}=yo.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:no,groupID:i,inviter:o,inviteeList:[n]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${_o}._createCancelSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviteeList:o,groupID:i}=yo.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:so,groupID:i,inviter:n,inviteeList:o});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${_o}._createRejectSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviter:o,groupID:i}=yo.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:oo,groupID:i,inviter:o,inviteeList:[n]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${_o}._createTimeoutSignalingData`,{isInviter:s=!1,inviteID:n}=e,{inviteeList:o,inviter:i}=yo.getSignaling(n),r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:io,inviter:i,inviteeList:s?o:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var s,n,o;const{groupID:i=""}=e,r={to:t,conversationType:i?co:ao,priority:"High",payload:{data:JSON.stringify(e)}};return null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.createCustomMessage(r)}_generateInviteID(){return[Eo(Co(32),8),Eo(Co(16),4),Eo(16384|Co(12),4),Eo(32768|Co(14),4),Eo(Co(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:s="",groupID:n=""}=e;return{businessID:1,timeout:0,data:t,inviteID:s,groupID:n}}},Mo=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return _e(this,void 0,void 0,function*(){var t;try{this._validateBeforeInvite(e);const{signaling:s,signalingData:n,signalingExtensionOptions:o}=So.createInviteSignaling(e),i=yield this._sendSignaling(s,o);if(0===(null==i?void 0:i.code)){const{inviteID:e,timeout:o}=n;return yo.saveSignaling(e,Object.assign(Object.assign({},n),{signaling:s})),o>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${fo}-${e}`,intervalMs:1e3*(o+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}return i}catch(e){throw e}})}accept(e){return _e(this,void 0,void 0,function*(){try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:s,signalingData:n,signalingExtensionOptions:o}=So.createAcceptSignaling(e),i=yield this._sendSignaling(s,o);return 0===(null==i?void 0:i.code)?(yo.updateSignaling(n),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(e){return _e(this,void 0,void 0,function*(){try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:n}=So.createCancelSignaling(e),o=yield this._sendSignaling(s,n);return 0===(null==o?void 0:o.code)?(yo.removeSignaling(t),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(e){return _e(this,void 0,void 0,function*(){try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:n}=So.createRejectSignaling(e),o=yield this._sendSignaling(s,n);return 0===(null==o?void 0:o.code)?(yo.removeSignaling(t),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return _e(this,void 0,void 0,function*(){var t,s;const{inviteID:n,data:o}=e;let i="";try{this._validateBeforeModifyInvitation(n);const e=yo.getSignaling(n),{signaling:r}=e,a=ge(e,["signaling"]);i=r.payload.data,a.data=o,r.payload.data=JSON.stringify(a);const c=yield null===(s=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===s?void 0:s.modifyMessage(r);return yo.hasSignaling(n)&&yo.saveSignaling(n,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(i){const{signaling:e}=yo.getSignaling(n);e.payload.data=i}throw e}})}getSignalingInfo(e){const{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0===vo([e]).length)return;const n=Io(e),o={businessID:n.businessID||1,inviteID:n.inviteID,groupID:n.groupID||"",inviter:n.inviter||"",inviteeList:n.inviteeList||[],data:n.data||"",actionType:n.actionType||to,timeout:n.timeout||0};return t.debug(`${_o} getSignalingInfo ${s(o)}`),o}addSignalingListener(e,t,s){var n,o;e===(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&yo.setSignalingListenStatus(!0),null===(o=this._core)||void 0===o||o.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var n,o;e===(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&yo.setSignalingListenStatus(!1),null===(o=this._core)||void 0===o||o.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){const t=yo.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();if(!t.has(e))return;const n=t.get(e).inviter===s;this._sendTimeoutNotice({inviteID:e,isInviter:n})}_sendSignaling(e,t){return _e(this,void 0,void 0,function*(){var s,n,o;return null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)})}_sendTimeoutNotice(e){return _e(this,void 0,void 0,function*(){var t,s,n;this._core.ssoLog.debug("_sendTimeoutNotice",`${_o}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:o,inviteID:i}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=So.createTimeoutSignaling(e),u=yield this._sendSignaling(r,c);if(0===(null==u?void 0:u.code)){const{data:e,groupID:c,inviteeList:u,inviter:l}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,{name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:i,inviteeList:u,inviter:l,isSelfTimeout:!0,message:r}}),o?yo.removeSignaling(i):yo.updateSignaling(a)}})}_validateInviteId(e,t){if(!yo.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:mo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=uo,{userID:s}=e,n=this._core.common.getCurrentUserID();if(s===n)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${n}, inviteeId:${s}`})}_validateBeforeAccept(e){const t=lo;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:n}=yo.getSignaling(e);if(!n.includes(s)){const n=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:n})}}_validateBeforeCancel(e){const t=ho;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviter:n}=yo.getSignaling(e);if(n!==s){const e=`unmatched inviter:${n} and my userID:${s}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=po;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:n}=yo.getSignaling(e);if(!n.includes(s)){const n=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:n})}}_validateBeforeModifyInvitation(e){const t=go;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},To=new class{constructor(){this._actionProcessor=new Map([[to,this._onNewInvitationReceived.bind(this)],[oo,this._onInviteeRejected.bind(this)],[no,this._onInviteeAccepted.bind(this)],[so,this._onInvitationCancelled.bind(this)],[io,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach(e=>{const t=Io(e);if(t){const s=this._actionProcessor.get(t.actionType);null==s||s(t,e)}})}_handleMessageReceived(e){if(!yo.getSignalingListenStatus())return;const t=vo(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!yo.getSignalingListenStatus())return;const t=vo(e.data);t.length>0&&t.forEach(e=>{const t=Io(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(e,t){var s,n;const o=`${_o}._onNewInvitationReceived`,{inviteID:i,inviteeList:r,groupID:a}=e,c=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${o} signalingData:${JSON.stringify(e)}}`),a&&!r.includes(c))return;let{timeout:u}=e;const l=Date.now()/1e3-t.time;u>0&&l>0&&u>l&&(u-=l);const d=yo.getSignaling(i);d!==e&&(d||yo.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),u>0&&(null===(s=this._core)||void 0===s||s.helper.taskScheduler.addOnceTask({id:`${fo}-${i}`,intervalMs:1e3*u,callback:Mo.handleInvitationExpiryTimer.bind(Mo,i)})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const s=`${_o}._onInviteeRejected`,{inviteID:n,inviter:o,groupID:i,inviteeList:r}=e,a=yo.hasSignaling(n);this._core.ssoLog.debug("_onInviteeRejected",`${s} inviteID:${n} hasInviteID:${a} inviter:${o} groupID:${i}`),a&&(yo.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const s=`${_o}._onInviteeAccepted`,{inviteID:n,inviter:o,groupID:i,inviteeList:r}=e,a=yo.hasSignaling(n);this._core.ssoLog.debug("_onInviteeAccepted",`${s} inviteID:${n} hasInviteID:${a} inviter:${o} groupID:${i}`),a&&(yo.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const s=`${_o}._onInvitationCancelled`,{inviteID:n,inviter:o,groupID:i}=e,r=yo.hasSignaling(n);this._core.ssoLog.debug("_onInvitationCancelled",`${s} inviteID:${n} hasInviteID:${r} inviter:${o} groupID:${i}`),r&&(yo.removeSignaling(n),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const s=`${_o}._onInvitationTimeout`,{inviteID:n,inviteeList:o}=e,i=yo.hasSignaling(n);this._core.ssoLog.debug("_onInvitationTimeout",`${s} inviteID:${n} hasInviteID:${i} data:${e.data}`),i&&(yo.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:o,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s;const n=`${_o}._onInvitationModified`,{inviteID:o,data:i}=e,r=yo.hasSignaling(o);this._core.ssoLog.debug("_onInvitationModified",`${n} inviteID:${o} data:${i}`),r&&(yo.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:o,data:i}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:s,groupID:n,data:o}=e;return{inviteID:t,inviter:s,groupID:n,data:o||""}}_dispose(){var e,t,s;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(s=this._core)||void 0===s||s.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Ro=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:s,constants:{InnerEvent:n,WORKFLOW_STEP:o,WORKFLOW_NAME:i}}=e;t.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,o.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(0===(null==t?void 0:t.size)||!yo.getSignalingListenStatus())return;const s=vo([...t.values()]);if(0!==s.length&&(s.forEach(e=>{this._handleC2CActionType(e)}),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();To.handleActionSignaling(e)}}_handleC2CActionType(e){const t=Io(e);if(!t)return;const{actionType:s}=t;s===to?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:s,inviteeList:n=[],timeout:o=0}=e,i=this._core.common.getCurrentUserID();if(!n.includes(i))return;const r=Date.now()/1e3-t.time;o>0&&r>o&&0!==o||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach(t=>{e=[...e,...t.signalingList]}),e.sort((e,t)=>e.time-t.time)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const Ao={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},Oo={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Do=new class{constructor(){this.name="Signaling"}install(e){Mo.init(e),To.init(e),So.init(e),yo.init(e),Ro.init(e),e.helper.registerValidateConfig({auth:Oo,params:Ao})}};const bo=new class{init(e){this.core=e}};function Lo(e){let t;const{message:s}=bo.core,{conversationID:n,messageID:o}=e;return t=s.messageDataHandler.getLocalMessageList(n).find(e=>e.ID===o),t||(t=s.messageDataHandler.getSparseMessageList(n).find(e=>e.ID===o)),t}function No(e){return e.map(e=>{const{from:t,to:s,cloudCustomData:n,avatar:o,nick:i,ID:r,clientSequence:a,clientTime:c,messageRandom:u,messageSequence:l,time:d}=e;return{ClientSeq:a,CloudCustomData:n,From_Account:t,From_AccountHeadurl:o,From_AccountNick:i,Id:r,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:c,MsgRandom:u,Random:u,MsgSeq:l,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function wo(e){var t;const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,GroupId:i,MsgClientTime:r,ClientSeq:a,To_Account:c,MsgTimeStamp:u,TinyId:l,MsgRandom:d,MsgSeq:h}=e;return{from:s,avatar:n,nick:o,clientTime:r,time:u,tinyID:l,random:d,sequence:h,to:c,groupID:i,clientSequence:a,_elements:null===(t=e.MsgBody)||void 0===t?void 0:t.map(e=>{const{MsgType:t}=e;return bo.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var Po,Go;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem",e.MSG_STREAM="TIMStreamElem"}(Po||(Po={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(Go||(Go={}));const Uo="MSG_REACTION",ko="MSG_EXT",Fo=0,xo=1,Vo={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},$o="16k_zh",qo="16k_en",Bo="16k_yue",jo="16k_ja",Ho="16k_zh-PY",Ko={[Vo.ZH_CN]:$o,[Vo.EN_US]:qo,[Vo.YUE_HK]:Bo,[Vo.JA_JP]:jo,[Vo.ZH_PY]:Ho},Wo=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Yo={READ:0,UNREAD:1},zo=1,Jo=2,Qo=3;var Xo;!function(e){e.IN="in",e.OUT="out"}(Xo||(Xo={}));const Zo=16,ei=17;var ti,si;!function(e){e[e.DATA=0]="DATA",e[e.REVOKED=1]="REVOKED"}(ti||(ti={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.TIMEOUT=1]="TIMEOUT"}(si||(si={}));const ni="StreamMsg.PushStreamHttp";var oi=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{MESSAGE_REACTION_UPDATED:o,MESSAGE_REACTION_UPDATED_SYNC:i}}=e;t.registerApi({apiName:"addMessageReaction",context:this}),t.registerApi({apiName:"removeMessageReaction",context:this}),t.registerApi({apiName:"getMessageReactions",context:this}),t.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),s.subscribeInnerEvent(n,o,this._handleReactionUpdated,this),s.subscribeInnerEvent(n,i,this._handleReactionSync,this)}addMessageReaction(e,t){return _e(this,void 0,void 0,function*(){const{OuterConstant:s,ssoLog:n,helper:o}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:i,ID:r,conversationType:a,from:c,to:u,clientSequence:l,random:d,time:h,sequence:p}=e,g=`conversationID:${i} messageID:${r} reactionID:${t}`;try{return this._recordMessageReactedByMe(r,t),a===s.CONV_C2C?yield function(e,t){return _e(this,void 0,void 0,function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:u})})}({from:c,to:u,clientSequence:l,random:d,time:h,reactionID:t},this._core):a===s.CONV_GROUP&&(yield function(e,t){return _e(this,void 0,void 0,function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:r})})}({to:u,reactionID:t,sequence:p},this._core)),{code:0,successLog:{message:g}}}catch(e){this._removeMyReactionRecord(r,t);const{errorCode:s}=e||{};throw new o.ChatError({functionName:"addMessageReaction",code:s,moreMessage:g})}})}removeMessageReaction(e,t){return _e(this,void 0,void 0,function*(){const{OuterConstant:s,helper:n}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:o,ID:i,conversationType:r,from:a,to:c,clientSequence:u,random:l,time:d,sequence:h}=e,p=`conversationID:${o} messageID:${i} reactionID:${t}`;try{return this._removeMyReactionRecord(i,t),r===s.CONV_C2C?yield function(e,t){return _e(this,void 0,void 0,function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:u})})}({from:a,to:c,clientSequence:u,random:l,time:d,reactionID:t},this._core):r===s.CONV_GROUP&&(yield function(e,t){return _e(this,void 0,void 0,function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:r},t)})}({to:c,reactionID:t,sequence:h},this._core)),{code:0,successLog:{message:p}}}catch(e){const{errorCode:t}=e||{};throw new n.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:p})}})}getAllUserListOfMessageReaction(e){return _e(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:t,reactionID:s,nextSeq:n=0}=e,o=e.count>100?100:e.count,{conversationID:i}=t,{ssoLog:r,helper:a,constants:c}=this._core;try{let e=null;if(e=i.startsWith(c.OuterConstant.CONV_C2C)?yield function(e){return _e(this,void 0,void 0,function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{from:i,to:r,clientSequence:a,random:c,time:u}=t,l={Reaction:n,NextSeq:s,Count:o,From_Account:i,To_Account:r,MsgKey:`${a}_${c}_${u}`};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:l})})}({message:t,reactionID:s,nextSeq:n,count:o}):yield function(e){return _e(this,void 0,void 0,function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{sequence:i,to:r}=t,a={Reaction:n,NextSeq:s,GroupId:r,Count:o,MsgSeq:i};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:a})})}({message:t,reactionID:s,nextSeq:n,count:o}),e){const{Reaction_Account:t,NextSeq:s}=e;return{code:0,data:{nextSeq:s,isCompleted:0===n,userList:yield this._getUserProfileList(t)}}}}catch(e){const{errorCode:t}=e||{};throw new a.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(e){return _e(this,void 0,void 0,function*(){const{constants:t}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:s,maxUserCountPerReaction:n=10}=e,o=s[0];let i=null;const r=new Map,{from:a,to:c,conversationType:u}=o,l=this._generateMessageKeyList(s,r);u===t.OuterConstant.CONV_C2C?i=yield function(e){return _e(this,void 0,void 0,function*(){const{from:t,to:s,messageKeyList:n,maxUserCountPerReaction:o}=e,i={From_Account:t,To_Account:s,MsgKeyList:n,Count:o};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})})}({from:a,to:c,messageKeyList:l,maxUserCountPerReaction:n}):u===t.OuterConstant.CONV_GROUP&&(i=yield function(e){return _e(this,void 0,void 0,function*(){const{groupId:t,messageSequenceList:s,maxUserCountPerReaction:n}=e,o={GroupId:t,MsgSeqList:s,Count:n};return bo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:o})})}({groupId:c,messageSequenceList:l,maxUserCountPerReaction:n}));const{Results:d=[]}=i||{},h=this._extractUserIDsFromReactionResults(d),p=yield this._getUserProfileMap(h);return{code:0,data:{resultList:d.map(e=>{const{ReactionList:t,MsgSeq:s,MsgKey:n}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:n,messageIDMap:r}),reactionList:t.map(e=>{const{Reaction:t,Count:s,Reaction_Account:n,ReactedByMe:o}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:n,userProfileMap:p}),reactedByMyself:1===o}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){const t=[];return null==e||e.forEach(e=>{const{ReactionList:s=[]}=e;s.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(e){return _e(this,void 0,void 0,function*(){var t;try{const s=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return s?s.data:[]}catch(e){return[]}})}_getUserProfileMap(e){return _e(this,void 0,void 0,function*(){const t=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{const{nick:s,avatar:n,userID:o}=e;t.set(o,{nick:s,avatar:n,userID:o})}),t})}_recordMessageReactedByMe(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)?this._reactionsMap.get(s).reactedByMe=!0:this._reactionsMap.set(s,{reactedByMe:!0})}_removeMyReactionRecord(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)&&(this._reactionsMap.get(s).reactedByMe=!1)}_recordMessageReactionInfo(e){const{messageID:t,reactionID:s,reactionInfo:n}=e,o=`${t}-${s}`,i=this._reactionsMap.get(o)||{};this._reactionsMap.set(o,Object.assign(Object.assign({},i),n))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(Uo))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){const{MsgReactionNotifyList:t}=e,{notificationCenter:s,constants:n}=this._core;t.forEach(e=>_e(this,void 0,void 0,function*(){const{C2CMsgInfo:t,GroupMsgInfo:o,MsgReactionSummary:i}=e,{TinyId:r,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},t),o),u=`${r}-${a}-${c}`,l=this._extractUserIDsFromReactionResults([{ReactionList:i}]),d=yield this._getUserProfileMap(l),h=i.map(e=>{var t;const{Reaction:s,Reaction_Account:n}=e,o=this._generatePartialUserInfo({userIDList:n,userProfileMap:d}),i=n?e.Count:0,r=(null===(t=this._reactionsMap.get(`${u}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:u,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:i,partialUserList:o}}),{reactionID:s,totalUserCount:i,partialUserList:o,reactedByMyself:r}});s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:u,reactionList:h}})}))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:n}=this._core,{C2CMsgInfo:o={},GroupMsgInfo:i={},Reaction:r,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:u=0,MsgRandom:l=0}=Object.assign(Object.assign({},o),i),d=`${c}-${u}-${l}`,h=`${d}-${r}`;if(1===a?this._recordMessageReactedByMe(d,r):this._removeMyReactionRecord(d,r),null===(t=this._reactionsMap.get(h))||void 0===t?void 0:t.reactionID){const e=this._reactionsMap.get(h);e.reactedByMyself=1===a,s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:d,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){const s=[];return null==e||e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){const{messageSequence:t,messageKey:s,messageIDMap:n}=e;return s?n.get(s):n.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,n=e[0],{conversationType:o}=n;let i=[];return o===s.OuterConstant.CONV_C2C?i=e.map(e=>{const{clientSequence:s,random:n,time:o,ID:i}=e,r=`${s}_${n}_${o}`;return t.set(r,i),r}):o===s.OuterConstant.CONV_GROUP&&(i=e.map(e=>{const{ID:s,sequence:n}=e;return t.set(n,s),n})),i}},ii=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:o},notificationCenter:i}=e;t.registerApi({apiName:"sendMessageReadReceipt",context:this}),t.registerApi({apiName:"getMessageReadReceiptList",context:this}),t.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(s,o,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return _e(this,void 0,void 0,function*(){const{common:t,constants:s}=this._core,n=this._filterValidMessageSendByOther(e);if(0===n.length)throw new t.ChatError({code:s.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:e}=n[0];return e===s.OuterConstant.CONV_C2C?yield function(e){return _e(this,void 0,void 0,function*(){const{common:t,constants:s}=bo.core,n=e[0].conversationID.replace(s.OuterConstant.CONV_C2C,""),o=e.map(e=>{const{from:t,to:s,sequence:n,random:o,time:i,clientTime:r}=e;return{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:o,MsgTime:i,MsgClientTime:r}}),i={Peer_Account:n,C2CMsgInfo:o};return t.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:i})})}(n):yield function(e){return _e(this,void 0,void 0,function*(){const{common:t,constants:s}=bo.core,n={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map(e=>({MsgSeq:e.sequence}))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:n})})}(n),{code:0,data:{}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}})}getMessageReadReceiptList(e){return _e(this,void 0,void 0,function*(){const{common:t,constants:s}=this._core;try{const{conversationType:t}=e[0];if(t===s.OuterConstant.CONV_GROUP){const t=this._filterValidMessageSendByMe(e);if((null==t?void 0:t.length)>0){const s=yield function(e){return _e(this,void 0,void 0,function*(){const{common:t,constants:s}=bo.core,n={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map(e=>({MsgSeq:e.sequence}))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:n})})}(t),{GroupMsgReceiptList:n}=s||{};this._updateGroupMessagesReadReceiptInfo({messageList:e,readReceiptList:n})}}return{code:0,data:{messageList:e}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}})}getGroupMessageReadMemberList(e){return _e(this,void 0,void 0,function*(){const{constants:t,common:s}=this._core,{message:n,filter:o=Yo.READ,cursor:i=""}=e,{conversationID:r,sequence:a,ID:c}=n,u=r.replace(t.OuterConstant.CONV_GROUP,""),l=e.count>=100?100:e.count;try{const e=yield function(e){return _e(this,void 0,void 0,function*(){const{sequence:t,groupID:s,filter:n,cursor:o,count:i}=e,r={MsgSeq:t,GroupId:s,Filter:n,Cursor:o,Num:i};return bo.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:r})})}({groupID:u,sequence:a,filter:o,cursor:i,count:l});if(e){const{Cursor:t,IsFinish:s,UnreadList:n,ReadList:i}=e,r={cursor:t,isCompleted:1===s,messageID:c,unreadUserIDList:[],readUserIDList:[]};return o===Yo.READ?r.readUserIDList=i.map(e=>e.Read_Account):o===Yo.UNREAD&&(r.unreadUserIDList=n.map(e=>e.Unread_Account)),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:n}=e;throw new s.ChatError({code:t,message:n})}})}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:n}=this._core,{C2cMsgInfo:o,PeerReadTime:i,Peer_Account:r}=e;if(n.isEmpty(o))return;const a=`${s.OuterConstant.CONV_C2C}${r}`;null==o||o.forEach(e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:o}=e,c=`${s}-${n}-${o}`,u=Lo({conversationID:a,messageID:c});u&&!u.readReceiptInfo.isPeerRead&&(u.readReceiptInfo.isPeerRead=!0,u.readReceiptInfo.timestamp=i,t.push({userID:r,messageID:c,isPeerRead:!0,timestamp:i}))}),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,n=new Map;t.forEach(e=>{n.set(e.sequence,e)}),null==s||s.forEach(e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:o}=e,i=n.get(t);i&&(i.readReceiptInfo.readCount=s,i.readReceiptInfo.unreadCount=o)}})}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:n}=e;n.forEach(e=>{const{MsgBody:{GroupMsgReceiptList:n},GroupInfo:{GroupId:o}}=e,i=`${s.OuterConstant.CONV_GROUP}${o}`;null==n||n.forEach(e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:r,ReadNum:a,UnreadNum:c}=e,u=`${s}-${n}-${r}`,l=Lo({conversationID:i,messageID:u}),d={groupID:o,messageID:u,readCount:0,unreadCount:0};l&&("number"==typeof a&&(l.readReceiptInfo.readCount=a,d.readCount=a),"number"==typeof c&&(l.readReceiptInfo.unreadCount=c,d.unreadCount=c),t.push(d))})}),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter(e=>{const{from:s,status:n}=e;return s===this._core.common.getCurrentUserID()&&n===t.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){const{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:n}=this._core;n.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),n.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function ri(e,t,s){return _e(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:n}}=bo.core,{from:o,to:i,clientSequence:r,random:a,time:c}=e;return n({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:o,To_Account:i,MsgKey:`${r}_${a}_${c}`,OperateType:s,ExtensionList:t}})})}function ai(e,t,s){return _e(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:n}}=bo.core,{to:o,sequence:i}=e;return n({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:o,MsgSeq:i,OperateType:s,ExtensionList:t}})})}var ci=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){this._core=e;const{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:n,LOGOUT:o},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=e;s({apiName:"setMessageExtensions",context:this}),s({apiName:"getMessageExtensions",context:this}),s({apiName:"deleteMessageExtensions",context:this}),t.subscribeInnerEvent(n,i,this._handleMessageExtensionsNotify,this),t.subscribeInnerEvent(o,this.reset,this)}setMessageExtensions(e,t){return _e(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:s},ssoLog:n}=this._core,{ID:o,conversationID:i,sequence:r,time:a,conversationType:c}=e;let u=t;t.length>20&&(u=t.slice(0,20),n.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const l=this._generateServerExtensions(e,u),d=`convID:${i} messageID:${o} sequence:${r} time:${a} count:${u.length}`;try{let t;if(c===s.CONV_C2C?t=yield ri(e,l,zo):c===s.CONV_GROUP&&(t=yield ai(e,l,zo)),t){const{resultList:s,successCount:n,failureCount:o}=this._handleModifyMessageExtensions(e,t);return{code:0,data:{extensions:s},successLog:{message:`${d} successCount:${n} failCount:${o}`}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:d})}})}getMessageExtensions(e){return _e(this,void 0,void 0,function*(){const{utils:{isUndefined:t}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:s,ID:n,sequence:o,time:i}=e,r=`convID:${s} messageID:${n} sequence:${o} time:${i}`;try{let s;this._completedFetchExtensions.has(n)&&(s=this._extensionsLatestSequenceMap.get(n));const o=yield this._fetchMessageExtensions(e,s);return t(s)&&o.length>1&&this._completedFetchExtensions.add(n),{code:0,data:{extensions:o},successLog:{message:r}}}catch(e){const{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:r})}})}deleteMessageExtensions(e,t){return _e(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:s},constants:{OuterConstant:n}}=this._core,{conversationType:o,conversationID:i,sequence:r,ID:a,time:c}=e;let u=Qo;const l=[];s(t)||(u=Jo,null==t||t.forEach(e=>{l.push({key:e,value:"",seq:0})}));const d=`convID:${i} messageID:${a} sequence:${r} time:${c} operateType:${u}`,h=this._generateServerExtensions(e,l);try{let t;if(o===n.CONV_C2C?t=yield ri(e,h,u):o===n.CONV_GROUP&&(t=yield ai(e,h,u)),t){const{resultList:s,successCount:n,failureCount:o}=this._handleModifyMessageExtensions(e,t);return{code:0,data:{extensions:s},successLog:{message:`${d}successCount:${n} failCount:${o}`}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:d})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:n}}=this._core;e.unSubscribeInnerEvent(t,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){const{ID:s}=e,{Seq:n}=t,o=t.ExtensionList||[],i=[];let r=0,a=0,c=[];return o.forEach(e=>{const{ErrorCode:t,Extension:s}=e,{Key:n,Value:o,Seq:u}=s;i.push({code:t,key:n,value:o}),0===t?r++:a++,c.push({key:n,value:o,seq:u})}),this._extensionsLatestSequenceMap.set(s,n),c.length>0&&this._updateLocalExtensions(e.ID,c),{resultList:i,successCount:r,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);const s=this._messageExtensionsMap.get(e);null==t||t.forEach(e=>{const{key:t,seq:n,value:o=""}=e;null==s||s.set(t,{value:o,seq:n})})}_fetchMessageExtensions(e,t){return _e(this,void 0,void 0,function*(){const{constants:{OuterConstant:s},utils:{isEmpty:n}}=this._core;try{let o;const{conversationType:i,ID:r}=e;if(i===s.CONV_C2C?o=yield function(e,t){const{common:{buildAndSendPacket:s}}=bo.core,{from:n,to:o,clientSequence:i,random:r,time:a}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,StartSeq:t}})}(e,t):i===s.CONV_GROUP&&(o=yield function(e,t){const{common:{buildAndSendPacket:s}}=bo.core,{to:n,sequence:o}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:n,MsgSeq:o,StartSeq:t}})}(e,t)),o){const{LatestSeq:t,ClearSeq:s,CompleteFlag:i}=o,a=(o.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(r,a),this._clearLocationExtensions(r,s),this._extensionsLatestSequenceMap.set(r,t),1!==i){const t=a[a.length-1].seq+1;return this._fetchMessageExtensions(e,t)}const c=[];if(this._messageExtensionsMap.has(r)){const e=this._messageExtensionsMap.get(r);null==e||e.forEach((e,t)=>{const{value:s}=e;n(s)||c.push({key:t,value:s})})}return c}}catch(e){throw e}})}_clearLocationExtensions(e,t){if(!(t<=0)&&this._messageExtensionsMap.has(e)){const s=this._messageExtensionsMap.get(e);null==s||s.forEach((e,n)=>{e.seq<=t&&s.delete(n)})}}_generateServerExtensions(e,t){const{ID:s}=e;if(this._messageExtensionsMap.has(s)){const e=this._messageExtensionsMap.get(s);return t.map(t=>{var s;const{key:n,value:o}=t;let i=0;return(null==e?void 0:e.has(n))&&(i=null===(s=e.get(n))||void 0===s?void 0:s.seq),{Key:n,Value:o,Seq:i}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){const{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(ko))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){const{SetKVInfo:t,DeleteKVInfo:s,ClearKVInfo:n,MsgOptType:o,TinyId:i,MsgLastSeq:r,ExtensionC2cMsgInfo:a,ExtensionGroupMsgInfo:c}=(null==e?void 0:e.MsgExtensionNotify)||{},u=a||c||{},{MsgClientTime:l,MsgRandom:d}=u,h=`${i}-${l}-${d}`;this._extensionsLatestSequenceMap.set(h,r),o===zo?this._handleMessageExtensionsUpdated({messageID:h,updateMessageExtensionsInfo:t}):o===Jo?this._handleMessageExtensionsDeleted({messageID:h,deleteMessageExtensionsInfo:s}):o===Qo&&this._handleMessageExtensionsCleared({messageID:h,clearMessageExtensionsInfo:n})}_handleMessageExtensionsUpdated(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,updateMessageExtensionsInfo:o=[]}=e,i=[];o.forEach(e=>{const{MsgKeyValue:t=[]}=e,s=t.map(e=>(i.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(n,s)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:n,extensions:i}})}_handleMessageExtensionsDeleted(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,deleteMessageExtensionsInfo:o=[]}=e,i=[];o.forEach(e=>{const{MsgKeyValue:t=[]}=e,s=t.map(e=>(i.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(n,s)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:n,keyList:i}})}_handleMessageExtensionsCleared(e){const{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:n}}=this._core,{messageID:o,clearMessageExtensionsInfo:i=[]}=e,r=[];i.forEach(e=>{const{ClearMsgSeq:t}=e;this._messageExtensionsMap.has(o)&&(this._messageExtensionsMap.get(o)||[]).forEach((e,s)=>{e.seq<=t&&!n(e.value)&&r.push(s)}),this._clearLocationExtensions(o,t)}),t.emitOuterEvent(s,{name:s,data:{messageID:o,keyList:r}})}};const ui={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{constants:{OuterConstant:t}}=bo.core;return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},li={setMessageExtensions:[ui,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[ui],deleteMessageExtensions:[ui]},di=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const t=function(e){var t;return"string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))||"payload.text is invalid."}(e);return!0!==t?t:!((null==e?void 0:e.atUserList)&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{utils:{isString:t,isNumber:s}}=bo.core;return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),li),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),hi=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class pi{constructor(e){this._core=e}deleteMessage(e){return _e(this,void 0,void 0,function*(){const{to:t,messageIdentifiers:s}=e,n={From_Account:this._core.common.getCurrentUserID(),To_Account:t,MsgKeyList:s};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:n})})}revokeMessage(e){return _e(this,void 0,void 0,function*(){const{to:t,from:s,sequence:n,time:o,random:i}=e,r={MsgInfo:{From_Account:s,To_Account:t,MsgSeq:n,MsgRandom:i,MsgTimeStamp:o}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:r})})}}class gi{constructor(e){this._core=e}deleteMessage(e){return _e(this,void 0,void 0,function*(){const{to:t,messageIdentifiers:s}=e,n={GroupId:t,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:s};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:n})})}revokeMessage(e){return _e(this,void 0,void 0,function*(){const{to:t,sequence:s}=e,n={GroupId:t,MsgSeqList:[{MsgSeq:s}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:n})})}}const _i=2116;class mi{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:n,tinyID:o,clientTime:i,revokeReason:r,revoker:a}=e;let c={};const{messageDataHandler:u}=this._core.message;return c=u.revokeMessage({conversationID:t,sequence:s,random:n,revoker:a}),c||(c={conversationID:t,sequence:s},o&&i&&n&&(c.ID=`${o}-${i}-${n}`)),c.revoker=a,c.revokeReason=r,c.revokerInfo={userID:a,nick:"",avatar:""},c}updateRevokerInfo(e){return _e(this,void 0,void 0,function*(){const t=e.map(e=>e.revoker);try{const s=yield this._fetchUserInfos(t);s&&e.forEach(e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(e){return _e(this,void 0,void 0,function*(){var t,s;const n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(s=n.data)||void 0===s?void 0:s.reduce((e,{userID:t,nick:s,avatar:n})=>(e[t]={nick:s||"",avatar:n||""},e),{}):null})}}var fi=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new gi(e),this._c2cMessageAction=new pi(e),this._messageHelper=new mi(e);const{helper:t}=e;t.registerApi({apiName:"deleteMessage",context:this}),t.registerApi({apiName:"revokeMessage",context:this}),t.registerApi({apiName:"resendMessage",context:this}),t.registerApi({apiName:"findMessage",context:this}),t.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(e){return _e(this,void 0,void 0,function*(){let t=[],s=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:_i});if(e.forEach(e=>{const{conversationID:i,conversationType:r,status:a,_onlineOnlyFlag:c,sequence:u,random:l,time:d}=e||{};if("success"===a&&i===n&&r===o){if(!c){const e="C2C"===r?`${u}_${l}_${d}`:String(u);t.push(e)}s.push(e)}}),0===t.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};t.length>30&&(t=t.slice(0,30),s=s.slice(0,30));try{return"C2C"===o?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:t}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:t}),this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(e){return _e(this,void 0,void 0,function*(){var t;const{conversationType:s,isRevoked:n,ID:o,type:i,from:r,to:a}=e;let c=null;const u=`type:${i} from:${r} to:${a} ID:${o}`;if("@TIM#SYSTEM"===s)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(n)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:u});try{if(c="C2C"===s?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),c){const{RecallRetList:s}=c,n=(null===(t=null==s?void 0:s[0])||void 0===t?void 0:t.RetCode)||0;if(0!==n)throw new this._core.helper.ChatError({code:n,moreMessage:u});return e.isRevoked=!0,yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e},successLog:{message:u}}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:u})}})}resendMessage(e,t){return _e(this,void 0,void 0,function*(){var s,n;return e.isResend=!0,e.status="unSend",null===(n=null===(s=this._core)||void 0===s?void 0:s.apiMap)||void 0===n?void 0:n.sendMessage(e,t)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}createQuoteMessage(e,t){const{ID:s,time:n,sequence:o}=t;return e.quoteInfo={msgID:s,messageTime:n,messageSequence:o},e}_handleDeleteMessageSuccess(e){if(0===e.length)return;const{message:{messageDataHandler:t},common:{isTopic:s},notificationCenter:n,InnerEvent:o}=this._core;e.forEach(e=>{e.isDeleted=!0;const s=t.getLocalMessageList(e.conversationID);null==s||s.forEach(t=>{t.ID===e.ID&&(t.isDeleted=!0)})});const{conversationID:i=""}=e[0];s(i)?n.emitInnerEvent(o.TOPIC_MESSAGE_DELETED,i):n.emitInnerEvent(o.MESSAGE_DELETED,i)}_handleRevokeMessageSuccess(e){return _e(this,void 0,void 0,function*(){var t;const s=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{conversationID:n,sequence:o,random:i}=e;this._core.message.messageDataHandler.revokeMessage({conversationID:n,sequence:o,random:i,revoker:s}),yield this._messageHelper.updateRevokerInfo([e])})}};class vi{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:n}=t;return new vi({index:s,data:n})}constructor(e){this.type=Po.MSG_FACE;const{index:t,data:s}=e;this.content={index:t,data:s}}validateBeforeSend(){var e,t;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(t=this.content)||void 0===t?void 0:t.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{index:n,data:o}=s;return{MsgType:this.type,MsgContent:{Index:n,Data:o}}}}class Ii{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Desc:s,Longitude:n,Latitude:o}=t;return new Ii({description:s,longitude:n,latitude:o})}constructor(e){this.type=Po.MSG_LOCATION;const{description:t,longitude:s,latitude:n}=e;this.content={description:t,longitude:s,latitude:n}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{description:n,longitude:o,latitude:i}=s;return{MsgType:this.type,MsgContent:{Desc:n,Longitude:o,Latitude:i}}}}class Ei{static parseServerPushElement(e){const{MsgContent:t={}}=e,{StreamMsgID:s,CompatibleText:n,Markdown:o,BinaryData:i,ErrorCode:r,ErrorMsg:a}=t;return new Ei({streamMessageID:s,compatibleText:n,markdown:o,binaryData:i,errorCode:r,errorMessage:a})}constructor(e){this.type=Po.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:t,compatibleText:s,markdown:n,binaryData:o,errorCode:i=0,errorMessage:r="",isStreamEnded:a=!1}=e;this.content.streamMessageID=t,this.content.compatibleText=s,this.content.markdown=n,this.content.binaryData=o,this.content.errorCode=i,this.content.errorMessage=r,this.content.isStreamEnded=a}updateChunks(e){if(!e||0===e.length)return;const t=e.sort((e,t)=>e.index-t.index),s=this._getMaxRevokedChunkIndex(t);s>=0&&(this._chunks=[],this._latestIndex=s,this._updateContent());const n=this._getValidChunks(t);if(0!==n.length&&(this._mergeAndSortChunks(n),this._chunks.length>0)){const e=this._chunks[this._chunks.length-1];this._latestIndex=e.index,this._updateContent(),this.content.isStreamEnded=e.isLast}}getLatestIndex(){return this._latestIndex}_filterContinuousChunks(e,t){if(0===e.length)return[];const s=[];let n=t;for(const t of e){if(t.index>n)break;t.index===n&&(s.push(t),n++)}return s}_mergeAndSortChunks(e){const t=new Map;this._chunks.forEach(e=>{t.set(e.index,e)}),e.forEach(e=>{t.set(e.index,e)}),this._chunks=Array.from(t.values()).sort((e,t)=>e.index-t.index)}_updateContent(){this.content.markdown=this._chunks.map(e=>e.markdown).join("");const e=this._chunks.map(e=>e.binaryData).filter(e=>(null==e?void 0:e.length)>0);if(0===e.length)this.content.binaryData=new Uint8Array(0);else if(1===e.length)this.content.binaryData=e[0];else{const t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;this.content.binaryData=s}}_getMaxRevokedChunkIndex(e){let t=-1;for(let s=0;s<e.length;s++){const n=e[s];n.eventType===ti.REVOKED&&n.index>t&&(t=n.index)}return t}_getValidChunks(e){const t=e.filter(e=>e.eventType===ti.DATA&&e.index>this._latestIndex);return this._filterContinuousChunks(t,this._latestIndex+1)}}var Ci=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(Po.MSG_FACE,vi),e.message.messageFactory.registerElementClass(Po.MSG_LOCATION,Ii),e.message.messageFactory.registerElementClass(Po.MSG_STREAM,Ei),e.helper.registerApi({apiName:"createFaceMessage",context:this}),e.helper.registerApi({apiName:"createTextAtMessage",context:this}),e.helper.registerApi({apiName:"createForwardMessage",context:this}),e.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(e){if(!e)return null;const{index:t,data:s}=(null==e?void 0:e.payload)||{},n=new vi({index:t,data:s}),o=this._core.common.getCurrentUserID(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:n}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],o=[];t.forEach(t=>{t!==n.MSG_AT_ALL?(e.push({GroupAtAllFlag:Fo,GroupAt_Account:t}),o.push(t)):(e.push({GroupAtAllFlag:xo}),o.push(n.MSG_AT_ALL))}),s._groupAtInfoList=e,s.atUserList=o}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:n,conversationType:o,priority:i,payload:r,needReadReceipt:a,receiverList:c,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(r._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(r.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const d=this._core.common.getCurrentUserID(),h=this._core.message.messageFactory.createMessage({to:n,from:d,conversationType:o,isPlaceMessage:0,priority:i,payload:r,needReadReceipt:a,isSupportExtension:l,cloudCustomData:u,receiverList:c});return h.setRelayFlag(!0),h.setElement(r._elements[0]),h}createLocationMessage(e){if(!e)return null;const{description:t,longitude:s,latitude:n}=(null==e?void 0:e.payload)||{},o=new Ii({description:t,longitude:s,latitude:n}),i=this._core.common.getCurrentUserID(),r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return r.setElement(o),r}};let yi=class{init(e){this._messageHelper=new mi(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:n},helper:{registerWorkflowStep:o},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:r}}=e;t.subscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this),o(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:t}=e;null==t||t.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(e){return _e(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:t}}=e;yield this._parseAndEmitC2CRevokedMessages(t)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(e){return _e(this,void 0,void 0,function*(){const t=[],{notificationCenter:s,OuterEvent:n,common:{getCurrentUserID:o}}=this._core;e.forEach(e=>{var s;const{MsgRand:n,MsgSeq:i,To_Account:r,From_Account:a,RevokerInfo:{Revoker_Account:c,Revoke_Reason:u}}=e,l=o()===a?`C2C${r}`:`C2C${a}`,d=(null===(s=null==e?void 0:e.RevokerInfo)||void 0===s?void 0:s.Reason)||u,h=this._messageHelper.generateRevokeMessage({conversationID:l,sequence:i,random:n,revoker:c,revokeReason:d});t.push(h)}),t.length>0&&(yield this._messageHelper.updateRevokerInfo(t),s.emitOuterEvent(n.MESSAGE_REVOKED,{name:n.MESSAGE_REVOKED,data:t}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(e){return _e(this,void 0,void 0,function*(){const{revokedMessageList:t}=e.result;yield this._parseAndEmitC2CRevokedMessages(t)})}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},Si=class{init(e){this._messageHelper=new mi(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:n}}=e;t.subscribeInnerEvent(s,n,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){const{GroupTips:t}=e;null==t||t.forEach(e=>{var t;Array.isArray(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(e){return _e(this,void 0,void 0,function*(){try{const{RevokerInfo:t,MsgBody:{GroupWithdrawInfoArray:s},GroupInfo:n}=e,o=[],i=[],{notificationCenter:r,OuterEvent:a,utils:{isEmpty:c},common:{isCommunity:u}}=this._core;let l=!1;n&&(l=u({groupID:n.GroupId})||!c(n.TopicId)),s.forEach(e=>{const{Random:s,MsgSeq:r,GroupId:a,MsgClientTime:c,TinyId:u,TopicId:d,RevokerInfo:{Revoker_Account:h=(null==t?void 0:t.Revoker_Account)||"",Reason:p=(null==t?void 0:t.Reason)||""}}=e,g=d?`GROUP${d}`:`GROUP${a}`,_=this._messageHelper.generateRevokeMessage({conversationID:g,sequence:r,random:s,tinyID:u,clientTime:c,revoker:h,revokeReason:p});l?(_.revokerInfo.nick=n.From_AccountNick,_.revokerInfo.avatar=n.From_AccountHeadurl,o.push(_)):i.push(_)}),i.length>0&&(yield this._messageHelper.updateRevokerInfo(i),o.push(...i)),0!==o.length&&r.emitOuterEvent(a.MESSAGE_REVOKED,{name:a.MESSAGE_REVOKED,data:o})}catch(e){console.debug(e)}})}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var Mi=new class{constructor(){this._c2cMessageReceiver=new yi,this._groupMessageReceiver=new Si}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},Ti=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"translateText",context:this})}translateText(e){return _e(this,void 0,void 0,function*(){try{const{sourceLanguage:t,sourceTextList:s,targetLanguage:n}=e,o=yield function(e,t){return _e(this,void 0,void 0,function*(){var s,n;const{sourceTextList:o,sourceLanguage:i,targetLanguage:r}=e,{store:a,common:c}=t,u={SourceText:o,Source:i,Target:r,FromAccount:null===(s=a.get("login"))||void 0===s?void 0:s.tinyID,SDKAppID:null===(n=a.get("instance"))||void 0===n?void 0:n.sdkAppId},l=yield c.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:u});if(l){const{CmdErrorCode:e,TargetText:t}=l;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:n},this._core);if(o){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=o;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},Ri=new class{init(e){this._core=e,e.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(e){return _e(this,void 0,void 0,function*(){var t;const{message:s,language:n=Vo.ZH_PY}=e;let{url:o}=s.payload||{};const i=this._core.common.getCurrentUserID();s.from===i&&"out"===s.flow&&(o=s.payload.remoteAudioUrl),this._validateVoiceFormat(o);const r=(null===(t=Wo.exec(o))||void 0===t?void 0:t[1])||"mp3",a=Ko[n]||Ho;try{const e=yield function(e){var t;const{store:s,common:n}=bo.core,{url:o,format:i,serverLanguageType:r}=e,a={BytesUrl:o,BytesEngServiceType:r,BytesVoiceFormat:i,Uint32Sdkappid:null===(t=s.get("instance"))||void 0===t?void 0:t.sdkAppId,Uint64SourceType:0};return n.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:a})}({url:o,format:r,serverLanguageType:a});if(e){const{CmdErrorCode:t,BytesResult:s}=e;if(0===t.ErrorCode)return{code:0,data:{result:s}};throw{code:t.ErrorCode,message:t.ErrorInfo}}}catch(e){const{code:t,message:s}=e||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!Wo.test(e))throw new this._core.common.ChatError({code:2119})}};class Ai{constructor(e){const{constants:t,common:s,utils:n}=bo.core,{CONV_C2C:o,CONV_GROUP:i}=t.OuterConstant,{ID:r,tinyID:a,from:c,to:u,clientTime:l=s.timeManager.getServerTimeSeconds()||0,random:d,sequence:h,cloudCustomData:p="",nick:g="",avatar:_="",clientSequence:m,conversationType:f,groupID:v,_elements:I,time:E}=e;this.ID=r||`${a}-${l}-${d}`,this.messageRandom=d,this.from=c,this.messageSender=c,this.time=E,this.messageSequence=h,this.clientSequence=m||h,this.clientTime=l,this.cloudCustomData=p,this.messageReceiver=u,this.avatar=_,this.nick=g;const C=n.deepCopyWithMethods(I);C.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=C,r?f.startsWith(o)?this.receiverUserID=u:f.startsWith(i)&&(this.receiverGroupID=u):v?(this.receiverGroupID=v,this.messageReceiver=v):u&&(this.receiverUserID=u,this.messageReceiver=u)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Oi{static parseServerPushElement(e){const{MsgContent:t}=e,{MsgList:s=[],CompatibleText:n,AbstractList:o,Title:i,PbMsgKey:r,JsonMsgKey:a}=t||{},c=s.map(e=>wo(e));return new Oi({messageList:c,title:i,abstractList:o,compatibleText:n,pbDownloadKey:r,downloadKey:a})}constructor(e){this.type=bo.core.constants.OuterConstant.MSG_MERGER;const{messageList:t,title:s,abstractList:n,compatibleText:o,pbDownloadKey:i="",downloadKey:r="",version:a=0,layersOverLimit:c=!1}=e,u=[];t.forEach(e=>{if(e){const t=new Ai(e);u.push(t)}}),this.content={messageList:u,title:s,abstractList:n,compatibleText:o,version:a,downloadKey:r,pbDownloadKey:i,layersOverLimit:c}}validateBeforeSend(){const{isEmpty:e}=bo.core.helper;return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{abstractList:n,compatibleText:o,downloadKey:i,layersOverLimit:r,pbDownloadKey:a,title:c,version:u,messageList:l}=s;return{MsgType:this.type,MsgContent:{AbstractList:n,CompatibleText:o,JsonMsgKey:i,LayersOverLimit:r,PbMsgKey:a,Title:c,Version:u,MsgList:No(l)}}}}var Di=new class{init(e){this._core=e;const{message:t,helper:s,constants:{OuterConstant:n}}=e;t.messageFactory.registerElementClass(n.MSG_MERGER,Oi),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===n.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){const{common:t}=this._core;if(!e)return null;const s=new Oi(e.payload),n=t.getCurrentUserID(),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return o.setRelayFlag(!0),o.setElement(s),o}sendMessage(e,t){return _e(this,void 0,void 0,function*(){var s,n,o;try{const i=function(e){let t="utf-8";bo.core.helper.IN_BROWSER&&document&&(t=document.charset.toLowerCase());let s,n=0,o=0;if(o=e.length,"utf-8"===t||"utf8"===t)for(let t=0;t<o;t++)s=e.codePointAt(t),s<=127?n+=1:s<=2047?n+=2:s<=65535?n+=3:(n+=4,t++);else if("utf-16"===t||"utf16"===t)for(let t=0;t<o;t++)s=e.codePointAt(t),s<=65535?n+=2:(n+=4,t++);else n=e.replace(/[^\x00-\xff]/g,"aa").length;return n}(JSON.stringify(e));let r=e,a=null;if(i>11264){r=this._core.utils.deepCopyWithMethods(e);try{const{JsonMsgKey:e,PbMsgKey:t}=yield function(e){return _e(this,void 0,void 0,function*(){const{payload:{messageList:t}}=e,s={MsgList:No(t)};return bo.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:s})})}(r),{payload:s}=r;a=new Oi(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(a)}catch(e){console.error(e)}}const{data:{message:c}}=yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(r,t);return a&&c.setElement(e._elements),{code:0,data:{message:c}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t}=this._core,s=e.payload,{downloadKey:n,pbDownload:o,type:i,messageList:r}=s,a=ge(s,["downloadKey","pbDownload","type","messageList"]);try{const s=yield function(e){return _e(this,void 0,void 0,function*(){return bo.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(n),{MsgList:o}=s||{},i=null==o?void 0:o.map(e=>{const t=wo(e);return new Ai(t)});return"function"==typeof e.isOnlineMessage?e.setElement({type:e.type,content:Object.assign({messageList:i},a)}):(e.payload.messageList=i,e.payload.downloadKey="",e.payload.pbDownloadKey=""),t.info("downloadMergerMessage",` success downloadKey:${n}`),e}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:n})}})}},bi=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(e){return _e(this,void 0,void 0,function*(){const{appStore:t,message:s,common:{getCurrentUserID:n},utils:{isArray:o}}=this._core,{GroupId:i,To_Account:r}=e;e.From_Account=e.From_Account||n();let a=null;if(i){a=this._generateGroupMessage(Object.assign(Object.assign({},e),{ToGroupId:i}));const s=t.userStore.getUserProfile(n());a.level=(null==s?void 0:s.level)||0,o(r)&&r.length>0&&(a._receiverList=r)}else r&&(a=this._generateC2CMessage(e));return s.messageSender.sendMessage(a,e)})}_generateC2CMessage(e){const{message:t,OuterConstant:{CONV_C2C:s}}=this._core,n=s,o=t.messageHelper.parseServerPushMessage(e),i=t.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:n,flow:Xo.OUT})),{elements:r}=o;return i.setElement(r),i}_generateGroupMessage(e){const{message:t,OuterConstant:{CONV_GROUP:s}}=this._core,n=s,o=t.messageHelper.parseServerGroupMessage(e),i=t.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:n,flow:Xo.OUT})),{elements:r}=o;return i.setElement(r),i}},Li=new class{init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{GROUP_MESSAGE_PINNED:o}}=e;s.subscribeInnerEvent(n,o,this._handleGroupMessagePinned,this),t.registerApi({apiName:"pinGroupMessage",context:this}),t.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,common:{isTopic:s},OuterConstant:{GROUP_ID_PREFIX:n},helper:{ChatError:o}}=this._core;let{groupID:i,message:r,isPinned:a}=e;const{sequence:c}=r;try{return yield function(e){return _e(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:t,getCurrentUserID:s}}=bo.core,{groupID:n,sequence:o,isPinned:i}=e,r=s(),a=i?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",c={GroupId:n,MsgSeq:o};return i?c.Pinner_Account=r:c.UnPinner_Account=r,t({servcmd:a,data:c})})}({groupID:i,sequence:c,isPinned:a}),{code:0,data:{}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new o({code:t,message:s})}})}getPinnedGroupMessageList(e){return _e(this,void 0,void 0,function*(){let t=[];try{const s=yield function(e){return _e(this,void 0,void 0,function*(){const{groupID:t}=e,{common:{buildAndSendPacket:s}}=bo.core;return s({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:t}})})}({groupID:e});if(s){const{PinnedMsgList:n=[]}=s;t=yield this._updatePinnedMessageInfo({serverPinnedMessageList:n,groupID:e})}return{code:0,data:{messageList:t}}}catch(e){throw e}})}_handleGroupMessagePinned(e){const{message:{messageHelper:t,messageFactory:s},notificationCenter:n,OuterEvent:o,OuterConstant:i}=this._core;e.GroupTips.forEach(e=>{const{ToGroupId:r,MsgBody:{PinnedMsg:a,OpType:c,MsgOperatorMemberExtraInfo:u,SdkGroupMessageId:l}}=e,{UserId:d,NickName:h="",ImageUrl:p=""}=u;let g=null,_=!1;if(c===Zo){_=!0;const e=t.parseServerGroupMessage(a);g=s.createMessage(Object.assign(Object.assign({},e),{conversationType:i.CONV_GROUP,flow:"in"})),g.setElement(e.elements),g.pinnerInfo={userID:d,nick:h,avatar:p}}else if(c===ei){const{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:n,MsgSeq:o}=l;g={ID:`${s}-${e}-${t}`,sequence:o,random:t,time:n,clientTime:e}}g&&n.emitOuterEvent(o.PINNED_GROUP_MESSAGE_UPDATED,{name:o.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:r,message:g,isPinned:_,operatorInfo:{userID:d,nick:h,avatar:p}}})})}_findMessageBySequence(e,t){const{message:{messageDataHandler:s}}=this._core;return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return _e(this,arguments,void 0,function*({serverPinnedMessageList:e,groupID:t}){const{OuterConstant:{CONV_GROUP:s},utils:{isEmpty:n}}=this._core,o=[],i=[],r=[],a=new Map,c=`${s}${t}`;for(let t=0;t<e.length;t++){const s=e[t],{Pinner_Account:n,MsgSeq:u}=s,l=this._findMessageBySequence(c,u);i.push(n),a.set(u,n),l?o.push(l):r.push(u)}const u=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:r,pinnerIDList:i});if(u){const{pinnerInfoMap:e,messageList:t}=u;return o.push(...t),o.forEach(t=>{const{sequence:s}=t,n=a.get(s),o=e[n]||{userID:n,nick:"",avatar:""};t.pinnerInfo=o}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(e){return _e(this,void 0,void 0,function*(){var t,s;const{message:{messageHistory:n},user:{userProfile:o},utils:{isArray:i}}=this._core,{conversationID:r,messageSequenceList:a,pinnerIDList:c}=e,u=yield Promise.all([this._fetchMessageBySequence({conversationID:r,messageSequenceList:a}),null==o?void 0:o.getUserProfile({userIDList:c})]);if(i(u)){const e={};return((null===(t=u[1])||void 0===t?void 0:t.data)||[]).forEach(t=>{const{userID:s,nick:n="",avatar:o=""}=t;e[s]={userID:s,nick:n,avatar:o}}),{messageList:(null===(s=u[0])||void 0===s?void 0:s.messageList)||[],pinnerInfoMap:e}}})}_fetchMessageBySequence(e){return _e(this,void 0,void 0,function*(){const{utils:{isEmpty:t},message:{messageHistory:s}}=this._core,{conversationID:n,messageSequenceList:o}=e;return t(o)?[]:s.getGroupRoamingMessagesByAnchor({conversationID:n,messageSequenceList:o,getType:3})})}};class Ni{constructor(e){this.eventType=ti.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:t,Index:s,Markdown:n,IsLast:o,BinaryData:i}=e;this.eventType=t,this.index=s,this.markdown=n,this.isLast=o,this.binaryData=i}}var wi=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(e){this._core=e;const{notificationCenter:t,OuterEvent:{MESSAGE_RECEIVED:s},InnerEvent:{HISTORY_MESSAGE_FETCHED:n},common:{workflowManager:o},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:r}}=e;t.subscribeInnerEvent(ni,this._handleStreamMessageChunkPush,this),t.subscribeOuterEvent(s,this._handleMessageReceived,this),t.subscribeInnerEvent(n,this.processHistoryMessage,this),o.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(e){const{utils:{isEmpty:t,safeStringify:s},ssoLog:n}=this._core;try{null==e||e.forEach(e=>{var s;if(this._isValidStreamMessage(e)){const n=null===(s=null==e?void 0:e._elements)||void 0===s?void 0:s[0],{streamMessageID:o,markdown:i,binaryData:r}=(null==n?void 0:n.content)||{};t(i)&&t(r)?(this._messageMap.set(o,e),this._fetchStreamMessageChunks(e)):n.content.isStreamEnded=!0}})}catch(e){n.error("processHistoryMessage.error",s(e))}}_handleMessageReceived(e){const t=e.data;null==t||t.forEach(e=>{var t,s;if(this._isValidStreamMessage(e)){const{streamMessageID:n}=(null===(s=null===(t=null==e?void 0:e._elements)||void 0===t?void 0:t[0])||void 0===s?void 0:s.content)||{};n&&(this._messageMap.set(n,e),this._fetchStreamMessageChunks(e))}})}_isValidStreamMessage(e){var t,s;const{utils:{isEmpty:n}}=this._core,{streamMessageID:o}=(null===(s=null===(t=null==e?void 0:e._elements)||void 0===t?void 0:t[0])||void 0===s?void 0:s.content)||{};return e.type===Po.MSG_STREAM&&!n(o)}_fetchStreamMessageChunks(e){return _e(this,void 0,void 0,function*(){var t,s;const{constants:{ERROR_CODE:n},ssoLog:o,utils:{safeStringify:i}}=this._core,r=null===(t=e._elements)||void 0===t?void 0:t[0],a=null===(s=null==r?void 0:r.content)||void 0===s?void 0:s.streamMessageID;try{const{from:t,to:s}=e,n=r.getLatestIndex();if(r.content.isStreamEnded)return;const o=yield function(e){return _e(this,void 0,void 0,function*(){const{from:t,to:s,streamMessageID:n,index:o}=e,i={From_Account:t,To_Account:s,StreamMsgID:n,AckIndex:o};return bo.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:i,timeout:5e3})})}({from:t,to:s,streamMessageID:a,index:n});if(o){const{ErrorCode:e,ErrorInfo:t}=o;if(0!==e)throw r.content.errorCode=e,r.content.errorMessage=t,{errorCode:e,errorMessage:t}}}catch(t){if(t.errorCode===n.NETWORK_TIMEOUT&&this._shouldRetryFetch(a)){const s=this._retryCountMap.get(a)||0;o.debug("_fetchStreamMessageChunks.timeout",`error: ${i(t)} retried: ${s}`),this._retryCountMap.set(a,s+1),this._fetchStreamMessageChunks(e)}else o.error("_fetchStreamMessageChunks.error",i(t))}})}_shouldRetryFetch(e){const{utils:{isNumber:t}}=this._core;if(!this._retryCountMap.has(e))return this._retryCountMap.set(e,1),!0;const s=this._retryCountMap.get(e);return!!(t(s)&&s<=3)}_onStreamEnded(e,t,s){const{ssoLog:n}=this._core;s.content.isStreamEnded=!0,s.stopReason=t,this._messageMap.delete(e),n.debug("_onStreamEnded",`streamMessage end, StopReason: ${t}`)}_handleStreamMessageChunkPush(e){var t;const{ssoLog:s}=this._core,{StopReason:n,Chunks:o,StreamID:i}=(null==e?void 0:e.body)||{},r=this._messageMap.get(i);if(!r)return void s.warn(`_handleStreamMessageChunkPush, unfounded message: ${i}`);const a=null===(t=r._elements)||void 0===t?void 0:t[0];if(a&&this._validateExpectedChunk(a,o)){if(o.length>0){const e=o.map(e=>new Ni(e));a.updateChunks(e)}this._emitMessageModify(r),function(e,t){_e(this,void 0,void 0,function*(){const{common:{generateProtocolData:s},utils:{safeStringify:n},ssoLog:o,channel:i}=bo.core,r={StreamMsgID:e,AckIndex:t};try{const e=s({servcmd:"StreamMsg.AckHttp",data:r});i.sendPacket(e)}catch(e){o.debug("sendStreamChunkAck",n(e))}})}(i,a.getLatestIndex()),a.content.isStreamEnded&&this._onStreamEnded(i,n,a)}}_emitMessageModify(e){const{notificationCenter:t,OuterEvent:{MESSAGE_MODIFIED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:[e]})}_validateExpectedChunk(e,t){const s=e.getLatestIndex()+1;let n=!1;for(let e=0;e<t.length;e++)if(t[e].Index===s){n=!0;break}if(!n){const{ssoLog:e}=this._core;return e.debug("_handleStreamMessageChunkPush",`Ignore push, expected index: ${s}, received: [${t.map(e=>e.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:e,utils:{safeStringify:t}}=this._core;try{const t=Array.from(this._messageMap.entries());for(let s=Math.max(0,t.length-300);s<t.length;s++){const n=t[s][0],o=t[s][1];!1===o.payload.isStreamEnded&&(e.debug("_recoverStreamMessage",`recover unfinished stream: ${n}`),this._fetchStreamMessageChunks(o))}}catch(s){e.error("_recoverStreamMessage.error",t(s))}}reset(){this._messageMap.clear(),this._retryCountMap.clear()}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;this.reset(),e.unSubscribeInnerEvent(ni,this._handleStreamMessageChunkPush,this),e.unSubscribeInnerEvent(t,this._handleMessageReceived,this)}},Pi=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,bo.init(e),fi.init(e),Ci.init(e),Mi.init(e),oi.init(e),Ti.init(e),Ri.init(e),ii.init(e),Di.init(e),ci.init(e),bi.init(e),Li.init(e),wi.init(e),e.helper.registerValidateConfig({auth:hi,params:di}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),Mi.dispose(),ii.dispose(),ci.dispose(),wi.dispose()}_reset(){wi.reset()}},Gi=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,t){return _e(this,void 0,void 0,function*(){var s;const{isEmpty:n}=null===(s=this._core)||void 0===s?void 0:s.utils,{downloadUrl:o="",method:i="PUT",url:r,qs:a,headers:c={},resources:u,dataType:l="text",uploadByIP:d,uploadIP:h}=e;let p=r;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(i.toUpperCase(),p,!0),g.responseType=l;const _=Object.assign({},c);if(d&&h&&(_.host=h),!n(_))for(const e in _)_.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,_[e]);return g.onload=()=>{const s=this._getResponseBody(g,o,d&&h),n=this._buildResponse(g,s);if(200===g.status)t(null,n);else{if(h&&!p.includes(h))return e.url=this._domainName2IP(p,h),e.uploadByIP=!0,this.request(e,t);t({code:g.status,message:JSON.stringify(g.responseText)},n)}},g.onerror=()=>{const e=this._getResponseBody(g,o,d&&h),s=this._buildResponse(g,e),n={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};t(n,s)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:s,loaded:n}=t,o=Math.min(Math.floor(100*n/s),100);e.onProgress({total:s,loaded:n,percent:o/100})}),g.send(u),g})}_buildResponse(e,t){const s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{if(e){const[t,n]=e.split(":").map(e=>e.trim());s[t.toLowerCase()]=n}}),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(e,t="&",s="="){var n;const{isEmpty:o,isPlainObject:i}=null===(n=this._core)||void 0===n?void 0:n.utils;return o(e)?"":i(e)?Object.keys(e).map(n=>{const o=encodeURIComponent(n)+s;return Array.isArray(e[n])?e[n].map(e=>o+encodeURIComponent(e)).join(t):o+encodeURIComponent(e[n])}).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const Ui=["unknown","image","video","audio","log"];var ki=new class{init(e){this._core=e}request(e,t){var s;const{MINI_APP_NAMESPACE:n,IN_ALIPAY_MINI_APP:o,isUniIOSApp:i}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:r="",headers:a={},url:c,downloadUrl:u=""}=e;let l=c,d=null;const h=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!h)return void console.warn("message Invalid download URL format");const p=decodeURIComponent(h[3]),g=p.includes("?")?p.split("?")[0]:p||"",_={key:e.fileKey||g,success_action_status:200,"Content-Type":""},m={};if(i()){const[e,t]=c.split("?sign=");t&&(l=`${e}?sign=${encodeURIComponent(t)}`,m.sign=decodeURIComponent(t),m.signature=decodeURIComponent(t))}let f={url:l,header:a,name:"file",filePath:r,formData:Object.assign(Object.assign({},_),m),timeout:e.timeout||3e5};if(o){const{name:t}=f,s=ge(f,["name"]);f=Object.assign(Object.assign({},s),{fileName:"file",fileType:e.fileType?Ui[e.fileType]:"image"})}return d=n.uploadFile(Object.assign(Object.assign({},f),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})}})),d.onProgressUpdate&&d.onProgressUpdate(t=>{e.onProgress&&e.onProgress({total:t.totalBytesExpectedToSend||0,loaded:t.totalBytesSent||0,percent:t.progress?Math.floor(t.progress)/100:0})}),d}_handleResponse(e){const{downloadUrl:t,response:s,callback:n}=e,o={};if(s.header)for(const e in s.header)s.header.hasOwnProperty(e)&&(o[e.toLowerCase()]=s.header[e]);const i=+s.statusCode;200===i?n(null,{statusCode:i,headers:o,data:Object.assign(Object.assign({},s.data),{location:t})}):n({code:i,message:JSON.stringify(s.data)},{statusCode:i,headers:o,data:void 0})}};function Fi(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function xi(e){const t=e||99999999;return Math.round(Math.random()*t)}function Vi(e,t=!0,s=!0){const n=Date.now();return t?s?n-e+" ms":`${Math.round((n-e)/1e3)} s`:s?n-e:Math.round((n-e)/1e3)}function $i(e){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${e}`}function qi(e,t){return Math.round(Number(e)*10**t)/10**t}function Bi(e){return e<=1048576?`${qi(e/1024,1)}KB/s`:`${qi(e/1048576,1)}MB/s`}const ji="TIMImageElem",Hi="TIMSoundElem",Ki="TIMFileElem",Wi="TIMVideoFileElem",Yi="RichMediaMessagePlugin",zi=["rich.my-imcloud.com","imrich.qcloud.com"],Ji=1,Qi=2,Xi=3,Zi=255;var er;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(er||(er={}));const tr={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},sr=Symbol("isCustomUpload");var nr,or=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[s,n]=e.split("?");if(!n)return s;const o=n.split("&").reduce((e,s)=>{const[n,o]=s.split("=");return n&&n!==t&&(e[n]=o||""),e},{}),i=Object.keys(o).map(e=>`${e}${o[e]?`=${o[e]}`:""}`).join("&");return i?`${s}?${i}`:s}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(tr).some(t=>t.test(e))}extractFileFromInput(e){const{utils:{isArray:t}}=this._core;return Fi(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile?e.tempFile:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return _e(this,void 0,void 0,function*(){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:n?this._probeImageDimensionsWeb(e):s?this._probeImageDimensionsMiniApp(e):void 0})}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:s}=t;return"0"!==s}getFileDNList(){var e;let t=zi;const s=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:n}=s;if(void 0===n)return t;try{JSON.parse(n).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=zi}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var s;let n=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(s=this._core)||void 0===s?void 0:s.utils.randomString()}`;if(t)return`${n}.${t}`;const o=e.name||e.value||e.url||e.tempFilePath,i=o&&o.slice(o.lastIndexOf(".")+1);return i&&(n=`${n}.${i}`),n}processResourceUrl(e){if(!e)return"";let t=e;const s=this.getFileDownloadProxy(),n=this.getAuthKey(),o=this.getFileDNList();s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s)));const i=n&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){const n=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),o=n&&n[2]||"";if(o.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(o.endsWith(t[e])){s=!0;break}}return s}(t,o);return i&&(t=t.indexOf("?")>-1?`${t}&authKey=${n}`:`${t}?authKey=${n}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}}isEmpty(e){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return s(e)}generateURL(e,t){const{needAddAuthToUrl:s=!0}=t||{};return s?this.addAuthToUrl(e):e}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise(t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:s,IE_VERSION:n,IN_WX_MINI_GAME:o}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||s&&9===n||o}_probeImageDimensionsWeb(e){return new Promise(t=>{const s=new Image,n=()=>{s.onload=null,s.onerror=null,s.src=""};s.onload=()=>{t({width:s.width,height:s.height}),n()},s.onerror=()=>{t({width:0,height:0}),n()},s.src=e})}},ir={exports:{}},rr=(nr||(nr=1,function(e){e.exports=function(e){var t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function s(e,t){var s=e[0],n=e[1],o=e[2],i=e[3];n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[0]-680876936|0)<<7|s>>>25)+n|0)&n|~s&o)+t[1]-389564586|0)<<12|i>>>20)+s|0)&s|~i&n)+t[2]+606105819|0)<<17|o>>>15)+i|0)&i|~o&s)+t[3]-1044525330|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[4]-176418897|0)<<7|s>>>25)+n|0)&n|~s&o)+t[5]+1200080426|0)<<12|i>>>20)+s|0)&s|~i&n)+t[6]-1473231341|0)<<17|o>>>15)+i|0)&i|~o&s)+t[7]-45705983|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[8]+1770035416|0)<<7|s>>>25)+n|0)&n|~s&o)+t[9]-1958414417|0)<<12|i>>>20)+s|0)&s|~i&n)+t[10]-42063|0)<<17|o>>>15)+i|0)&i|~o&s)+t[11]-1990404162|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[12]+1804603682|0)<<7|s>>>25)+n|0)&n|~s&o)+t[13]-40341101|0)<<12|i>>>20)+s|0)&s|~i&n)+t[14]-1502002290|0)<<17|o>>>15)+i|0)&i|~o&s)+t[15]+1236535329|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[1]-165796510|0)<<5|s>>>27)+n|0)&o|n&~o)+t[6]-1069501632|0)<<9|i>>>23)+s|0)&n|s&~n)+t[11]+643717713|0)<<14|o>>>18)+i|0)&s|i&~s)+t[0]-373897302|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[5]-701558691|0)<<5|s>>>27)+n|0)&o|n&~o)+t[10]+38016083|0)<<9|i>>>23)+s|0)&n|s&~n)+t[15]-660478335|0)<<14|o>>>18)+i|0)&s|i&~s)+t[4]-405537848|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[9]+568446438|0)<<5|s>>>27)+n|0)&o|n&~o)+t[14]-1019803690|0)<<9|i>>>23)+s|0)&n|s&~n)+t[3]-187363961|0)<<14|o>>>18)+i|0)&s|i&~s)+t[8]+1163531501|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[13]-1444681467|0)<<5|s>>>27)+n|0)&o|n&~o)+t[2]-51403784|0)<<9|i>>>23)+s|0)&n|s&~n)+t[7]+1735328473|0)<<14|o>>>18)+i|0)&s|i&~s)+t[12]-1926607734|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[5]-378558|0)<<4|s>>>28)+n|0)^n^o)+t[8]-2022574463|0)<<11|i>>>21)+s|0)^s^n)+t[11]+1839030562|0)<<16|o>>>16)+i|0)^i^s)+t[14]-35309556|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[1]-1530992060|0)<<4|s>>>28)+n|0)^n^o)+t[4]+1272893353|0)<<11|i>>>21)+s|0)^s^n)+t[7]-155497632|0)<<16|o>>>16)+i|0)^i^s)+t[10]-1094730640|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[13]+681279174|0)<<4|s>>>28)+n|0)^n^o)+t[0]-358537222|0)<<11|i>>>21)+s|0)^s^n)+t[3]-722521979|0)<<16|o>>>16)+i|0)^i^s)+t[6]+76029189|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[9]-640364487|0)<<4|s>>>28)+n|0)^n^o)+t[12]-421815835|0)<<11|i>>>21)+s|0)^s^n)+t[15]+530742520|0)<<16|o>>>16)+i|0)^i^s)+t[2]-995338651|0)<<23|n>>>9)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[0]-198630844|0)<<6|s>>>26)+n|0)|~o))+t[7]+1126891415|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[14]-1416354905|0)<<15|o>>>17)+i|0)|~s))+t[5]-57434055|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[12]+1700485571|0)<<6|s>>>26)+n|0)|~o))+t[3]-1894986606|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[10]-1051523|0)<<15|o>>>17)+i|0)|~s))+t[1]-2054922799|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[8]+1873313359|0)<<6|s>>>26)+n|0)|~o))+t[15]-30611744|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[6]-1560198380|0)<<15|o>>>17)+i|0)|~s))+t[13]+1309151649|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[4]-145523070|0)<<6|s>>>26)+n|0)|~o))+t[11]-1120210379|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[2]+718787259|0)<<15|o>>>17)+i|0)|~s))+t[9]-343485551|0)<<21|n>>>11)+o|0,e[0]=s+e[0]|0,e[1]=n+e[1]|0,e[2]=o+e[2]|0,e[3]=i+e[3]|0}function n(e){var t,s=[];for(t=0;t<64;t+=4)s[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return s}function o(e){var t,s=[];for(t=0;t<64;t+=4)s[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return s}function i(e){var t,o,i,r,a,c,u=e.length,l=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=u;t+=64)s(l,n(e.substring(t-64,t)));for(o=(e=e.substring(t-64)).length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<o;t+=1)i[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(i[t>>2]|=128<<(t%4<<3),t>55)for(s(l,i),t=0;t<16;t+=1)i[t]=0;return r=(r=8*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(r[2],16),c=parseInt(r[1],16)||0,i[14]=a,i[15]=c,s(l,i),l}function r(e){var t,n,i,r,a,c,u=e.length,l=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=u;t+=64)s(l,o(e.subarray(t-64,t)));for(n=(e=t-64<u?e.subarray(t-64):new Uint8Array(0)).length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<n;t+=1)i[t>>2]|=e[t]<<(t%4<<3);if(i[t>>2]|=128<<(t%4<<3),t>55)for(s(l,i),t=0;t<16;t+=1)i[t]=0;return r=(r=8*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(r[2],16),c=parseInt(r[1],16)||0,i[14]=a,i[15]=c,s(l,i),l}function a(e){var s,n="";for(s=0;s<4;s+=1)n+=t[e>>8*s+4&15]+t[e>>8*s&15];return n}function c(e){var t;for(t=0;t<e.length;t+=1)e[t]=a(e[t]);return e.join("")}function u(e){return/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e))),e}function l(e,t){var s,n=e.length,o=new ArrayBuffer(n),i=new Uint8Array(o);for(s=0;s<n;s+=1)i[s]=e.charCodeAt(s);return t?i:o}function d(e){return String.fromCharCode.apply(null,new Uint8Array(e))}function h(e,t,s){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e)),n.set(new Uint8Array(t),e.byteLength),n}function p(e){var t,s=[],n=e.length;for(t=0;t<n-1;t+=2)s.push(parseInt(e.substr(t,2),16));return String.fromCharCode.apply(String,s)}function g(){this.reset()}return c(i("hello")),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||function(){function t(e,t){return(e=0|e||0)<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(s,n){var o,i,r,a,c=this.byteLength,u=t(s,c),l=c;return n!==e&&(l=t(n,c)),u>l?new ArrayBuffer(0):(o=l-u,i=new ArrayBuffer(o),r=new Uint8Array(i),a=new Uint8Array(this,u,o),r.set(a),i)}}(),g.prototype.append=function(e){return this.appendBinary(u(e)),this},g.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,o=this._buff.length;for(t=64;t<=o;t+=64)s(this._hash,n(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},g.prototype.end=function(e){var t,s,n=this._buff,o=n.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<o;t+=1)i[t>>2]|=n.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),s=c(this._hash),e&&(s=p(s)),this.reset(),s},g.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},g.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},g.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},g.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},g.prototype._finish=function(e,t){var n,o,i,r=t;if(e[r>>2]|=128<<(r%4<<3),r>55)for(s(this._hash,e),r=0;r<16;r+=1)e[r]=0;n=(n=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=o,e[15]=i,s(this._hash,e)},g.hash=function(e,t){return g.hashBinary(u(e),t)},g.hashBinary=function(e,t){var s=c(i(e));return t?p(s):s},g.ArrayBuffer=function(){this.reset()},g.ArrayBuffer.prototype.append=function(e){var t,n=h(this._buff.buffer,e),i=n.length;for(this._length+=e.byteLength,t=64;t<=i;t+=64)s(this._hash,o(n.subarray(t-64,t)));return this._buff=t-64<i?new Uint8Array(n.buffer.slice(t-64)):new Uint8Array(0),this},g.ArrayBuffer.prototype.end=function(e){var t,s,n=this._buff,o=n.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<o;t+=1)i[t>>2]|=n[t]<<(t%4<<3);return this._finish(i,o),s=c(this._hash),e&&(s=p(s)),this.reset(),s},g.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},g.ArrayBuffer.prototype.getState=function(){var e=g.prototype.getState.call(this);return e.buff=d(e.buff),e},g.ArrayBuffer.prototype.setState=function(e){return e.buff=l(e.buff,!0),g.prototype.setState.call(this,e)},g.ArrayBuffer.prototype.destroy=g.prototype.destroy,g.ArrayBuffer.prototype._finish=g.prototype._finish,g.ArrayBuffer.hash=function(e,t){var s=c(r(new Uint8Array(e)));return t?p(s):s},g}()}(ir)),ir.exports),ar=qt(rr),cr=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?ki:Gi,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return _e(this,void 0,void 0,function*(){const t=`${Yi} uploadToCOS`,{ssoLog:s,utils:{safeStringify:n}}=this._core,{file:o}=e;this.uploadFileType=e.uploadFileType,s.debug("uploadToCOS",`${t} options:${n(e)}`);try{const n=Date.now(),i=yield this._createCosOptions(e),r=i.fileExistsInCOS?{data:{location:i.downloadUrl}}:yield this._uploadFile(i);this._handleUploadError(r,e);const a=this._createUploadResult(o,r),c=Date.now()-n,u=function(e){const t=1024,s=1048576;return e<t?`${e}B`:e<s?`${Math.floor(e/t)}KB`:`${Math.floor(e/s)}MB`}(o.size),l=`size:${u} time:${c}ms speed:${Bi(1e3*o.size/c)}`;return s.debug("uploadToCOS",`${t} ok. name:${o.name} ${l}`),{uploadOptions:i,response:a}}catch(e){throw s.warn("uploadToCOS",`${t} failed, error:${n(e)}`),e}})}_handleUploadError(e,t){var s,n;const{ChatError:o}=null===(s=this._core)||void 0===s?void 0:s.helper;if(403===e.statusCode)throw t.url,(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.uploadIP)&&e.data.uploadIP,new o({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:Vi(Date.now(),!1),uploadSpeed:Bi(1e3*e.size/Vi(Date.now(),!1))}}_createCosOptions(e){return _e(this,void 0,void 0,function*(){const{fileName:t,resources:s,uploadMethod:n}=yield this._prepareUploadParams(e),o=this._isC2CConversation(e.message.conversationID)?1:2;try{const i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:n,duration:this.duration,userID:e.message.from,conversationType:o}),{uploadUrl:r,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,existFlag:h}=i,p=!or.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(r),fileType:this.uploadFileType,fileName:t,resources:s,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,uploadIP:p||"",fileExistsInCOS:1===h,onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s,isEmpty:n}}=this._core;t.debug("_prepareUploadParams",` prepareUploadParams:${s(e)}`);const{file:o}=e,{IN_MINI_APP:i,IN_RN_APP:r}=or.getPlatformFlags(),a=i||r,c=a&&e.message.type!==Ki,{name:u}=o,l=u.slice(u.lastIndexOf(".")),d=`${xi(999999)}${l}`,h=c?o.name:d,p=yield this._generateHashFileName(o);return{fileName:n(p)?$i(h):`${p}${l}`,resources:a?o.url:o,uploadMethod:a?1:0}})}_generateHashFileName(e){return _e(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:t,IN_BROWSER:s,IN_UNI_NATIVE_APP:n,isArray:o},ssoLog:i}=this._core,r=Date.now();let a="";return s&&(a=yield this._generateHashFileNameInWeb(e)),t&&(o(e.tempFiles)&&(e=e.tempFiles[0]),n||(a=yield this._generateFileNameInMiniProgram(e)),n&&(a=yield this._generateFileNameInUNINativeApp(e))),i.info("_generateHashFileName",`hashFileName:${a} costTime:${Date.now()-r}`),a})}_generateHashFileNameInWeb(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;let n="";try{n=yield new Promise((s,n)=>{const o=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;o||(t.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),s(""));const i=10485760,r=Math.ceil(e.size/i);let a=0;const c=new ar.ArrayBuffer,u=new FileReader,l=setTimeout(()=>{u.abort(),t.warn("_generateHashFileNameInWeb","File hash generation timeout"),s("")},2e3);function d(){const t=a*i,s=t+i>=e.size?e.size:t+i;u.readAsArrayBuffer(o.call(e,t,s))}u.onload=e=>{t.debug("_generateHashFileNameInWeb",`read chunk nr ${a+1} of ${r}`),c.append(e.target.result),a++,a<r?d():(t.debug("_generateHashFileNameInWeb","finished loading"),clearTimeout(l),s(c.end()))},u.onerror=e=>{clearTimeout(l),n(e)},d()})}catch(e){t.warn("_generateHashFileNameInWeb",s(e))}return n})}_generateFileNameInMiniProgram(e){return _e(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:t,safeStringify:s,isEmpty:n},ssoLog:o}=this._core;let i="";if(n(e.url))return o.warn("_generateFileNameInMiniProgram","file.url is empty"),i;if("function"!=typeof(null==t?void 0:t.getFileSystemManager))return o.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),i;try{i=yield new Promise((s,n)=>{t.getFileSystemManager().getFileInfo({filePath:e.url,success:e=>{s(e.digest)},fail:e=>{n(e)}})})}catch(e){o.warn("_generateFileNameInMiniProgram",s(e))}return i})}_generateFileNameInUNINativeApp(e){return _e(this,void 0,void 0,function*(){var t;const{utils:{safeStringify:s,isEmpty:n},ssoLog:o}=this._core;let i="";if(n(e.url))return o.warn("_generateFileNameInUNINativeApp","file.url is empty"),i;if("function"!=typeof(null===(t=null===plus||void 0===plus?void 0:plus.io)||void 0===t?void 0:t.getFileInfo))return o.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),i;try{i=yield new Promise((t,s)=>{plus.io.getFileInfo({filePath:e.url,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){o.warn("_generateFileNameInMiniProgram",s(e))}return i})}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core,n=or.isSimpleCos(),o=this._prepareCosRequestData(e),i=n?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,t,s){return _e(this,void 0,void 0,function*(){try{const{helper:n,channel:o}=s,i=n.generateCosSpecifiedData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(i,o,this._core);this.fetchCosTryCount=0;const r=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${n} data:${s(r)}`),r||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;const s=or.isSimpleCos(),n=s?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!n)return{};if(s){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:o,str_download_url:i,str_upload_url:r,str_snapshot_url:a,str_file_key:c}=n;return{uploadIP:e,preSig:t,fileID:s,existFlag:o,downloadUrl:i,uploadUrl:r,requestSnapshotUrl:a,fileKey:c}}const{upload_url:o,download_url:i,snapshot_url:r,thumb_url:a,large_url:c,file_key:u}=n;return{uploadUrl:o,downloadUrl:i,requestSnapshotUrl:r,thumbUrl:a,largeUrl:c,fileKey:u}}_prepareCosRequestData(e){return or.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:or.getPlatform(),uint32_sdkappid:or.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return _e(this,void 0,void 0,function*(){return new Promise((t,s)=>{this.httpRequest.request(e,(n,o)=>{n&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(n)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(s)):(this.uploadFileTryCount=0,n?s(n):t(o))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{const n=null===(t=e.error)||void 0===t?void 0:t.Code,o=null===(s=e.error)||void 0===s?void 0:s.Message;return"RequestTimeTooSkewed"===n||"AccessDenied"===n&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(!o)return!1;const i=Date.now(),r=Date.parse(o);return Math.abs(i+this.systemClockOffset-r)>=3e4}_syncSystemClock(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(o){const e=Date.now(),t=Date.parse(o);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=or.getFileUploadProxy();let s=e;return t&&(s=e.replace(/^https:\/\/[^/]+/,t)),s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const ur=2108,lr=2251,dr=2252,hr=2253,pr=["jpg","jpeg","gif","png","bmp","image","webp"],gr={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},_r=1,mr=2;class fr{constructor(e,t){this.instanceID=xi(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=or.addAuthToUrl(e.imageUrl||e.url||""),this.url=or.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=or.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function vr(e){const{originUrl:t,originWidth:s,originHeight:n,min:o=198}=e,i=parseInt(s)||0,r=parseInt(n)||0,a={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)a.url=t,a.width=i,a.height=r;else{r<=i?(a.width=Math.ceil(i*o/r),a.height=o):(a.width=o,a.height=Math.ceil(r*o/i));const e=t&&t.indexOf("?")>-1?`${t}&`:`${t}?`;a.url=198===o?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===t){const{url:e}=a;return ge(a,["url"])}return a}class Ir{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=ji;const{uuid:t,file:s,imageFormat:n,imageInfoArray:o=[],isCustomUpload:i=!1}=e;this._imageMemoryURL=this.createImageDataAsURL(s),this.content={imageFormat:n,uuid:t,imageInfoArray:[]},this[sr]=i,this.initImageInfoArray(o),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:s,ImageInfoArray:n,UUID:o}=t,i=function(e){return e.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}))}(n);return new Ir({imageFormat:s,imageInfoArray:i,uuid:o})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:s,IN_RN_APP:n,IN_BROWSER:o}=or.getPlatformFlags();return e?((s||n)&&(t=e.url),o&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let s=0;s<3;s++){const n=e[s]||Object.assign({},t),o=new fr(n,this._imageMemoryURL);o.setSizeType(s+1),o.setType(s),this.addImageInfo(o)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach(t=>{if(!t.url||""===t.imageUrl)return;const[s,...n]=t.imageUrl.split("://"),o=n.join("://");e.includes(s)||t.setImageUrl(`https://${o}`)})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=gr[e.toUpperCase()]||gr.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let s;for(let n=0;n<t;n++)s=this.content.imageInfoArray[n],e[n].size&&(s.size=e[n].size),e[n].url&&s.setImageUrl(e[n].url),e[n].width&&(s.width=e[n].width),e[n].height&&(s.height=e[n].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],vr({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){if(this[sr])return delete this[sr],{isValid:!0};const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:n,imageFormat:o,imageInfoArray:i}=s;return{MsgType:this.type,MsgContent:{ImageFormat:o,ImageInfoArray:this.parseImageInfoArray(i),UUID:n}}}parseImageInfoArray(e){return e.map(e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:or.removeAuthToUrl(e.imageUrl)}))}}const Er=new class{init(e){this.core=e}},Cr={[Ji]:"i",[Xi]:"a",[Qi]:"v",[Zi]:"f"};let yr=null,Sr=null;function Mr(e){var t;const{store:s,utils:{isNumber:n,safeStringify:o},ssoLog:i}=Er.core;try{const o=(null===(t=s.get("cloudConfig"))||void 0===t?void 0:t.upload_size_limit)||"";o!==Sr&&(Sr=o,yr=JSON.parse(o)||{});const i=null==yr?void 0:yr[Cr[e]];if(n(i))return 1024*i*1024}catch(e){i.debug("getCloudControlUploadSizeLimit",o(e))}return null}var Tr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createImageMessage",context:this}),n.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(ji,Ir),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,n;try{const o=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,i=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:o})),r=this._processImage(e);e.payload.file=r;const a={imageFormat:gr.UNKNOWN,uuid:or.generateUUID(r),file:r,imageInfoArray:[]},c=new Ir(a);return i.setElement(c),this._messageOptionsMap.set(i.clientSequence,e),i}catch(e){throw e}}createCustomUploadImageMessage(e){var t,s,n,o;const{store:i,utils:{isEmpty:r}}=this._core,a=null===(t=i.get("login"))||void 0===t?void 0:t.userId,c=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:a})),{largeImageUuid:u,largeFileSize:l,largeImageWidth:d,largeImageHeight:h,largeImageUrl:p,originImageUuid:g,originFileSize:_,originImageWidth:m,originImageHeight:f,originImageUrl:v,thumbImageUuid:I,thumbFileSize:E,thumbImageWidth:C,thumbImageHeight:y,thumbImageUrl:S}=(null===(o=null==e?void 0:e.payload)||void 0===o?void 0:o.file)||{};if(r(v)||r(g))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const M=new Ir({imageFormat:gr.UNKNOWN,uuid:g,imageInfoArray:[{instanceID:g,size:_,width:m,height:f,imageUrl:v,url:v},{instanceID:u,size:l,width:d,height:h,imageUrl:p,url:p},{instanceID:I,size:E,width:C,height:y,imageUrl:S,url:S}],isCustomUpload:!0});return c.setElement(M),this._messageOptionsMap.set(c.clientSequence,e),c._skipUpload=!0,c}upload(e){return _e(this,void 0,void 0,function*(){const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(s);const n=yield this._performImageUpload(t,e,s),o=this._generateImageInfo(n);return t.updateImageFormat(null==n?void 0:n.fileType),t.updateImageInfoArray(o),this._updateImageType(t.content.imageInfoArray),e})}_performImageUpload(e,t,s){return _e(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:Ji,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{uploadOptions:i,response:r}=yield cr.uploadToCOS(o);return this._parseResponse(i,r)})}_generateImageInfo(e){const{location:t,fileSize:s,width:n,height:o,smallImageUrl:i,smallImageWidth:r,smallImageHeight:a,largeImageUrl:c,largeImageWidth:u,largeImageHeight:l,imageInfoArray:d}=e,h=or.addAuthToUrl(t),p={size:s,url:h,width:n,height:o};return(null==d?void 0:d.length)>0?this._processImageInfoArray(d,s):i&&c?[Object.assign({},p),{largeImageUrl:c,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:r,smallImageHeight:a}]:[Object.assign({},p),this._generateThumbInfo(h,n,o,720),this._generateThumbInfo(h,n,o,198)]}_generateThumbInfo(e,t,s,n){return vr({originUrl:e,originWidth:t,originHeight:s,min:n})}_processImageInfoArray(e,t){let s,n,o;for(const i of e)1===i.type?(n=i,n.size=t):2===i.type?(o=i,o.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},o),Object.assign({},n)]}_parseResponse(e,t){return _e(this,void 0,void 0,function*(){try{const{thumbUrl:s,largeUrl:n,downloadUrl:o}=e;if(s&&n&&(yield this._getImageInfoByUrl(s,t,"thumb"),yield this._getImageInfoByUrl(n,t,"large")),or.isSimpleCos()&&!or.isPrivateNetWork()&&(yield this._getImageInfoArray(o,t),null==t?void 0:t.uploadIP)){const e=this._extractDomainFromUrl(o);e&&(yield this._getDownloadIP(e,t))}return t}catch(e){throw e}})}_extractDomainFromUrl(e){var t;try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return null===(t=this._core)||void 0===t||t.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${e.message}`),null}}_getImageInfoByUrl(e,t,s){return _e(this,void 0,void 0,function*(){var n;try{const n=or.addAuthToUrl(e),{width:o=0,height:i=0}=yield or.probeImageWidthHeight(n);t.width=o,t.height=i,"thumb"===s?(t.smallImageUrl=e,t.smallImageWidth=o,t.smallImageHeight=i):(t.largeImageUrl=e,t.largeImageWidth=o,t.largeImageHeight=i)}catch(e){null===(n=this._core)||void 0===n||n.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${s} image info:${e.message}`)}})}_validateBeforeUploadImage(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:lr});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:n}=e.payload;return n=s?this._processMiniAppImageFile(n):this._processWebImageFile(n),n}catch(e){throw e}}_processMiniAppImageFile(e){Fi(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,n=or.extractFileFromInput(e);if(!n)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return n}_getDownloadIP(e,t){return _e(this,void 0,void 0,function*(){const s=`${Yi} getDownloadIP domainName: ${e}`;try{const n=yield function(e,t){return _e(this,void 0,void 0,function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_final_ip",i={str_domain:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(e,this._core);if(!n||!n.str_final_ip)return;console.log(`${s} ok. downloadIP:${n}`);const o=t.location.split("/");o[0]=n.str_final_ip,t.location=o.join("/")}catch(e){console.warn(e)}})}_getImageInfoArray(e,t){return _e(this,void 0,void 0,function*(){try{const s=yield function(e,t){return _e(this,void 0,void 0,function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_imageinfo",i={str_image_url:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(e,this._core);return t.imageInfoArray=this._processImageInfoResponse(s),t}catch(e){throw t.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))}_checkImageType(e){const{utils:t,helper:s}=this._core;let n="";if(t.IN_MINI_APP&&(n=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(n=e.name.slice(e.name.lastIndexOf(".")+1)),pr.indexOf(n.toLowerCase())<0)throw new s.ChatError({code:dr})}_checkImageSize(e){const{utils:t,helper:s,store:n}=this._core;let o=0;if(t.IN_MINI_APP,o=e.size,0===o)throw new s.ChatError({code:ur});if(o>=(Mr(Ji)||20971520))throw new s.ChatError({code:hr})}_updateImageType(e){e[1].type=mr,e[2].type=_r}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Rr=2108,Ar=2401,Or=2402,Dr="2.5.0",br="1.18.0";function Lr(e,t){const s=e.split("."),n=t.split("."),o=Math.max(s.length,n.length);for(;s.length<o;)s.push("0");for(;n.length<o;)n.push("0");for(let e=0;e<o;e++){const t=parseInt(s[e]),o=parseInt(n[e]);if(t>o)return 1;if(t<o)return-1}return 0}var Nr;class wr{constructor(e){this.type=Ki,this.uploadProgress=0,this[Nr]=!1;const t=this._getFileInfo(e);this[sr]=e.isCustomUpload||!1,this.content={downloadFlag:2,fileUrl:or.generateURL(e.url||e.fileUrl,{needAddAuthToUrl:!this[sr]})||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:s,Url:n,FileName:o,FileSize:i,UUID:r}=t;return new wr({downloadFlag:s,url:n,fileName:o,fileSize:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){if(this[sr])return{isValid:!0};const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:n,downloadFlag:o,fileUrl:i,fileName:r,fileSize:a}=s;return{MsgType:this.type,MsgContent:{Download_Flag:o,Url:or.removeAuthToUrl(i),FileName:r,FileSize:a,UUID:n}}}_getFileInfo(e){const{utils:{IN_UNI_NATIVE_APP:t}}=Er.core;if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:s}=e;return s?(t&&this._processNativeAppFile(s),{size:s.size,name:s.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${xi(999999)}.${t}`)}e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}Nr=sr;var Pr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createFileMessage",context:this}),n.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Ki,wr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,n;try{this._checkVersion();const o=this._processFile(e.payload.file);e.payload.file=o;const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a={uuid:or.generateUUID(o),file:o},c=new wr(a);return r.setElement(c),this._messageOptionsMap.set(r.clientSequence,e),r}catch(e){throw e}}createCustomUploadFileMessage(e){var t,s,n;try{const{store:o,message:i,utils:{isEmpty:r}}=this._core,a=null===(t=o.get("login"))||void 0===t?void 0:t.userId,{url:c,uuid:u,fileSize:l,fileName:d=""}=(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.file)||{};if(r(c))throw new Error("url is required");const h=null===(n=i.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:a})),p=new wr({url:c,uuid:u,file:{size:l,name:d},isCustomUpload:!0});return h.setElement(p),h}catch(e){throw e}}upload(e){return _e(this,void 0,void 0,function*(){const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const s=e.getElements()[0],n=yield this._performFileUpload(s,e,t),o=or.addAuthToUrl(null==n?void 0:n.location);return s.updateFileUrl(o),e})}_validateBeforeUploadFile(e){const{helper:{ChatError:t}}=this._core;if(!e)throw new t({code:Ar});const s=Mr(Zi)||104857600;if(e.size>s)throw new t({code:Or});if(0===e.size)throw new t({code:Rr})}_performFileUpload(e,t,s){return _e(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:Zi,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield cr.uploadToCOS(o);return i})}_processFile(e){var t,s;const{IN_BROWSER:n,IN_RN_APP:o,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:c}=null===(s=this._core)||void 0===s?void 0:s.helper;if(n||a){const t=or.extractFileFromInput(e);if(!t)throw new c({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(i||r){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return o?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:s,IN_MINI_APP:n,IN_WX_MINI_APP:o,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:r}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(n){if(!(o||i||r))throw new a({message:"Unsupported mini app environment"});const e=s.getSystemInfoSync().SDKVersion;if(o&&Lr(e,Dr)<0)throw new a({message:`WXChooseMessageFile requires SDK version ${Dr} or higher`});if(i&&Lr(e,br)<0)throw new a({message:`QQChooseMessageFile requires SDK version ${br} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Gr=2108,Ur=2351,kr=2352,Fr=["mp4","quicktime","mov","video"];var xr;class Vr{constructor(e){this.type=Wi,this.uploadProgress=0,this[xr]=!1;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this[sr]=e.isCustomUpload||!1,this.content={remoteVideoUrl:or.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:or.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:or.addAuthToUrl(e.thumbUrl),snapshotUrl:or.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:s,VideoFormat:n,VideoSecond:o,VideoSize:i,VideoDownloadFlag:r,VideoUUID:a,ThumbUUID:c,ThumbFormat:u,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:h,SnapshotHeight:p,ThumbSize:g,SnapshotSize:_,ThumbDownloadFlag:m,ThumbUrl:f,SnapshotUrl:v}=t;return new Vr({videoUrl:s,videoFormat:n,videoSecond:o,videoSize:i,videoDownloadFlag:r,videoUUID:a,thumbUUID:c,thumbFormat:u,thumbWidth:l,snapshotWidth:d,thumbHeight:h,snapshotHeight:p,thumbSize:g,snapshotSize:_,thumbDownloadFlag:m,thumbUrl:f,snapshotUrl:v})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:s,snapshotHeight:n}=e;or.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),or.isEmpty(s)||(this.content.thumbWidth=this.content.snapshotWidth=Number(s)),or.isEmpty(n)||(this.content.thumbHeight=this.content.snapshotHeight=Number(n))}validateBeforeSend(){if(this[sr])return{isValid:!0};const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{remoteVideoUrl:n,videoFormat:o,videoSecond:i,videoSize:r,videoDownloadFlag:a,videoUUID:c,thumbUUID:u,thumbFormat:l,thumbWidth:d,snapshotWidth:h,thumbHeight:p,snapshotHeight:g,thumbSize:_,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:v,snapshotUrl:I}=s;return{MsgType:this.type,MsgContent:{VideoUrl:or.removeAuthToUrl(n),VideoFormat:o,VideoSecond:i,VideoSize:r,VideoDownloadFlag:a,VideoUUID:c,ThumbUUID:u,ThumbFormat:l,ThumbWidth:d,SnapshotWidth:h,ThumbHeight:p,SnapshotHeight:g,ThumbSize:_,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:or.removeAuthToUrl(v),SnapshotUrl:or.removeAuthToUrl(I)}}}}xr=sr;var $r,qr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createVideoMessage",context:this}),n.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Wi,Vr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,n;try{const o=this._processVideo(e);e.payload.file=o;const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a={videoFormat:o.videoFile.type,videoSecond:qi(o.videoFile.second,0),videoSize:o.videoFile.size,remoteVideoUrl:"",videoUrl:o.videoFile.url,videoUUID:or.generateUUID(o.videoFile),thumbUUID:or.generateUUID(o.videoFile,"jpg"),thumbWidth:o.width||200,thumbHeight:o.height||200,thumbUrl:o.thumbUrl,thumbSize:o.thumbSize,thumbFormat:"jpg"},c=new Vr(a);return r.setElement(c),this._messageOptionsMap.set(r.clientSequence,e),r}catch(e){throw e}}createCustomUploadVideoMessage(e){var t,s,n;try{const{store:o,message:i}=this._core;this._validateCustomUploadVideoMessage(e);const r=null===(t=o.get("login"))||void 0===t?void 0:t.userId,{videoUrl:a,videoUuid:c,duration:u,snapshotUrl:l,snapshotUuid:d,videoFileSize:h,videoType:p,snapshotWidth:g,snapshotHeight:_,snapshotFileSize:m,snapshotType:f="jpg"}=(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.file)||{},v=null===(n=i.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),I=new Vr({videoFormat:p,videoSecond:u||0,videoSize:h,remoteVideoUrl:a,videoUrl:a,videoUUID:c,thumbUUID:d,thumbWidth:g||200,thumbHeight:_||200,thumbUrl:l,thumbSize:m,thumbFormat:f,isCustomUpload:!0});return v.setElement(I),this._messageOptionsMap.set(v.clientSequence,e),v}catch(e){throw e}}upload(e){return _e(this,void 0,void 0,function*(){const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(s);const n=yield this._performVideoUpload(t,e,s),{location:o,snapshotInfo:i}=n,r=or.addAuthToUrl(o);return t.updateVideoUrl(r),or.isEmpty(i)||t.updateSnapshotInfo(i),e})}_validateBeforeUploadVideo(e){const{helper:{ChatError:t}}=this._core,s=Mr(Qi)||104857600;if(e.videoFile.size>s)throw new t({code:Ur});if(0===e.videoFile.size)throw new t({code:Gr});if(-1===Fr.indexOf(e.videoFile.type))throw new t({code:kr})}_validateCustomUploadVideoMessage(e){var t;const{utils:{isEmpty:s,isNumber:n}}=this._core,{videoUrl:o,videoUuid:i,duration:r,snapshotUrl:a,snapshotUuid:c}=(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.file)||{};if(s(o)||s(i)||!n(r)||s(a)||s(c))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(e,t,s){return _e(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:Qi,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i,uploadOptions:r}=yield cr.uploadToCOS(o);return{snapshotInfo:yield this._getSnapshotInfoByUrl(r.requestSnapshotUrl),location:i.location}})}_processVideo(e){var t,s;try{const{ChatError:n}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:o,IN_BROWSER:i}=null===(s=this._core)||void 0===s?void 0:s.utils;let{file:r}=e.payload,a={};if(o&&(a=this._processMiniVideoFile(r),r.name=a.name,r.url=a.url,r.type=a.type),i){const e=or.extractFileFromInput(r);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});r=e,a=this._processWebVideoFile(r)}return r.videoFile=a,r.thumbUrl="",r.thumbSize=0,r}catch(e){throw console.warn(`${Yi} _processFile error:`,e),e}}_processMiniVideoFile(e){const{utils:{IN_UNI_NATIVE_APP:t},helper:{ChatError:s}}=this._core;if(Fi(e))throw new s({message:"FileUnsupportedInMiniApp"});Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]);let n=e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return t&&(n=e.fileType||n),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:n}}_processWebVideoFile(e){const{name:t,size:s=1,duration:n=0,type:o}=e,i=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:n,type:i}}_getSnapshotInfoByUrl(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t}=this._core;try{t.debug("_getSnapshotInfoByUrl",`${Yi} _getSnapshotInfoByUrl url:${e}`);const s={version:1,platform:or.getPlatform(),cover_name:$i(xi(99999)),snapshot_url:e},n=yield function(e,t){return _e(this,void 0,void 0,function*(){try{const s="im_cos_msg.video_cover",{helper:n,channel:o}=t,i=n.generateCosSpecifiedData({servcmd:s,data:e}),r=`${i.head.seq}${s}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}(s,this._core),{download_url:o}=n||{};if(t.debug("_getSnapshotInfoByUrl",`${Yi} _getSnapshotInfoByUrl OK snapshotUrl:${o}`),or.isEmpty(o))return{};const i=or.addAuthToUrl(o),{width:r=0,height:a=0}=yield or.probeImageWidthHeight(i);return{snapshotUrl:i,snapshotWidth:r,snapshotHeight:a}}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Br{constructor(e){this.uploadProgress=0,this.type=Hi,this[$r]=!1,this[sr]=e.isCustomUpload||!1,this.content={downloadFlag:2,second:e.second,size:e.size,url:or.generateURL(e.url,{needAddAuthToUrl:!this[sr]}),remoteAudioUrl:or.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:s,Download_Flag:n,Second:o,Size:i,UUID:r}=t;return new Br({url:s,downloadFlag:n,second:o,size:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){if(this[sr])return{isValid:!0};const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:n,downloadFlag:o,remoteAudioUrl:i,size:r,second:a}=s;return{MsgType:this.type,MsgContent:{Url:or.removeAuthToUrl(i),Download_Flag:o,Second:a,Size:r,UUID:n}}}}$r=sr;const jr=2108,Hr=2300,Kr=2301;var Wr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createAudioMessage",context:this}),n.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Hi,Br),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,n;try{let{file:o}=e.payload;o=this._processAudioFile(e.payload.file),e.payload.file=o;const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a={second:Math.max(1,Math.round((o.duration||o.second)/1e3)),size:o.fileSize||o.size||1,url:o.tempFilePath||o.uri||o.url,uuid:or.generateUUID(o)},c=new Br(a);return r.setElement(c),this._messageOptionsMap.set(r.clientSequence,e),r}catch(e){throw e}}createCustomUploadAudioMessage(e){var t,s,n;try{this._validateCustomUploadOptions(e);const{store:o,message:i}=this._core,r=null===(t=o.get("login"))||void 0===t?void 0:t.userId,{url:a,uuid:c,duration:u,fileSize:l}=(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.file)||{},d=null===(n=i.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),h=new Br({second:u,size:l||1,url:a,uuid:c,isCustomUpload:!0});return d.setElement(h),this._messageOptionsMap.set(d.clientSequence,e),d}catch(e){throw e}}upload(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("upload",`${Yi} uploadAudio message:${s(e)}`);const{file:n}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(n);const o=e.getElements()[0],i=yield this._performAudioUpload(o,e,n),r=or.addAuthToUrl(null==i?void 0:i.location);return o.updateAudioUrl(r),e})}_validateBeforeUploadAudio(e){const{helper:{ChatError:t},store:s}=this._core;if(!e)throw new t({code:Hr});const n=Mr(Xi)||20971520;if(e.size>n)throw new t({code:Kr});if(0===e.size)throw new t({code:jr})}_performAudioUpload(e,t,s){return _e(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:Xi,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield cr.uploadToCOS(o);return i})}_processAudioFile(e){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=null===(t=this._core)||void 0===t?void 0:t.utils;return s?this._processMiniFile(e):n?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_validateCustomUploadOptions(e){var t;const{utils:{isEmpty:s}}=this._core,{url:n,uuid:o,duration:i}=(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.file)||{};if(s(n)||s(o)||s(i))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Yr={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},zr={createImageMessage:Yr,createAudioMessage:Yr,createVideoMessage:Yr,createFileMessage:Yr},Jr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Qr={[ji]:Tr,[Ki]:Pr,[Wi]:qr,[Hi]:Wr};var Xr=new class{constructor(){this.name="RichMediaMessage"}install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:n,MSG_VIDEO:o}}}=e;Er.init(e),Tr.init(e),Pr.init(e),qr.init(e),Wr.init(e),cr.init(e),or.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,n,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Jr,params:zr})}sendMessage(e,t){return _e(this,void 0,void 0,function*(){var s,n,o;try{return this._isCustomUpload(e)||(yield this._upload(e)),yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)}catch(e){throw e}})}_upload(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;if(t.debug("_upload",` uploadFile message:${s(e)}`),!0!==e._relayFlag)try{const s=Qr[e.type];s&&(yield s.upload(e),t.info("_upload",` type:${e.type}`))}catch(t){throw e.status=er.FAIL,t instanceof Error&&(t.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),t}})}_isCustomUpload(e){var t,s;return!0===(null===(s=null===(t=e._elements)||void 0===t?void 0:t[0])||void 0===s?void 0:s[sr])}};const Zr=new class{init(e){this.core=e}},ea=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Zr;return s(e)&&e.slice(0,3)===t.CONV_C2C},ta=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Zr;return s(e)&&e.slice(0,5)===t.CONV_GROUP},sa=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Zr;return s(e)&&e===t.CONV_SYSTEM},na=e=>({lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:Zr.core.common.getMessagePreviewText(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null});function oa(e){const{OuterConstant:t}=Zr.core;let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}function ia(e){const{OuterConstant:t}=Zr.core;let s;return e.startsWith(t.CONV_C2C)&&(s=e.replace(t.CONV_C2C,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}function ra(e,t){const{helper:s}=Zr.core,n=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(`${e} fail:`,n),n}class aa{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=na(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark=e.remark||"",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var e;const{core:{OuterConstant:t,utils:{isUndefined:s}}}=Zr;s(this.userProfile)&&this.type===t.CONV_C2C?this.userProfile={userID:this.conversationID.replace(t.CONV_C2C,"")}:this.type===t.CONV_GROUP&&(!this.subType&&(null===(e=this.groupProfile)||void 0===e?void 0:e.type)&&(this.subType=this.groupProfile.type),s(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(t.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(e){var t;const{core:{OuterConstant:s,utils:{isUndefined:n},store:o}}=Zr,{nextUnreadCount:i,isFromGetConversations:r,isUnreadC2CMessage:a}=e;if(n(i))return;if(this.subType===s.GRP_AVCHATROOM)return void(this.unreadCount=0);if(r&&this.type===s.CONV_GROUP)return void(this.unreadCount=i);if(a&&this.type===s.CONV_C2C)return void(this.unreadCount=i);const c="1"===(null===(t=o.get("cloudConfig"))||void 0===t?void 0:t.support_unread_count_for_meeting);this.subType!==s.GRP_MEETING||c?this.unreadCount+=i:this.unreadCount=0}updateLastMessage(e){this.lastMessage=na(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{core:{OuterConstant:t}}=Zr,{sequence:s,time:n}=e;return this.type===t.CONV_C2C&&s===this.lastMessage.lastSequence&&n===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&s===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){const{core:{common:{updateGroupAtInfo:t}}}=Zr;t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var ca,ua,la;!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(ca||(ca={})),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ua||(ua={})),function(e){e[e.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",e[e.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",e[e.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"}(la||(la={}));const da=0,ha=1;var pa=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(e){return _e(this,void 0,void 0,function*(){try{const{common:t}=this._core,s=yield function(e,t){return _e(this,void 0,void 0,function*(){const{toAccount:s,userIDList:n}=e,o={To_Account:s,Peer_Account:n};return t.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:o})})}({toAccount:t.getCurrentUserID(),userIDList:e},this._core),{MuteNotificationsList:n=[]}=s||{};n.forEach(e=>{const{Peer_Account:t,MuteNotifications:s}=e,n=`${this._core.OuterConstant.CONV_C2C}${t}`,o=oa(s);_a.patchMessageRemindType([n],o)})}catch(e){console.error(`${this._name}.get fail:`,e)}})}},ga=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(e){return _e(this,void 0,void 0,function*(){if(0!==e.length)try{const t=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupIDList:s,responseFilter:n}=e,o={GroupIdList:s,ResponseFilter:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:o})})}({groupIDList:e,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:s=[]}=t||{};s.forEach(e=>{var t;const{GroupId:s,MemberList:n}=e,o=(null===(t=n[0])||void 0===t?void 0:t.MsgFlag)||"",i=`${this._core.OuterConstant.CONV_GROUP}${s}`;_a.patchMessageRemindType([i],o)})}catch(e){console.error(`${this._name}.get fail:`,e)}})}},_a=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){this._core=e;const{helper:t,notificationCenter:s,appStore:{conversationStore:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},InnerEvent:{SYNC_CONVERSATION_LIST:r,MESSAGE_PUSH:a,NEW_MESSAGE:c,MESSAGE_DELETED:u,MESSAGE_REVOKED:l,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:h,LOGOUT:p,DESTROY:g},InnerEventSubType:{C2C_MESSAGE_PEER_READ:_}}=e;this._conversationStore=n,t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_GROUP_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_GROUP_TIPS_NOTIFICATION,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:m}}=s;s.subscribeInnerEvent(r,this._handleConversationSynced,this),s.subscribeInnerEvent(c,this._handleNewMessage,this),s.subscribeInnerEvent(a,m,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(l,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(h,this._handleConversationUpdated,this),s.subscribeInnerEvent(a,_,this._handleMessageRead,this),s.subscribeInnerEvent(p,this._reset,this),s.subscribeInnerEvent(g,this._dispose,this),e.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){const{constants:{WORKFLOW_STEP:t}}=this._core,{conversationUpdateFieldList:s=[],groupTipList:n=[],isUnreadC2CMessage:o}=e.result[t.UNREAD_MESSAGE_SYNC]||{};let i=!1;s.forEach(e=>{const{conversationID:t,unreadCount:s}=e,n=this.getLocalConversation(t);n&&n.unreadCount!==s&&(n.updateUnreadCount({nextUnreadCount:s,isUnreadC2CMessage:o}),i=!0)}),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(n)}_handleGroupAtTipsSynced(e){var t;for(let s=0;s<e.length;s++)if(12===e[s].Event){if(null===(t=e[s].GroupTips[0].MsgBody)||void 0===t?void 0:t.TopicId)continue;this._handleNewGroupAtTips(e[s])}}_handleGroupListSyncFinished(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,n=e.result[s.GROUP_LIST_SYNC]||[],{OuterConstant:{CONV_GROUP:o}}=this._core;let i=!1;for(let e=0;e<n.length;e++){const s=n[e],r=`${o}${s.groupID}`;if(!this.hasLocalConversation(r))continue;const a=this.getLocalConversation(r);a.groupProfile=JSON.parse(JSON.stringify(s)),a.lastMessage.lastSequence<s.nextMessageSeq&&(a.lastMessage.lastSequence=s.nextMessageSeq-1),a.subType||(a.subType=s.type),(null===(t=s._groupAtInfoList)||void 0===t?void 0:t.length)>0&&this._handleNewGroupAtTips({GroupTips:s._groupAtInfoList}),i=!0}i&&this.emitConversationListUpdate()}_handleNewMessage(e){const{conversationUpdateFieldList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:o=!0}=e.result||{};if(0===t.length)return;const{common:{isTopic:i}}=this._core;i(t[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:t,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:o}),t.filter(e=>this._isConversationNeedShow(e.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){const{GroupTips:t=[]}=e;t.forEach(e=>{const{GroupAtTips:t,MsgBody:s,MsgRandom:n,ClientSeq:o}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=n,i.__sequence=o,this._groupAtTipsList.push(i)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){const{From_Account:t,GroupId:s,MsgSeq:n,GroupAtType:o}=e;return{from:t,groupID:s,sequence:n,groupAtType:o}}_updateGroupAtInfoList(){if(0===this._groupAtTipsList.length)return;const{common:e,OuterConstant:t}=this._core,s=e.getCurrentUserID();let n=!1;this._groupAtTipsList.forEach(e=>{const{groupID:o,from:i}=e;if(i!==s){const s=this.getLocalConversation(`${t.CONV_GROUP}${o}`);s&&(s.updateGroupAtInfoList(e),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(e){var t,s;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const{message:{messageDataHandler:n},OuterConstant:o}=this._core,i=(null==n?void 0:n.getLocalMessageList(e))||[];let r={};for(let e=(i.length||0)-1;e>=0;e--)if(!i[e].isDeleted){r=i[e];break}const a=this.getLocalConversation(e);if(!a)return;let c=!1;a.lastMessage.lastSequence===r.sequence&&a.lastMessage.lastTime===r.time||((null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r))&&(r=void 0),a.updateLastMessage(r),c=!0),e.startsWith(o.CONV_C2C)&&this.updateUnreadCount(e),c&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${e} with lastMessage:`,a.lastMessage))}_handleMessageRevoked(e){const{messageList:t=[],updateUnreadCount:s=!0}=e;if(console.log(`${this._name}._handleMessageRevoked messageList:${t.length}`),0===t.length)return;let n=null,o=!1;t.forEach(e=>{n=this.getLocalConversation(e.conversationID),n&&(s&&n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(e.revoker),o=!0))}),o&&this.emitConversationListUpdate()}_handleMessageModified(e){console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:t,messageList:s}=e,n=this.getLocalConversation(t),{utils:{isEmpty:o},common:{getMessagePreviewText:i}}=this._core;if(o(n))return;const{lastMessage:r}=n;if(r){const e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${t} lastMessage updated`))}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){const{isFromGetConversations:t}=e,{newConversationList:s}=this._getTmpConversationListMapping(e);this._sortConversationList(),t||this._updateNewConversationProfile(s),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${s.length}`)}_getTmpConversationListMapping(e){const{OuterConstant:t}=this._core,{conversationUpdateFieldList:s,isFromGetConversations:n,isInstantMessage:o,isUnreadC2CMessage:i=!1,updateUnreadCount:r}=e,a=[],c=null==s?void 0:s.length;for(let e=0;e<c;e++){const c=new aa(s[e]),{conversationID:u,type:l}=c;if(!ia(u))if(this.hasLocalConversation(u)){const a=this.getLocalConversation(u);if(n){this.setLocalConversation(u,c),l===t.CONV_C2C?c.unreadCount=(null==a?void 0:a.unreadCount)||0:l===t.CONV_GROUP&&(c.groupProfile=JSON.parse(JSON.stringify(null==a?void 0:a.groupProfile)));continue}this._mergeConversationInfo({conversationID:u,tmpConversation:c,lastMessage:s[e].lastMessage,isFromGetConversations:n,isInstantMessage:o}),this._patchLastMessage({conversationID:u,lastMessage:s[e].lastMessage,isInstantMessage:o}),!0===r&&(null==a||a.updateUnreadCount({nextUnreadCount:c.unreadCount,isFromGetConversations:n,isUnreadC2CMessage:i}))}else a.push(c),this.setLocalConversation(u,c)}return{newConversationList:a}}_mergeConversationInfo(e){const{conversationID:t,tmpConversation:s,lastMessage:n,isFromGetConversations:o,isInstantMessage:i}=e,r=this.getLocalConversation(t),a=["unreadCount","allowType","adminForbidType","payload"];!1===i&&a.push("lastMessage"),o||a.push("isPinned");const{utils:{isUndefined:c,isEmpty:u},common:{deepMerge:l}}=this._core;c(i)&&n&&null===(null==r?void 0:r.lastMessage.payload)&&(r.lastMessage.payload=n.payload),u(null==r?void 0:r.lastMessage.revoker)||(r.lastMessage.revoker=null),l(r,s,a,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{OuterConstant:t}=this._core,{conversationID:s,lastMessage:n,isInstantMessage:o}=e,i=this.getLocalConversation(s);if(i&&n){const{payload:e,nameCard:s,nick:r,cloudCustomData:a=""}=n;o&&(e&&(i.lastMessage.payload=e),i.type===t.CONV_GROUP&&(i.lastMessage.nameCard=s,i.lastMessage.nick=r)),i.lastMessage.cloudCustomData!==a&&(i.lastMessage.cloudCustomData=a)}}_sortConversationList(){const{utils:{isEmpty:e}}=this._core,t=[...this._conversationStore.getConversationMap()],s=[],n=[],o=[],i=[];t.forEach(t=>{!0===t[1].isPinned?e(t[1].lastMessage.lastTime)?n.push(t):s.push(t):e(t[1].lastMessage.lastTime)?i.push(t):o.push(t)});const r=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(n).concat(o.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(i);this._updateConversationMapFromList(r)}_updateNewConversationProfile(e){if(0===e.length)return;const t=[],s=[],{OuterConstant:{CONV_GROUP:n,CONV_C2C:o}}=this._core;e.forEach(e=>{const{conversationID:i,type:r}=e;if(r===o){const e=i.replace(o,"");t.push(e)}else if(r===n){const e=i.replace(n,"");s.push(e)}}),t.length>0&&this._updateC2CConversation(t),s.length>0&&this._updateGroupConversation(s)}_updateC2CConversation(e){var t;const{OuterConstant:{CONV_C2C:s},appStore:{userStore:n},user:o}=this._core;let i=!1;null===(t=o.userProfile)||void 0===t||t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(e=>{var t;const{userID:o}=e,r=this.getLocalConversation(`${s}${o}`);if(r){const s=(null===(t=n.getFriend(o))||void 0===t?void 0:t.remark)||"";r.remark=s,r.userProfile=e,i=!0}}),i&&this.emitConversationListUpdate()}).catch(e=>{}),pa.get(e)}_updateGroupConversation(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s},utils:{safeStringify:n},ssoLog:o,apiMap:{getGroupProfile:i}}=this._core;let r=!1;try{yield Promise.all(e.map(e=>_e(this,void 0,void 0,function*(){const n=s.getGroup(e),o=this.getLocalConversation(`${t}${e}`);n&&o&&(o.groupProfile=n,r=!0),o&&!o.getProfileCompleted()&&"function"==typeof i&&(yield i({groupID:e}))}))),ga.get(e),r&&this.emitConversationListUpdate()}catch(e){o.debug("_updateGroupConversation",n(e))}})}_handleMessageRead(e){const{OuterConstant:{CONV_C2C:t}}=this._core,{C2cNotifyMsgArray:s=[]}=e||{};s.forEach(e=>{const{To_Account:s,UinPairReadArray:n=[]}=(null==e?void 0:e.C2cReadedReceipt)||{};null==n||n.forEach(e=>{const{LastReadTime:n}=e,o=`${t}${s}`;this._updateConversationReadInfo({conversationID:o,peerReadTime:n}),this._updateMessageListPeerRead({conversationID:o,peerReadTime:n})})})}_updateConversationReadInfo(e){const{appStore:t,utils:{isEmpty:s},common:{getCurrentUserID:n}}=this._core,{conversationID:o,peerReadTime:i}=e,r=t.conversationStore.getConversationMap();if(r.has(o)){const e=r.get(o);e.peerReadTime=i;const a=null==e?void 0:e.lastMessage;s(a)||a.fromAccount===n()&&a.lastTime<=i&&!a.isPeerRead&&(a.isPeerRead=!0,t.conversationStore.updateConversation(o,{lastMessage:a}))}}_updateMessageListPeerRead(e){const{notificationCenter:t,OuterEvent:s,message:n}=this._core,{conversationID:o,peerReadTime:i}=e,r=n.messageDataHandler.getLocalMessageList(o),a=n.messageDataHandler.getSparseMessageList(o),c=[];r.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),a.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),t.emitOuterEvent(s.MESSAGE_READ_BY_PEER,{name:s.MESSAGE_READ_BY_PEER,data:c})}_isConversationNeedShow(e){var t,s;const{OuterConstant:{CONV_GROUP:n,GRP_ROOM:o,GRP_LIVE:i},utils:{isUndefined:r}}=this._core,a=this.getLocalConversation(e);if(r(a))return!0;const c=a.type===n&&(null===(t=a.groupProfile)||void 0===t?void 0:t.type)===o,u=a.type===n&&(null===(s=a.groupProfile)||void 0===s?void 0:s.type)===i;return!(c||u)}updateUnreadCount(e,t=!0){var s,n;let o=!1;const i=this.getLocalConversation(e),r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageDataHandler)||void 0===n?void 0:n.getLocalMessageList(e);if(!i)return o;const a=i.unreadCount,c=null==r?void 0:r.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${e} currentUnreadCount:${a} newUnreadCount:${c}`),a!==c&&(i.unreadCount=c,o=!0,!0===t&&this.emitConversationListUpdate()),o}emitConversationListUpdate(e=!1){var t,s;e&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:n},conversation:o}=this._core,i=this.getLocalConversationList();this._emitEvent({name:n,data:i,isSyncCompleted:null===(s=null===(t=null==o?void 0:o.syncConversationHandler)||void 0===t?void 0:t.isSyncCompleted)||void 0===s?void 0:s.call(t)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${t}`),this._totalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){const{OuterConstant:e,utils:{isEmpty:t}}=this._core,s=this.getLocalConversationList();let n=0;return s.forEach(s=>{s.type!==e.CONV_SYSTEM&&(t(s.messageRemindType)||s.messageRemindType===e.MSG_REMIND_ACPT_AND_NOTE)&&(n+=s.unreadCount)}),n}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(e=>this._isConversationNeedShow(e.conversationID))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(const[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{const n=this.getLocalConversation(e);(null==n?void 0:n.messageRemindType)!==t&&(n.messageRemindType=t,s=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:${s}`),s&&this.emitConversationListUpdate()}markMessageAsRead(e){const{message:{messageDataHandler:t}}=this._core,{conversationID:s,lastReadTime:n=0,lastReadSequence:o=0}=e,i=null==t?void 0:t.getLocalMessageList(s);if(0===i.length)return;const{length:r}=i;for(let e=r-1;e>=0;e--){const t=i[e],s=n&&t.time>n,r=o&&t.sequence>o;if(!s&&!r){if("in"===t.flow&&t.isRead)break;t.setIsRead(!0)}}}appendToPinnedConversation(e){const t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:n,MESSAGE_MODIFIED:o,CONVERSATION_UPDATED:i,LOGOUT:r,DESTROY:a,SYNC_CONVERSATION_LIST:c}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:u}}=e;e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(o,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(c,this._handleConversationSynced,this),e.unSubscribeInnerEvent(r,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},ma=new class{constructor(){this._name="GetConversationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return _e(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(e){const{utils:{isUndefined:t,isArray:s,isPlainObject:n}}=this._core;if(t(e))return _a.getLocalConversationList();if(s(e))return 0===e.length?[]:_a.getLocalConversationList().filter(t=>e.includes(t.conversationID));if(n(e)){const{type:t,markType:s,groupName:n,hasUnreadCount:o,hasGroupAtInfo:i}=e;return _a.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,i))}return[]}_filterType(e,t){const{OuterConstant:s}=this._core;return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){const{utils:{isString:s}}=this._core;return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){const{utils:{isNumber:s}}=this._core;return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}},fa=new class{constructor(){this._name="GetConversationProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,GRP_AVCHATROOM:n},appStore:{groupStore:o},utils:{isEmpty:i}}=this._core,r={code:0,data:{}};let a=_a.getLocalConversation(e);if(sa(e))return r.data.conversation=a,r;let c=!1;const u=ea(e)?t:s;if(i(a)&&(c=!0,a=new aa({conversationID:e,type:u})),console.log(`${this._name}.getConversationProfile conversationID:${e} isNewConversation:${c}`),r.data.conversation=a,null==a?void 0:a.getProfileCompleted())return r;if(u===t){const s=e.replace(t,"");yield this._handleC2CConversation(a,s),c&&(yield pa.get([s]))}if(u===s){const t=e.replace(s,"");if(!o.getGroup(t))return r;yield this._handleGroupConversation(a,t),c&&a.groupProfile.type!==n&&(yield ga.get([t]))}return r})}_handleC2CConversation(e,t){return _e(this,void 0,void 0,function*(){var s,n;const{user:o,helper:i,utils:{isEmpty:r},appStore:{conversationStore:a,userStore:c}}=this._core,{conversationID:u}=e,l=yield null===(s=o.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:[t]});if(0===(null==l?void 0:l.data.length))throw new i.ChatError({code:la.USER_OR_GRP_NOT_FOUND});e.userProfile=null==l?void 0:l.data[0];const d=null===(n=c.getFriend(t))||void 0===n?void 0:n.remark;r(d)||e.remark===d||(e.remark=d),e.setProfileCompleted();const h=_a.hasLocalConversation(u);console.log(`${this._name}._handleC2CConversation conversationID:${u} hasLocalConversation: ${h}`),h?a.updateConversation(u,e):_a.appendToPinnedConversation(e)})}_handleGroupConversation(e,t){return _e(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:s},appStore:{conversationStore:n}}=this._core,{conversationID:o}=e,i=yield s({groupID:t});e.groupProfile=null==i?void 0:i.data.group,e.setProfileCompleted();const r=_a.hasLocalConversation(o);console.log(`${this._name}._handleGroupConversation conversationID:${o} hasLocalConversation: ${r}`),r?n.updateConversation(o,e):_a.appendToPinnedConversation(e)})}},va=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return _a.getTotalUnreadMessageCount()}},Ia=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){this._core=e;const{helper:t,common:{isTopic:s},notificationCenter:n,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{ALL_MESSAGE_READ:i}}=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),n.subscribeInnerEvent(o,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach(e=>{const{ReadC2cMsgNotify:n}=e;if(!t(n)){const{UinPairReadArray:e=[]}=n;e.forEach(e=>{const{From_Account:t,LastReadTime:n}=e,o=`${s.CONV_C2C}${t}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${o} lastReadTime:${n}`),_a.markMessageAsRead({conversationID:o,lastReadTime:n}),_a.updateUnreadCount(o)})}})}handleGroupMessageReadSync(e){const{OuterConstant:t,utils:{isUndefined:s}}=this._core;e.forEach(e=>{const{GroupReadInfoArray:n}=e.MsgBody;s(n)||n.forEach(e=>{const{GroupId:s,LastReadMsgSeq:n}=e,o=`${t.CONV_GROUP}${s}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${o} lastReadSequence:${n}`),_a.markMessageAsRead({conversationID:o,lastReadSequence:n}),_a.updateUnreadCount(o),this._clearGroupAtInfoList(o)})})}setMessageRead(e){return _e(this,void 0,void 0,function*(){var t,s;const{OuterConstant:n}=this._core,{conversationID:o}=e,i={code:0,data:{}},r=_a.getLocalConversation(o);let a=`${this._name}.setMessageRead conversationID:${o} unreadCount:${(null==r?void 0:r.unreadCount)||0}`;if(i.successLog={message:a},!r)return i;const c=!(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r.groupAtInfoList));if(r.type===n.CONV_GROUP&&c&&this._deleteGroupAtTips(o),0===r.unreadCount)return i;const{helper:{ChatError:u}}=this._core;try{if(r.type===n.CONV_C2C){const e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(o,e),a+=`lastMessageTime:${e}`}if(r.type===n.CONV_GROUP){const e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(o,e),a+=`lastMessageSequence:${e}`}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new u({functionName:"setMessageRead",code:t,message:s,moreMessage:a})}return r.type===n.CONV_SYSTEM&&(r.unreadCount=0),_a.emitConversationListUpdate(),Object.assign(Object.assign({},i),{successLog:{message:a}})})}setAllMessageRead(){return _e(this,arguments,void 0,function*(e={}){const{OuterConstant:{READ_ALL_MSG:t},utils:{safeStringify:s}}=this._core;let n=`scope:${e.scope}`;e.scope||(e.scope=t);const{scope:o}=e,i=this._generateSetAllMessageReadRequestData(o);if(i.allC2CMessageReadStatus===da&&0===i.groupMessageReadInfoList.length)return{code:0};try{const e=yield function(e){return _e(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:t,groupMessageReadInfoList:s}=e,n={C2CReadAllMsg:t,GroupReadInfo:s};return Zr.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:n})})}(i);if(e){const{GroupReadInfoArray:t,C2CReadAllMsg:o}=e,i=this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:o})>0&&_a.emitConversationListUpdate(),n+=`failureGroupInfoList:${s(i)}`}return{code:0,successLog:{message:n}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:t,moreMessage:n})}})}_handleAllMessageRead(e){const{GroupReadInfoArray:t,C2CReadAllMsg:s}=e;this._parseGroupReadInfo(t),this._updateAllConversationReadStatus({allC2CMessageReadStatus:s})>0&&_a.emitConversationListUpdate()}_updateAllConversationReadStatus(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s},appStore:n}=this._core,o=n.conversationStore.getConversationMap(),{allC2CMessageReadStatus:i}=e;let r=0;for(const[e,n]of o)if(n.unreadCount>=1){if(i===ha&&n.type===t){const t=this._getLocalMessageMaxTime(n);_a.markMessageAsRead({conversationID:e,lastReadTime:t})}else if(n.type===s){const t=e.replace(s,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){const s=this._serverGroupConversationLastReadSeqMap.get(t);_a.markMessageAsRead({conversationID:e,lastReadSequence:s})}}_a.updateUnreadCount(e,!1)&&(r+=1)}return r}_generateSetAllMessageReadRequestData(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_C2C_MSG:n},appStore:o}=this._core,i={allC2CMessageReadStatus:da,groupMessageReadInfoList:[]},r=o.conversationStore.getConversationMap();for(const[,o]of r){const{type:r,unreadCount:a}=o;if(this._shouldSetAllMessageRead({scope:e,type:r,unreadCount:a}))if(r===t&&i.allC2CMessageReadStatus===da){if(i.allC2CMessageReadStatus=ha,e===n)break}else if(r===s){const e=this._getLocalMessageMaxSequence(o),{groupID:t}=o.groupProfile;i.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return i}_parseGroupReadInfo(e){const{utils:{isUndefined:t}}=this._core,s=[];return null==e||e.forEach(e=>{const{GroupId:n,MsgSeq:o,RetCode:i,LastReadMsgSeq:r}=e;t(i)?this._serverGroupConversationLastReadSeqMap.set(n,r):(this._serverGroupConversationLastReadSeqMap.set(n,o),0!==i&&s.push(`${n}-${o}-${i}`))}),s}_deleteGroupAtTips(e){return _e(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${e}`);const t=_a.getLocalConversation(e);if(!t)return;const s=(null==t?void 0:t.groupAtInfoList)||[];if(0!==s.length)try{const{common:{getCurrentUserID:t,isCommunity:n},OuterConstant:{CONV_GROUP:o,CONV_AT_ALL:i}}=this._core;let r=[...s];if(n({groupID:e.replace(o,"")})&&(r=s.filter(e=>!e.atTypeArray.includes(i)),0===r.length))return void this._clearGroupAtInfoList(e,!1);const a=r.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}));yield function(e,t){return _e(this,void 0,void 0,function*(){const{messageListToDelete:s}=e,n={DelMsgList:s};return t.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:n})})}({messageListToDelete:a},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${s.length}`),this._clearGroupAtInfoList(e)}catch(e){console.error(`${this._name}._deleteGroupAtTips fail:`,e)}})}_clearGroupAtInfoList(e,t=!0){const s=_a.getLocalConversation(e);s&&(s.groupAtInfoList.length>0&&(s.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:${t}`)),t&&_a.emitConversationListUpdate())}_getLocalMessageMaxTime(e){var t;const{conversationID:s}=e,n=this._core.message.messageDataHandler.getLocalMessageList(s),o=Math.max(...n.map(e=>e.time));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastTime)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${i} to ${o}`),i=o),i}_getLocalMessageMaxSequence(e){var t;const{conversationID:s}=e,n=this._core.message.messageDataHandler.getLocalMessageList(s),o=Math.max(...n.map(e=>e.sequence));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to ${o}`),i=o),i}_setC2CMessageRead(e,t){return _e(this,void 0,void 0,function*(){try{yield function(e,t){return _e(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:e})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${t}`),_a.markMessageAsRead({conversationID:e,lastReadTime:t}),_a.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setC2CMessageRead fail:`,e),e}})}_setGroupMessageRead(e,t){return _e(this,void 0,void 0,function*(){try{yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,lastMessageSequence:n}=e,o={GroupId:s,MsgReadedSeq:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:o})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${t}`),_a.markMessageAsRead({conversationID:e,lastReadSequence:t}),_a.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setGroupMessageRead fail:`,e),e}})}_shouldSetAllMessageRead(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:n,READ_ALL_C2C_MSG:o,READ_ALL_GROUP_MSG:i}}=this._core,{type:r,scope:a,unreadCount:c}=e;return!(c<=0||(r!==t||![n,o].includes(a))&&(r!==s||![n,i].includes(a)))}},Ea=new class{constructor(){this._name="PinConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,t){const{utils:{isArray:s}}=this._core;if(!s(e))return;const{OuterConstant:n}=this._core;let o=!1;e.forEach(e=>{const{Type:s,Peer_Account:i,GroupId:r}=e;let a;1===s?a=_a.getLocalConversation(`${n.CONV_C2C}${i}`):2===s&&(a=_a.getLocalConversation(`${n.CONV_GROUP}${r}`)),a&&(console.log(`${this._name}.handleConversationPinned conversationID:${a.conversationID} localPinned:${a.isPinned} remotePinned:${t}`),t&&!a.isPinned&&(a.isPinned=!0,o=!0),!t&&a.isPinned&&(a.isPinned=!1,o=!0))}),o&&_a.emitConversationListUpdate(!0)}pinConversation(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:t,common:s,helper:{ChatError:n}}=this._core,{conversationID:o,isPinned:i}=e,r={code:0,data:{conversationID:o}},a=_a.getLocalConversation(o);if(a&&a.isPinned===i)return r;if(sa(o))return a&&(a.isPinned=i),_a.emitConversationListUpdate(!0),r;const c=`conversationID:${o} isPinned:${i}`;try{let e=null;ea(o)?e={Type:1,To_Account:o.replace(t.CONV_C2C,"")}:ta(o)&&(e={Type:2,GroupId:o.replace(t.CONV_GROUP,"")});const n=yield function(e,t){return _e(this,void 0,void 0,function*(){const{fromAccount:s,operationType:n,itemList:o}=e,i={From_Account:s,OperationType:n,RecentContactItem:o};return t.common.buildAndSendPacket({servcmd:"recentcontact.top",data:i})})}({fromAccount:s.getCurrentUserID(),operationType:!0===i?1:2,itemList:[e]},this._core);if(n){if(a)a.isPinned!==i&&(a.isPinned=i);else{const e=new aa({conversationID:o,type:ea(o)?t.CONV_C2C:t.CONV_GROUP,isPinned:i});_a.setLocalConversation(o,e)}_a.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},r),{successLog:{message:c}})}catch(e){const{errorCode:t,errorInfo:s}=e;throw new n({functionName:"pinConversation",code:t,message:s,moreMessage:c})}})}},Ca=new class{constructor(){this._name="DeleteConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){const{utils:{isArray:t}}=this._core;if(!t(e))return;const{OuterConstant:s}=this._core,n=[];e.forEach(e=>{const{Type:t,Peer_Account:o,GroupId:i}=e;1===t&&n.push(`${s.CONV_C2C}${o}`),2===t&&n.push(`${s.CONV_GROUP}${i}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${n}`),this._deleteLocalConversationList(n)}deleteConversation(e){return _e(this,void 0,void 0,function*(){const{utils:{isString:t}}=this._core;if(t(e))return this._deleteConversation({conversationIDList:[e],flag:ua.ONLY_CONVERSATIONID});const s=Object.assign({},e);return s.conversationIDList.length>100&&(s.conversationIDList=s.conversationIDList.slice(0,100)),this._deleteConversation(s)})}_deleteConversation(e){return _e(this,void 0,void 0,function*(){const{conversationIDList:t,clearHistoryMessage:s=!0,flag:n=0}=e,{helper:{ChatError:o}}=this._core,i=`conversationIDList:${t} clearHistoryMessage:${s}`;try{const e=yield Promise.all([this._deleteConversationFromLocal(t),this._deleteConversationFromServer(t,s)]),o=[...e[0],...e[1]];if(0===o.length)throw new this._core.helper.ChatError({code:la.CONV_NOT_FOUND});return{code:0,data:n===ua.ONLY_CONVERSATIONID?{conversationID:o[0]}:{conversationIDList:o},successLog:{message:i}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new o({code:t,message:s,moreMessage:i})}})}_deleteConversationFromLocal(e){const{OuterConstant:t}=this._core;return e.filter(e=>{var s;if(!_a.hasLocalConversation(e))return!1;const n=null===(s=_a.getLocalConversation(e))||void 0===s?void 0:s.type;return n!==t.CONV_GROUP||this._hasLocalGroup(e)?n===t.CONV_SYSTEM&&(this._deleteLocalConversation(e),!0):(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(e,t){return _e(this,void 0,void 0,function*(){const{OuterConstant:s,common:n}=this._core,o={fromAccount:n.getCurrentUserID(),conversationList:[],clearHistoryMessage:t?1:0};if(e.forEach(e=>{var t;if(_a.hasLocalConversation(e)){const n=(null===(t=_a.getLocalConversation(e))||void 0===t?void 0:t.type)||"",i=e.replace(n,"");n===s.CONV_C2C?o.conversationList.push({To_Account:i,Type:1}):n===s.CONV_GROUP&&this._hasLocalGroup(e)&&o.conversationList.push({ToGroupid:i,Type:2})}}),0===o.conversationList.length)return[];const i=yield function(e,t){return _e(this,void 0,void 0,function*(){const{fromAccount:s,conversationList:n,clearHistoryMessage:o}=e,i={From_Account:s,ContactItem:n,ClearRamble:o};return t.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:i})})}(o,this._core);if(i){const{ResultItem:e=[]}=i,t=[];return e.length>0&&e.forEach(e=>{if(0===e.ResultCode){const n=1===e.Type?`${s.CONV_C2C}${e.To_Account}`:`${s.CONV_GROUP}${e.ToGroupid}`;t.push(n)}}),this._deleteLocalConversationList(t),t}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{_a.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${t}`),t&&_a.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){const s=_a.hasLocalConversation(e);console.log(`${this._name}._deleteLocalConversation conversationID:${e} has:${s}`),s&&(_a.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t&&_a.emitConversationListUpdate())}_hasLocalGroup(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,n=e.replace(t,"");return!!s.getGroup(n)}_deleteConversationLocalMessage(e){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${e}`),this._core.message.messageDataHandler.deleteConversationMessageList(e),this._core.message.messageHistory.completedHistoryConversations.delete(e)}},ya=new class{constructor(){this._name="SetConversationDraft"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(e){return _e(this,void 0,void 0,function*(){const{conversationID:t,draftText:s}=e;if(console.log(`${this._name} conversationID:${t} draftText:${s}`),!_a.hasLocalConversation(t))throw new this._core.helper.ChatError({code:la.CONV_NOT_FOUND});const n=_a.getLocalConversation(t);return null==n||n.setDraftText(s),_a.emitConversationListUpdate(),{code:0,data:{conversation:n}}})}},Sa=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(e,t){return _e(this,void 0,void 0,function*(){e.length>30&&(console.warn(`${this._name}.set userIDList length:${e.length} exceeds limit 30`),e.splice(30));const s=function(){const{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=Zr.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[t],n=yield function(e,t){return _e(this,void 0,void 0,function*(){const{userIDList:s,receiveMessageOption:n}=e,o={Peer_Account:s,Mute_Notifications:n};return t.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:o})})}({userIDList:e,receiveMessageOption:s},this._core),{ErrorList:o=[]}=n||{},i=[];o.forEach(t=>{const{Peer_Account:s,ErrorCode:n}=t;i.push({userID:s,code:n});const o=e.indexOf(s);o>-1&&e.splice(o,1)});const r=[],a=[],{OuterConstant:c}=this._core;return e.forEach(e=>{a.push(`${c.CONV_C2C}${e}`),r.push({userID:e})}),_a.patchMessageRemindType(a,t),{code:0,data:{successUserIDList:r,failureUserIDList:i}}})}},Ma=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(e,t){return _e(this,void 0,void 0,function*(){const{common:{getCurrentUserID:s,isTopic:n},OuterConstant:o}=this._core;if(yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,userID:n,receiveMessageOption:o}=e,i={GroupId:s,Member_Account:n,MsgFlag:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:i})})}({groupID:e,userID:s(),receiveMessageOption:t},this._core),!n(e)){const s=`${o.CONV_GROUP}${e}`;_a.patchMessageRemindType([s],t)}return{code:0,data:{groupID:e,messageRemindType:t}}})}},Ta=new class{constructor(){this._name="SetMessageRemindType"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){const{helper:{isEmpty:t},OuterConstant:s,ssoLog:n}=this._core;e.forEach(e=>{const{MuteNotificationsSync:o}=e;if(!t(o)){const{To_Account:e,MuteNotifications:t}=o,i=e.map(e=>`${s.CONV_C2C}${e}`),r=oa(t);n.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${i} messageRemindType:${r}`),_a.patchMessageRemindType(i,r)}})}setMessageRemindType(e){return _e(this,void 0,void 0,function*(){const t="setMessageRemindType",{groupID:s,userIDList:n,messageRemindType:o}=e,{helper:i,utils:{isUndefined:r},ssoLog:a}=this._core;try{if(!r(s))return a.debug(`${this._name}.${t} groupID:${s} messageRemindType:${o}`),yield Ma.set(s,o);if(!r(n))return a.debug(`${this._name}.${t} userIDList:${n} messageRemindType:${o}`),yield Sa.set(n,o);throw new i.ChatError({functionName:t,message:"userIDList or groupID is required"})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},Ra=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,ma.init(e),fa.init(e),va.init(e),Ia.init(e),Ea.init(e),Ca.init(e),ya.init(e),Ta.init(e);const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:n}}=this._core,{InnerEventSubType:{CONV_MODIFIED:o,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:r,C2C_REMIND_TYPE_SYNC:a}}=t;t.subscribeInnerEvent(s,o,this._onConversationModified,this),t.subscribeInnerEvent(s,i,this._onC2CMessageReadSync,this),t.subscribeInnerEvent(s,a,this._onC2CMessageRemindTypeSync,this),t.subscribeInnerEvent(s,r,this._onGroupMessageReadSync,this),t.subscribeInnerEvent(n,this._dispose,this)}_onConversationModified(e){const{constants:{ConvModifyPushType:t}}=this._core,{RecentContactMod:s=[]}=e;s.forEach(e=>{const{PushType:s}=e;if(s===t.CONV_DELETED){const{RecentContactList:t}=e.RecentContactDeleteItem;Ca.handleConversationDeleted(t)}if(s===t.CONV_PINED){const{RecentContactList:t}=e.RecentContactTopItem;Ea.handleConversationPinned(t,!0)}if(s===t.CONV_UNPINED){const{RecentContactList:t}=e.RecentContactTopItem;Ea.handleConversationPinned(t,!1)}})}_onC2CMessageReadSync(e){const{C2cNotifyMsgArray:t=[]}=e;Ia.handleC2CMessageReadSync(t)}_onC2CMessageRemindTypeSync(e){const{C2cNotifyMsgArray:t=[]}=e;Ta.handleC2CMessageRemindTypeSync(t)}_onGroupMessageReadSync(e){const{GroupTips:t=[]}=e;Ia.handleGroupMessageReadSync(t)}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:o,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:r}}=e;e.unSubscribeInnerEvent(t,n,this._onConversationModified,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,r,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Aa=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(e){return _e(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:t}}=this._core,{messageRemindType:s=t,isRepeated:n=!0}=e,{startTime:o=0,endTime:i=0}=this._calcStartAndEndTime(e),r=yield function(e){return _e(this,void 0,void 0,function*(){const{common:t}=Zr.core,{startTime:s,endTime:n,isRepeated:o,messageRemindType:i}=e,r={StartTime:s,EndTime:n,IsRepeated:o,Level:i};return t.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:r})})}({messageRemindType:this._getType(s),startTime:o,endTime:i,isRepeated:n?ca.ON:ca.OFF});return{code:0,data:{errorCode:r.ErrorCode,errorInfo:r.ErrorInfo}}}catch(e){ra("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){const{startHour:t=0,startMinute:s=0,startSecond:n=0,duration:o=0,isRepeated:i=!0}=e,r=new Date,a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),t,s,n),c=Math.round(a.getTime()/1e3);let u=c+o;return i&&o>=86400&&(u=c+86400),{startTime:c,endTime:u}}_getType(e){const{OuterConstant:t}=this._core;return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}},Oa=new class{init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:n}=e;t.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),s.subscribeInnerEvent(n.MESSAGE_PUSH,s.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){const t=this._handleResult(e),{notificationCenter:s,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:n}}=this._core;s.emitOuterEvent(n,{name:n,data:t})}getAllReceiveMessageOpt(){return _e(this,void 0,void 0,function*(){try{const e=yield function(){return _e(this,void 0,void 0,function*(){const{common:e}=Zr.core,t={To_Account:e.getCurrentUserID()};return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:t})})}();return{code:0,data:this._handleResult(e)}}catch(e){ra("getAllReceiveMessageOpt",e)}})}_handleResult(e){const{OuterConstant:t}=this._core,{MSG_REMIND_ACPT_AND_NOTE:s,MSG_REMIND_DISCARD:n,MSG_REMIND_ACPT_NOT_NOTE:o}=t,i={0:s,1:n,2:o},{Level:r,StartTime:a,EndTime:c,IsRepeated:u}=e;return{messageRemindType:i[r]||s,startTime:a,endTime:c,isRepeated:u===ca.ON}}},Da=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,Sa.init(e),Ma.init(e),pa.init(e),ga.init(e),Aa.init(e),Oa.init(e)}};const ba=e=>!ea(e)&&!ta(e)&&!sa(e),La={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ba(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ba(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ba(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{const{core:{utils:{isArray:t,isObject:s,isString:n}}}=Zr;if(!n(e)&&!s(e))return"options is String or Object.";if(n(e)&&ba(e))return"conversationID is invalid.";if(s(e)){if(!t(e.conversationIDList))return"conversationIDList is not Array.";if(0===e.conversationIDList.length)return"conversationIDList is empty.";if(e.conversationIDList.some(e=>{if(ba(e))return!0}))return"conversationIDList includes invalid conversationID.";if(e.clearHistoryMessage&&"boolean"!=typeof e.clearHistoryMessage)return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!ea(e)&&!ta(e))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Na={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var wa=new class{constructor(){this.name="Conversation"}install(e){Zr.init(e),Ra.init(e),Da.init(e),_a.init(e),e.helper.registerValidateConfig({auth:Na,params:La})}};const Pa=new class{init(e){this.core=e}},Ga="AVChatRoom",Ua="AV_HISTORY_MSG",ka="GRP_COUNTER",Fa="Set",xa="Increase",Va="Decrease",$a=0,qa=1,Ba=2,ja=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Ha=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ka=["Role","JoinTime","MsgFlag","MsgSeq"],Wa=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Ya=0,za=1,Ja="notStart",Qa="resolved",Xa="rejected",Za=10018,ec=11e3,tc=2,sc=["Owner","Admin","Member"],nc=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],oc=0,ic=1,rc=2,ac=4,cc=1,uc=2,lc=3,dc=4,hc=5,pc=1,gc=0,_c=4,mc=6,fc=400,vc=300,Ic={from:!0,groupID:!0,groupName:!0,to:!0},Ec={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Cc=2,yc=4,Sc=5,Mc=7,Tc=8,Rc=15,Ac=20,Oc=21,Dc=2600,bc=2602,Lc=2603,Nc=2620,wc=2621,Pc=2623,Gc=2660,Uc=2661,kc=2681,Fc=2683,xc=2684,Vc=2685,$c=2687,qc=3122,Bc=10018,jc={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},Hc=e=>e===Pa.core.OuterConstant.GRP_PUBLIC,Kc=e=>e===Pa.core.OuterConstant.GRP_AVCHATROOM,Wc=(e,t)=>{const{isArray:s}=Pa.core.utils;if(!s(e)||!s(t))return!1;let n=!1;return t.forEach(({key:t,value:s})=>{const o=e.find(e=>e.key===t);o?o.value!==s&&(o.value=s,n=!0):(e.push({key:t,value:s}),n=!0)}),n},Yc=e=>{const t=[];if(!e)return t;for(let s=0,n=e.length;s<n;s++){const{Key:n,Value:o}=e[s];t.push({key:n,value:o})}return t},zc=e=>{const t=[];for(let s=0,n=e.length;s<n;s++){const{key:n,value:o}=e[s];t.push({Key:n,Value:o})}return t};function Jc(e,t){const{helper:s}=Pa.core;if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:qc,replacement1:e})}function Qc(e,t){const{helper:s}=Pa.core,n=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(`${e} fail:`,n),n}const Xc=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Zc{constructor(e){this.groupID="",this.name="",this.avatar="",this.type="",this.introduction="",this.notification="",this.ownerID="",this.createTime=0,this.selfInfo={messageRemindType:"",joinTime:"",nameCard:"",role:"",userID:"",memberCustomField:void 0,readedSequence:0,excludedUnreadSequenceList:void 0},this.lastMessage={lastTime:0,lastSequence:0,fromAccount:"",messageForShow:""},this.nextMessageSeq=0,this.memberCount=0,this.maxMemberCount=0,this.joinOption="",this.inviteOption="",this.groupCustomField=[],this.muteAllMembers=!1,this.isSupportTopic=!1,this._lastRevokedTime=0,this._groupAtInfoList=[],this._initGroup(e)}_initGroup(e){const{utils:{isString:t}}=Pa.core;for(const s in e)Xc.indexOf(s)<0||("selfInfo"!==s?"isSupportTopic"!==s?"muteAllMembers"===s&&t(e[s])?this.muteAllMembers="On"===e[s]:this[s]=e[s]:this.isSupportTopic=1===e[s]:this.updateSelfInfo(e[s]))}updateGroup(e){const{utils:{isArray:t,isUndefined:s,isNumber:n,isString:o},common:{deepMerge:i}}=Pa.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);const r=JSON.parse(JSON.stringify(e));r.lastMsgTime&&(this.lastMessage.lastTime=r.lastMsgTime),o(r.muteAllMembers)&&(r.muteAllMembers="On"===r.muteAllMembers),r.groupCustomField&&Wc(this.groupCustomField,r.groupCustomField),s(r.isSupportTopic)||(this.isSupportTopic=n(r.isSupportTopic)?1===r.isSupportTopic:r.isSupportTopic),i(this,r,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(r.members)&&r.members.length>0&&r.members.forEach(e=>{e.userID===this.selfInfo.userID&&i(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){const{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r}=e,{common:{deepMerge:a}}=Pa.core;a(this.selfInfo,{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var eu=new class{constructor(){this._name="GroupDataHandler"}init(e){this._core=e;const{appStore:{groupStore:t}}=e;this._groupMap=t.getGroupMap()}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){const{common:{getCurrentUserID:t}}=this._core;let s;e.forEach(e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null===(t=this.getLocalGroup(s))||void 0===t||t.updateGroup(e):this._groupMap.set(s,new Zc(e))});const n=t();for(const[,e]of this._groupMap)e.selfInfo.userID=n,"Owner"===e.selfInfo.role&&(e.ownerID=n)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:e,GRP_LIVE:t}}=this._core;return[...this._groupMap.values()].filter(s=>{const{type:n}=s;return n!==e&&n!==t})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,n=`${s}${e}`,o=t.getConversation(n);if(o){const s=this.getLocalGroup(e);o.setProfileCompleted(),t.updateConversation(n,{groupProfile:s})}}reset(){this.clearLocalGroup()}};function tu(e,t){return _e(this,void 0,void 0,function*(){const{type:s,limit:n,offset:o,supportTopic:i=0,memberAccount:r,responseFilter:a}=e,c={Type:s,Limit:n,Offset:o,Member_Account:r,ResponseFilter:a,SupportTopic:i,NeedAppDefineData:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:c})})}const su=function(e,t){return{code:0,data:e||{},successLog:t}};var nu=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Ja,this.PAGING_GRP_COUNT_LIMIT=200}init(e){this._core=e;const{helper:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=e;t.registerApi({apiName:"getGroupList",context:this}),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,n.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return _e(this,arguments,void 0,function*(e=!1){if(e){const e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),eu.updateLocalGroup(e),eu.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Xa||this._pagingStatus===Ja)return this._syncGroupList().then(()=>{const e=eu.getLocalGroupList();return su({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e});const t=eu.getLocalGroupList();return su({groupList:t,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${t.length}`})})}_syncGroupList(){return _e(this,void 0,void 0,function*(){this._pagingStatus===Ja&&eu.clearLocalGroup();const e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Qa,this._groupListTreeShaking(t),eu.updateLocalGroup(t);const s=eu.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${s.length}`),eu.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Xa,e}})}_pagingGetGroupList(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t}=this._core,{isCommunityRelay:s=!1,groupList:n}=e;let o,{limit:i,offset:r}=e;const a=[...ja];s&&(o=this._core.OuterConstant.GRP_COMMUNITY,a.push("AtInfoList"));try{const e=yield tu({type:o,limit:i,offset:r,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:a,SelfInfoFilter:[...Ka]}},this._core),{GroupIdList:c=[],TotalCount:u=0}=e||{},l=this._convertGroupKey(c);n.push(...l);const d=r+i,h=!(u>d),p=`offset:${r} limit:${i} total:${u} isCompleted:${h} current:${n.length} isCommunityRelay:${s}`;return t.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${p}`),s?h?n:(r=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:i,offset:r,groupList:n})):h?(t.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),r=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:i,offset:r,groupList:n})):(r=d,this._pagingGetGroupList({limit:i,offset:r,groupList:n}))}catch(e){if(e.ErrorCode===Za)return t.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${i}`),i=50,this._pagingGetGroupList({isCommunityRelay:s,limit:i,offset:r,groupList:n});if(s)return e.code===ec&&t.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),n;throw e}})}_pagingGetJoinedCommunityList(e){return _e(this,void 0,void 0,function*(){const{common:{getCurrentUserID:t},OuterConstant:s,ssoLog:n}=this._core,{groupList:o}=e;let{limit:i,offset:r}=e;try{const e=yield tu({limit:i,offset:r,type:s.GRP_COMMUNITY,memberAccount:t(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ja],SelfInfoFilter:[...Ka]}},this._core),{GroupIdList:a=[],TotalCount:c=0}=e||{},u=this._convertGroupKey(a);o.push(...u);const l=r+i,d=!(c>l),h=`offset:${r} limit:${i} total:${c} isCompleted:${d} current:${o.length}`;return n.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${h}`),d?o:(r=l,this._pagingGetJoinedCommunityList({limit:i,offset:r,groupList:o}))}catch(e){if(e.code===Bc)return n.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${i}`),i=50,this._pagingGetJoinedCommunityList({limit:i,offset:r,groupList:o});throw e}})}_groupListTreeShaking(e){const t=new Map([...eu.getLocalGroupList()]);for(let s=0,n=e.length;s<n;s++)t.delete(e[s].groupID);const s=[...t.keys()];for(let e=0,t=s.length;e<t;e++)eu.deleteLocalGroup(s[e])}_isSyncCompleted(){return this._pagingStatus===Qa}_convertGroupKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,Introduction:c,InviteJoinOption:u,LastInfoTime:l,LastMsgTime:d,MemberNum:h,MaxMemberNum:p,MuteAllMember:g,Name:_,NextMsgSeq:m,Notification:f,Owner_Account:v,Type:I,LastRecallTime:E,SelfInfo:C,AtInfoList:y=[],SupportTopic:S}=e[s],M=Yc(n),T=this._convertSelfInfo(C),R=this._convertAtInfoList(a,y);t.push({groupCustomField:M,joinOption:o,createTime:i,avatar:r,groupID:a,introduction:c,inviteOption:u,lastInfoTime:l,lastMsgTime:d,memberCount:h,maxMemberCount:p,muteAllMembers:g,name:_,nextMessageSeq:m,notification:f,ownerID:v,type:I,selfInfo:T,_lastRevokedTime:E,_groupAtInfoList:R,isSupportTopic:S})}return t}_convertSelfInfo(e){const{JoinTime:t,MsgFlag:s,MsgSeq:n,NoUnreadSeqList:o,Role:i}=e;return{joinTime:t,messageRemindType:s,readedSequence:n,excludedUnreadSequenceList:o,role:i}}_convertAtInfoList(e,t){if(0===t.length)return[];const s=[];return t.forEach(t=>{const{AtFlagList:n,AtMsgSeq:o,From_Account:i}=t;s.push({groupID:e,groupAtType:n,sequence:o,from:i})}),s}},ou=new class{constructor(){this._name="CreateGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"createGroup",context:this})}createGroup(e){return _e(this,void 0,void 0,function*(){var t;this._preCheckParams(e);const{helper:{ChatError:s}}=this._core;try{const{utils:{isEmpty:s},common:{getCurrentUserID:n},OuterConstant:{GRP_AVCHATROOM:o}}=this._core,i=yield function(e,t){return _e(this,void 0,void 0,function*(){const{name:s,type:n,groupID:o,introduction:i,notification:r,avatar:a,maxMemberNum:c,joinOption:u,inviteOption:l,memberList:d,groupCustomField:h,isSupportTopic:p}=e;let g,_;d&&(g=d.map(e=>{const{userID:t,memberCustomField:s}=e;return{Member_Account:t,AppMemberDefinedData:s?zc(s):void 0}})),h&&(_=zc(h));const m={Name:s,Type:n,GroupId:o,Introduction:i,Notification:r,FaceUrl:a,MaxMemberCount:c,ApplyJoinOption:u,InviteJoinOption:l,MemberList:g,AppDefinedData:_,SupportTopic:p,webPushFlag:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:m})})}(Object.assign(Object.assign({},e),{ownerID:n()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:a=[]}=i||{},c=`${this._name}.createGroup ok, type:${e.type} groupID:${r} overLimitUserIDList:${a}`;if(s(e.memberList)||s(a)||(e.memberList=null===(t=e.memberList)||void 0===t?void 0:t.filter(e=>a.includes(e.userID))),e.type===o)return su({group:new Zc(Object.assign(Object.assign({},e),{groupID:r}))},{message:c});eu.updateLocalGroup([Object.assign(Object.assign({},e),{groupID:r})]);const u=eu.getLocalGroup(r);return this._notNeedSendCustomMessage(e)||(this._sendCustomMessage(r,e.type),eu.emitGroupListUpdate()),su({group:u},{message:c})}catch(t){const{errorCode:n,errorInfo:o}=t;throw new s({functionName:"createGroup",code:n,message:o,moreMessage:` groupID:${e.groupID}`})}})}_preCheckParams(e){const{type:t,groupID:s}=e,{utils:{isEmpty:n,isUndefined:o},common:{isCommunity:i}}=this._core,r=!n(s);if(!(()=>{const{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:n,GRP_COMMUNITY:o}=Pa.core.OuterConstant;return[e,t,s,n,o]})().includes(t))throw new this._core.helper.ChatError({code:Dc});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:bc});o(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||o(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||o(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:bc});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Kc(e)}_canIUseJoinOption(e){return Hc(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){const{isSupportTopic:t}=e;return!0===t}_notNeedSendCustomMessage(e){const{type:t,isSupportTopic:s}=e,{OuterConstant:{GRP_AVCHATROOM:n,GRP_COMMUNITY:o}}=this._core;return t===n||t===o&&1===s}_sendCustomMessage(e,t){var s,n,o,i,r,a;const{OuterConstant:c,common:{t:u}}=this._core;let l=u("CREATE_GROUP"),d=Ya;t===c.GRP_COMMUNITY&&(l=u("CREATE_COMMUNITY"),d=za);const h={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:l,cmd:d,opUser:this._core.store.get("login").userId,version:4})}},p=null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.createCustomMessage(h);null===(a=null===(r=null===(i=this._core)||void 0===i?void 0:i.message)||void 0===r?void 0:r.messageSender)||void 0===a||a.sendMessage(p,{})}},iu=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){const{elements:{newGroupProfile:t}}=e,{utils:{isEmpty:s,isUndefined:n}}=this._core;return!n(t)&&!s(t.groupAttributeOption)}handleGroupAttributesUpdated(e){const{groupID:t,groupAttributeOption:s}=e,{serverMainSequence:n,groupAttributeList:o=[],operation:i}=s;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${t} operation:${i}`);const{utils:{isUndefined:r}}=this._core;r(i)||(this.refreshGroupAttributesCache({groupID:t,serverMainSequence:n,groupAttributeList:o,operation:i}),this.emitGroupAttributesUpdated(t))}initGroupAttributesCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupAttributesCache.set(t,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:s,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${t} avChatRoomKey:${s}`)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){const{groupID:t,serverMainSequence:s,groupAttributeList:n,operation:o}=e;if(this.hasGroupAttributesCache(t)){const e=this.getGroupAttributesCache(t),{localMainSequence:i}=e;o!==hc&&s-i!==1||(e.serverMainSequence=s,e.localMainSequence=s,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:o})),s-i>1&&(e.serverMainSequence=s),this._groupAttributesCache.set(t,e),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${o} localMainSequence:${i} serverMainSequence:${s}`)}}_updateGroupAttributesCacheValues(e){const{groupAttributes:t,groupAttributeList:s=[],operation:n}=e;n!==lc?n!==dc?(n===cc&&t.values.clear(),s.forEach(e=>{const{key:s,value:n,sequence:o}=e;t.values.set(s,{value:n,sequence:o})})):s.forEach(e=>{t.values.delete(e.key)}):t.values.clear()}getGroupAttributesCacheValues(e){var t;const{groupID:s,keyList:n=[]}=e,o={};if(this.hasGroupAttributesCache(s)){const{values:e}=this.getGroupAttributesCache(s);if(0===n.length){for(const s of e.keys())o[s]=(null===(t=e.get(s))||void 0===t?void 0:t.value)||"";return o}return n.forEach(t=>{var s;e.has(t)&&(o[t]=(null===(s=e.get(t))||void 0===s?void 0:s.value)||"")}),o}return o}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s;const{OuterConstant:{GRP_ROOM:n,GRP_LIVE:o}}=this._core,i=this.getGroupAttributesCacheValues({groupID:e}),r=this._core.appStore.groupStore.getGroup(e),{updatedKeyList:a,deletedKeyList:c}=this._computeValuesChangedData(i);0===a.length&&0===c.length||([n,o].includes(r.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${a.length}, delete count:${c.length}`),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:e,richStatus:i,updatedKeyList:a,deletedKeyList:c}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${a.length}, delete count:${c.length}`),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:i,updatedKeyList:a,deletedKeyList:c}})))}_computeValuesChangedData(e){const{utils:{isUndefined:t}}=this._core,s=[],n=[];return Object.keys(e).forEach(t=>{e[t]!==this._groupAttributesCacheValuesCopy[t]&&s.push(t)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(s=>{t(e[s])&&n.push(s)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:s,deletedKeyList:n}}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(e){const t=[];return Object.keys(e).forEach(s=>{t.push({key:s,value:e[s]})}),t}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},ru=new class{constructor(){this._name="DismissGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ga)})}dismissGroup(e){return _e(this,void 0,void 0,function*(){const{helper:{ChatError:t}}=this._core;try{yield function(e,t){return _e(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:s})})}(e,this._core);const{type:t}=eu.getLocalGroup(e);return eu.deleteLocalGroup(e),eu.emitGroupListUpdate(),iu.deleteGroupAttributesCache(e),su({groupID:e,type:t},{message:e})}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t({functionName:"dismissGroup",code:s,message:n})}})}},au=new class{constructor(){this._name="GetGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(e){return _e(this,void 0,void 0,function*(){const{groupID:t,groupCustomFieldFilter:s}=e,n={groupIDList:[t],responseFilter:{GroupBaseInfoFilter:[...ja],AppDefinedDataFilter_Group:s,MemberInfoFilter:[...Wa]}},{helper:{ChatError:o}}=this._core;try{const e=yield this.getGroupProfileAdvance(n),{successGroupList:s,failureGroupList:o}=e;if(o.length>0)throw o[0];let i;return!eu.hasLocalGroup(t)&&Kc(s[0].type)?i=new Zc(s[0]):(eu.updateLocalGroup(s),i=eu.getLocalGroup(t)),i.isSupportTopic||eu.updateConversationGroupProfile(t),su({group:i},{message:`groupID:${t}`})}catch(e){const{code:t,message:s}=e;throw new o({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(e){return _e(this,void 0,void 0,function*(){const{groupIDList:t}=e,{common:{isCommunity:s}}=this._core,n=t.filter(e=>!s({groupID:e})),o=t.filter(e=>s({groupID:e}));n.length>50&&(n.length=50),o.length>50&&(o.length=50);const i=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:n})),this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:o,isCommunityProfile:!0}))]),r=[],a=[];return i.forEach(e=>{r.push(...e.successGroupList),a.push(...e.failureGroupList)}),{successGroupList:r,failureGroupList:a}})}_getGroupProfileAdvance(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t,utils:{isUndefined:s}}=this._core,{isCommunityProfile:n=!1}=e,o=ge(e,["isCommunityProfile"]);if(0===o.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupIDList:s,responseFilter:n}=e,o={GroupIdList:s,ResponseFilter:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:o})})}(o,this._core),{GroupInfo:n=[]}=e||{},i=this._convertGroupProfileKey(n),r=i.filter(e=>s(e.errorCode)||0===e.errorCode),a=i.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return t.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${o.groupIDList.join(",")}`),{successGroupList:r,failureGroupList:a}}catch(e){if(n)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,InfoSeq:c,Introduction:u,InviteJoinOption:l,LastInfoTime:d,LastMsgTime:h,MaxMemberNum:p,MemberNum:g,MuteAllMember:_,Name:m,NextMsgSeq:f,Notification:v,Owner_Account:I,ShutUpAllMember:E,ShutUpUntil:C,Type:y,MemberList:S,ErrorCode:M,ErrorInfo:T}=e[s],R=Yc(n),A=this._convertMembers(S);t.push({groupCustomField:R,joinOption:o,createTime:i,avatar:r,groupID:a,infoSequence:c,introduction:u,inviteOption:l,lastInfoTime:d,lastMsgTime:h,maxMemberCount:p,memberCount:g,muteAllMembers:_,name:m,nextMessageSeq:f,notification:v,ownerID:I,shutUpAllMember:E,muteUntil:C,type:y,members:A,errorCode:M,errorInfo:T})}return t}_convertMembers(e){if(!e)return[];const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,MsgFlag:r,MsgSeq:a,NameCard:c,Role:u}=e[s],l=Yc(n);t.push({memberCustomField:l,joinTime:o,userID:i,messageRemindType:r,sequence:a,nameCard:c,role:u})}return t}},cu=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:o,groupCounterSeq:i}=this.getLocalGroupCounters(t);if(n>0&&n<i)return;s.forEach(t=>{const{Key:s,Value:n=0}=t;e.set(s,n)}),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:e,avChatRoomKey:o})}}initGroupCountersCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupCountersMap.set(t,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:s})}getLocalCounters(e,t){const s={};if(!this._hasLocalGroupCounters(e))return s;const{counters:n}=this.getLocalGroupCounters(e);if(t.length>0)t.forEach(e=>{n.has(e)&&(s[e]=n.get(e))});else for(const e of n.keys())s[e]=n.get(e);return s}deleteLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:o}=this.getLocalGroupCounters(t);s.forEach(t=>{e.delete(t.key)}),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:e,avChatRoomKey:o})}}setGroupCounters(e,t){if(!this._hasLocalGroupCounters(e))return;const s=this.getLocalGroupCounters(e),{counters:n}=s;let o=!1;Object.entries(t).forEach(([e,t])=>{n.has(e)&&n.get(e)!==t&&(n.set(e,t),o=!0)}),o&&this._groupCountersMap.set(e,Object.assign(Object.assign({},s),{lastUpdateTime:Date.now(),counters:n}))}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},uu=new class{constructor(){this._name="JoinGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ga)})}joinGroup(e){return _e(this,void 0,void 0,function*(){const{groupID:t}=e,{helper:{ChatError:s},OuterConstant:n,ssoLog:o}=this._core;try{if(eu.hasLocalGroup(t))try{return yield au.getGroupProfile({groupID:t}),su({status:n.JOIN_STATUS_ALREADY_IN_GROUP,group:eu.getLocalGroup(t)},{message:`groupID:${t} joinedStatus:${n.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch(s){return o.warn("joinGroup",`${this._name}.joinGroup ${t} was unjoined, start to join!`),eu.deleteLocalGroup(t),yield this._applyJoinGroup(e)}return yield this._applyJoinGroup(e)}catch(e){const{errorCode:n,errorInfo:o}=e;throw new s({functionName:"joinGroup",code:n,message:o,moreMessage:`groupID:${t}`})}})}_applyJoinGroup(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:t,helper:s,ssoLog:n}=this._core,{groupID:o}=e,i=Object.assign({},e),r=s.checkBusinessCapabilityBits(Ua);r&&(i.historyMessageFlag=1);const a=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,applyMessage:n,historyMessageFlag:o}=e,i={GroupId:s,ApplyMsg:n,HugeGroupHistoryMsgFlag:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:i})})}(i,this._core),{Type:c,JoinedStatus:u,LongPollingKey:l,StartSeq:d,HugeGroupFlag:h,AVChatRoomKey:p,RspMsgList:g=[]}=a||{},_=`groupID:${o} joinedStatus:${u} longPollingKey:${l} startSeq:${d} avChatRoomFlag:${h} canGetAVChatRoomHistoryMsg:${r}, historyMessageCount:${g.length}`;n.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${_}`);let m=new Zc({groupID:o,type:c});if(u===t.JOIN_STATUS_WAIT_APPROVAL)return su({status:t.JOIN_STATUS_WAIT_APPROVAL,group:m});if(u===t.JOIN_STATUS_SUCCESS){try{m=(yield au.getGroupProfile({groupID:o})).data.group}catch(e){n.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${o}, errorCode:${null==e?void 0:e.code}`)}return this._handleJoinResult({group:m,avChatRoomFlag:h,longPollingKey:l,startSequence:d,avChatRoomKey:p,historyMessageList:g})}throw new this._core.helper.ChatError({code:Gc})})}_handleJoinResult(e){const{group:t,avChatRoomFlag:s,avChatRoomKey:n}=e;return 1===s?(iu.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:n}),cu.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:n}),su(e)):(eu.updateLocalGroup([t]),eu.emitGroupListUpdate(),su({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t},{message:`groupID:${t.groupID}`}))}},lu=new class{constructor(){this._name="QuitGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ga)})}quitGroup(e){return _e(this,void 0,void 0,function*(){if(!eu.hasLocalGroup(e))throw new this._core.helper.ChatError({code:Pc});const{helper:{ChatError:t}}=this._core;try{yield function(e,t){return _e(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:s})})}(e,this._core);const{type:t}=eu.getLocalGroup(e);return eu.deleteLocalGroup(e),eu.emitGroupListUpdate(),iu.deleteGroupAttributesCache(e),su({groupID:e,type:t},{message:`groupID:${e}`})}catch(s){const{errorCode:n,errorInfo:o}=s;throw new t({functionName:"quitGroup",code:n,message:o,moreMessage:`groupID:${e}`})}})}},du=new class{constructor(){this._name="SearchGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(e){return _e(this,void 0,void 0,function*(){try{const t=yield function(e,t){return _e(this,void 0,void 0,function*(){const s={GroupIdList:[e],GroupBasePublicInfoFilter:[...Ha]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:s})})}(e,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:n=[],ApplyJoinOption:o,CreateTime:i,FaceUrl:r,Introduction:a,InviteJoinOption:c,MaxMemberNum:u,MemberNum:l,Name:d,Owner_Account:h,Type:p,ErrorCode:g,ErrorInfo:_}=s[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:_});const m=Yc(n),f=new Zc({groupID:e,name:d,avatar:r,introduction:a,joinOption:o,inviteOption:c,maxMemberCount:u,memberCount:l,type:p,ownerID:h,createTime:i,groupCustomField:m});return su({group:f})}catch(e){const{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:t,message:s})}})}},hu=new class{constructor(){this._name="UpdateGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(e){return _e(this,void 0,void 0,function*(){const{groupID:t}=e,{utils:{isUndefined:s},ssoLog:n,helper:o}=this._core;let i=eu.getLocalGroup(t);if(i){const{type:o}=i;this._canIUseJoinOption(o)||s(e.joinOption)||(n.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${t} joinOption is unavailable for Work/Meeting/AVChatRoom`),e.joinOption=void 0)}s(e.muteAllMembers)||(e.muteAllMembers=!0===e.muteAllMembers?"On":"Off");try{return yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,name:n,avatar:o,introduction:i,notification:r,muteAllMembers:a,joinOption:c,inviteOption:u,groupCustomField:l}=e,d={GroupId:s,Name:n,FaceUrl:o,Introduction:i,Notification:r,ShutUpAllMember:a,ApplyJoinOption:c,InviteJoinOption:u,AppDefinedData:l?zc(l):void 0};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:d})})}(e,this._core),i?(i.updateGroup(e),eu.emitGroupListUpdate()):i=new Zc(e),su({group:i},{message:`groupID:${t}`})}catch(e){const{errorCode:s,errorInfo:n}=e;throw new o.ChatError({code:s,message:n,moreMessage:`groupID:${t}`})}})}_canIUseJoinOption(e){return Hc(e)||this._core.common.isCommunity({type:e})}},pu=new class{constructor(){this._name="ChangeGroupOwner"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(e){return _e(this,void 0,void 0,function*(){const t="changeGroupOwner",{groupID:s,newOwnerID:n}=e,o=eu.getLocalGroup(s),{helper:i,OuterConstant:r,common:{getCurrentUserID:a}}=this._core;if((null==o?void 0:o.type)===r.GRP_AVCHATROOM)throw new i.ChatError({functionName:t,code:Nc});if(n===a())throw new i.ChatError({functionName:t,code:wc});try{return yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,newOwnerID:n}=e,o={GroupId:s,NewOwner_Account:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:o})})}(e,this._core),o.ownerID=n,eu.emitGroupListUpdate(),su({group:o})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},gu=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ga)})}getGroupOnlineMemberCount(e){return _e(this,void 0,void 0,function*(){const t="getGroupOnlineMemberCount";if(!eu.hasLocalGroup(e))return su({memberCount:0});const s=Date.now();if(this._onlineMemberCountMap.has(e)){const t=this._onlineMemberCountMap.get(e),{lastReqTime:n=0,memberCount:o=0}=t||{};if(s-n<=6e4)return su({memberCount:o})}try{const s=yield function(e,t){return _e(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})})}(e,this._core),{OnlineMemberNum:n=0}=s||{};this._onlineMemberCountMap.set(e,{lastReqTime:Date.now(),memberCount:n});const o=`${this._name}.${t} ok. groupID:${e} memberCount:${n}`;return su({memberCount:n},{message:o})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},_u=new class{init(e,t){e.ssoLog.debug("GroupAction.init"),nu.init(e),ou.init(e),ru.init(e,t),uu.init(e,t),lu.init(e,t),du.init(e),au.init(e),hu.init(e),pu.init(e),gu.init(e,t)}dismissGroup(e){return ru.dismissGroup(e)}joinGroup(e){return uu.joinGroup(e)}quitGroup(e){return lu.quitGroup(e)}getGroupOnlineMemberCount(e){return gu.getGroupOnlineMemberCount(e)}},mu=new class{constructor(){this._name="GetGroupApplicationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return _e(this,void 0,void 0,function*(){const e="getGroupApplicationList";try{const t=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${e} ok.`);const s=this._handleGroupApplicationResult([...t[0],...t[1]]);return su({applicationList:s})}catch(t){throw new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo})}})}_getGroupApplicationList(e){return _e(this,void 0,void 0,function*(){const{type:t,startTime:s=0,limit:n=20}=e||{},{common:o}=this._core;let i;try{i=yield function(e,t){return _e(this,void 0,void 0,function*(){const{type:s,startTime:n,limit:o,handleAccount:i}=e,r={Type:s,StartTime:n,Limit:o,Handle_Account:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:r})})}({type:t,startTime:s,limit:n,handleAccount:o.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}const{NextStartTime:r=0,PendencyList:a=[]}=i||{};if(0===r)return a;const c=yield this._getGroupApplicationList(Object.assign(Object.assign({},e),{startTime:r}));return[...a,...c]})}_handleGroupApplicationResult(e){const t=[];return e.forEach(e=>{const s=this._convertApplicationData(e),{handled:n}=s,o=ge(s,["handled"]);0===n&&t.push(o)}),t}_convertApplicationData(e){const{Handled:t,AddTime:s,ApplyInviteMsg:n,Authentication:o,FromUserNickName:i,From_Account:r,GroupId:a,GroupName:c,PendencyType:u,To_Account:l}=e;return{handled:t,messageKey:s,applicant:r,applicantNick:i,groupID:a,groupName:c,authentication:o,applicationType:u,userID:l,note:n,addTime:s}}},fu=new class{constructor(){this._name="HandleGroupApplication"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return _e(this,void 0,void 0,function*(){const{application:t}=e,s=this._handleParams(e);try{(null==t?void 0:t.applicationType)===tc?yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,invitee:a}=e,c={GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,Invited_Account:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:c})})}(s,this._core):yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,messageKey:a}=e,c={GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,MsgKey:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:c})})}(s,this._core);const e=eu.getLocalGroup(s.groupID);return su({group:e})}catch(e){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleParams(e){var t;const{handleAction:s,handleMessage:n,message:o,application:i}=e;let r,a,c,u,l;if(o){const{payload:e}=o||{};r=e.operatorID,a=null===(t=e.groupProfile)||void 0===t?void 0:t.groupID,c=e.authentication,u=e.messageKey}else r=(null==i?void 0:i.applicant)||"",a=(null==i?void 0:i.groupID)||"",c=(null==i?void 0:i.authentication)||"",u=(null==i?void 0:i.messageKey)||0;return(null==i?void 0:i.applicationType)===tc&&(l=i.userID),{handleAction:s,handleMessage:n,applicant:r,invitee:l,groupID:a,authentication:c,messageKey:u}}},vu=new class{init(e){e.ssoLog.debug("GroupApplication.init"),mu.init(e),fu.init(e)}};let Iu=class{constructor(e){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(e)}updateMember(e){const{core:{utils:{isUndefined:t},common:{deepMerge:s}}}=Pa;t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus);const n=[null,void 0,"",0,NaN];e.memberCustomField&&Wc(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],n)}};function Eu(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,userID:n,muteTime:o,role:i,nameCard:r,memberCustomField:a}=e;let c;a&&(c=zc(a));const u={GroupId:s,Member_Account:n,ShutUpTime:o,Role:i,NameCard:r,AppMemberDefinedData:c};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:u})})}var Cu=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ga)})}getGroupMemberList(e){return _e(this,void 0,void 0,function*(){const t="getGroupMemberList",{groupID:s,offset:n=0,count:o=100,role:i="",filter:r=""}=e,a=eu.getLocalGroup(s),c=o>100?100:o,u={groupID:s,offset:n,limit:c,memberRoleFilter:sc.includes(i)?[i]:void 0,memberInfoFilter:nc};try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{isCommunity:s}=t.common,{groupID:n,offset:o,limit:i,memberRoleFilter:r,memberInfoFilter:a}=e,c={GroupId:n,Limit:i,MemberRoleFilter:r,MemberInfoFilter:a};return s({groupID:n})?c.Next=String(o):c.Offset=o,t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:c})})}(u,this._core),{MemberList:o,MemberNum:i,Next:r}=e||{},l=`${this._name}.${t} ok, totalMemberCount:${i} next:${r}`,{utils:{isArray:d,isEmpty:h},common:{isCommunity:p}}=this._core;if(a&&(a.memberCount=i),!d(o)||0===o.length)return su({memberList:[],offset:0},{message:l});let g=n+c;p({groupID:s})&&(g=h(r)?0:r),o.length<c&&(g=0);let _=this._convertMemberInfo(o);_=yield this._patchAvatarAndNick(_);const m=this._generateGroupMember(_);return su({memberList:m,offset:g},{message:l})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c,NameCard:u}=e[s],l=Yc(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:l,nameCard:u})}return t}_patchAvatarAndNick(e){return _e(this,void 0,void 0,function*(){var t;const s=e.map(e=>e.userID),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.map(e=>[e.userID,e]));return e.forEach(e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}}),e})}_generateGroupMember(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=new Iu(e[s]);t.push(n)}return t}},yu=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(e){return _e(this,void 0,void 0,function*(){const t="getGroupMemberProfile",{groupID:s,userIDList:n,memberCustomFieldFilter:o}=e,i=eu.getLocalGroup(s),{helper:r,utils:{isArray:a},ssoLog:c}=this._core;if(i&&Kc(i.type))throw new r.ChatError({functionName:t,replacement1:t,code:$c});n.length>50&&(c.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${n.length} exceeds limit 50`),n.splice(50));const u=`userIDList length:${n.length} groupID:${s}`;try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,userIDList:n,memberInfoFilter:o,memberCustomFieldFilter:i}=e,r={GroupId:s,Member_List_Account:n,MemberInfoFilter:o,AppDefinedDataFilter_GroupMember:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:r})})}({groupID:s,userIDList:n,memberCustomFieldFilter:o,memberInfoFilter:[...nc]},this._core),{MemberList:t}=e||{};if(!a(t)||0===t.length)return su({memberList:[]});let i=this._convertMemberInfo(t);i=yield this._getMemberAvatarAndNick(i);const r=this._generateGroupMember(i);return su({memberList:r},{message:u})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:u})}})}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c,NameCard:u}=e[s],l=Yc(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:l,nameCard:u})}return t}_getMemberAvatarAndNick(e){return _e(this,void 0,void 0,function*(){var t;const s=e.map(e=>e.userID),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.map(e=>[e.userID,e]));return e.forEach(e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}}),e})}_generateGroupMember(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=new Iu(e[s]);t.push(n)}return t}},Su=new class{constructor(){this._name="AddGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(e){return _e(this,void 0,void 0,function*(){const t="addGroupMember",{groupID:s,userIDList:n}=e,o=eu.getLocalGroup(s),{helper:i}=this._core;if(o&&Kc(o.type))throw new i.ChatError({functionName:t,code:Uc});const r=n.map(e=>({Member_Account:e}));try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,userIDList:n}=e,o={GroupId:s,MemberList:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:o})})}({groupID:s,userIDList:r},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:n,successUserIDList:i,existedUserIDList:a,overLimitUserIDList:c}=this._handleResult(t);return su({failureUserIDList:n,successUserIDList:i,existedUserIDList:a,overLimitUserIDList:c,group:o},{message:` groupID:${s} successUserIDList:${i} failureUserIDList:${n} existedUserIDList:${a} overLimitUserIDList:${c}`})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){const t=[],s=[],n=[],o=[];return e.forEach(e=>{const{Result:i,Member_Account:r}=e;i===oc?t.push(r):i===ic?s.push(r):i===rc?n.push(r):i===ac&&o.push(r)}),{failureUserIDList:t,successUserIDList:s,existedUserIDList:n,overLimitUserIDList:o}}},Mu=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ga)})}deleteGroupMember(e){return _e(this,void 0,void 0,function*(){const t="deleteGroupMember",{groupID:s,userIDList:n}=e,o=eu.getLocalGroup(s),{helper:i,utils:{isUndefined:r},ssoLog:a}=this._core;if(r(o))throw new i.ChatError({functionName:t,code:Lc});n.length>20&&(a.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${n.length} exceeds limit 20`),n.splice(20));try{return yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,userIDList:n,reason:o}=e,i={GroupId:s,MemberToDel_Account:n,Reason:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:i})})}({groupID:s,userIDList:n},this._core),su({group:o,userIDList:n},{message:`groupID:${s} userIDList length:${n.length}`})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Tu=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(e){return _e(this,void 0,void 0,function*(){const{helper:t}=this._core,{groupID:s,userID:n,muteTime:o}=e,i=` groupID:${s} userID:${n} muteTime:${o}`;this._preCheckSettingMuteParams(e);try{yield Eu(e,this._core);const t=eu.getLocalGroup(s),r=new Iu({userID:n,muteTime:o});return su({group:t,member:r},{message:i})}catch(e){throw new t.ChatError({functionName:"setGroupMemberMuteTime",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:i})}})}_preCheckSettingMuteParams(e){const{userID:t}=e,{store:s,helper:n}=this._core;if(t===s.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:Vc})}},Ru=new class{constructor(){this._name="SetGroupMemberRole"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(e){return _e(this,void 0,void 0,function*(){const t="setGroupMemberRole",{helper:s}=this._core,{groupID:n,userID:o,role:i}=e,r=`${this._name}.${t} ok, groupID:${n} userID:${o} role:${i}`;this._preCheckSettingRoleParams(e);try{yield Eu(e,this._core);const t=eu.getLocalGroup(n),s=new Iu({userID:o,role:i});return su({group:t,member:s},{message:r})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:r})}})}_preCheckSettingRoleParams(e){var t;const{groupID:s,userID:n,role:o}=e,{store:i,helper:r,OuterConstant:a,common:{isCommunity:c}}=this._core,u=eu.getLocalGroup(s);if((null===(t=null==u?void 0:u.selfInfo)||void 0===t?void 0:t.role)!==a.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:kc});if(n===i.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:xc});const l=[...sc];if(c({groupID:s})&&l.push(a.GRP_MBR_ROLE_CUSTOM),!l.includes(o))throw new r.ChatError({functionName:"setGroupMemberRole",code:Fc})}},Au=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(e){return _e(this,void 0,void 0,function*(){var t;const s="setGroupMemberNameCard",{helper:n,common:{getCurrentUserID:o}}=this._core,{groupID:i,userID:r=o(),nameCard:a}=e,c=`${this._name}.${s} ok, groupID:${i} userID:${r} nameCard:${a}`;this._preCheckSettingNameCardParams(e);try{const e={groupID:i,userID:r,nameCard:a};yield Eu(e,this._core);const s=eu.getLocalGroup(i);r===(null===(t=null==s?void 0:s.selfInfo)||void 0===t?void 0:t.userID)&&(s.updateSelfInfo({nameCard:a}),eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(i));const n=new Iu({userID:r,nameCard:a});return su({group:s,member:n},{message:c})}catch(e){throw new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:c})}})}_preCheckSettingNameCardParams(e){const{groupID:t}=e,{helper:s}=this._core,n=eu.getLocalGroup(t);if(Kc(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberNameCard",code:$c})}},Ou=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(e){return _e(this,void 0,void 0,function*(){const t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingCustomFiledParams(e);const{groupID:o,userID:i=n(),memberCustomField:r}=e,a=`${this._name}.${t} ok, groupID:${o}userID:${i} memberCustomField:${JSON.stringify(r)}`;try{const e={groupID:o,userID:i,memberCustomField:r};yield Eu(e,this._core);const t=eu.getLocalGroup(o),s=new Iu({userID:i,memberCustomField:r});return su({group:t,member:s},{message:a})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:a})}})}_preCheckSettingCustomFiledParams(e){const{groupID:t}=e,{helper:s}=this._core,n=eu.getLocalGroup(t);if(Kc(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberCustomField",code:$c})}},Du=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),Cu.init(e,t),yu.init(e),Su.init(e),Mu.init(e,t),Tu.init(e),Ru.init(e),Au.init(e),Ou.init(e)}getGroupMemberList(e){return Cu.getGroupMemberList(e)}deleteGroupMember(e){return Mu.deleteGroupMember(e)}},bu=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(e){return _e(this,void 0,void 0,function*(){const t="getGroupCounters";try{Jc(t,ka);const{groupID:s,keyList:n=[]}=e,{avChatRoomKey:o,lastUpdateTime:i}=cu.getLocalGroupCounters(s);if(!(Date.now()-i>=this._getExpireTime()))return{code:0,data:{counters:cu.getLocalCounters(s,n)}};const r=yield function(e){return _e(this,void 0,void 0,function*(){const{groupID:t,GroupCounterKeys:s,avChatRoomKey:n}=e,{common:o}=Pa.core,i={GroupId:t,keyList:s,BytesKey:n};return o.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:i})})}({groupID:s,keyList:n,avChatRoomKey:o}),{GroupCounter:a=[],GroupCounterSeq:c}=r;return cu.updateLocalGroupCounters({groupID:s,counterList:a,groupCounterSeq:c}),{code:0,data:{counters:cu.getLocalCounters(s,n)}}}catch(e){Qc(t,e)}})}_getExpireTime(){const{store:e,utils:{isUndefined:t}}=this._core,s=e.get("cloudConfig")||{},{grp_counter_expire_time:n}=s;return t(n)?3e4:Number(n)}},Lu=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"setGroupCounters",context:this}),t.registerApi({apiName:"increaseGroupCounter",context:this}),t.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return _e(this,void 0,void 0,function*(){return this._handleCounterOperation(Fa,e)})}increaseGroupCounter(e){return _e(this,void 0,void 0,function*(){return this._handleCounterOperation(xa,e)})}decreaseGroupCounter(e){return _e(this,void 0,void 0,function*(){return this._handleCounterOperation(Va,e)})}_handleCounterOperation(e,t){return _e(this,void 0,void 0,function*(){const s=`${e}GroupCounter`;try{Jc(s,ka);const{groupID:n,key:o,value:i=0}=t,{avChatRoomKey:r}=cu.getLocalGroupCounters(n),a=e===Fa?this._convertObjectToList(t.counters):[{Key:o,Value:i}],c=yield this._updateGroupCounters({groupID:n,counterList:a,avChatRoomKey:r,mode:e});return cu.setGroupCounters(n,c),{code:0,data:{counters:c}}}catch(e){Qc(s,e)}})}_updateGroupCounters(e){return _e(this,void 0,void 0,function*(){const t=yield function(e){const{groupID:t,counterList:s,mode:n,avChatRoomKey:o}=e,{common:i}=Pa.core,r={GroupId:t,GroupCounter:s,Mode:n,BytesKey:o};return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:r})}(e),{GroupCounter:s=[]}=t,n={};return s.forEach(e=>{const{Key:t,Value:s=0}=e;n[t]=s}),n})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},Nu=new class{init(e){this._core=e,bu.init(e),Lu.init(e)}isGroupCounterUpdated(e){const{elements:{groupCounterInfo:t}}=e,{utils:{isEmpty:s}}=this._core;return!s(t)}handleGroupCounterUpdated(e){const{to:t,elements:{groupCounterInfo:s}}=e;s.forEach(e=>{const{type:s,groupCounterSeq:n,counterList:o=[]}=e;s!==$a&&s!==Ba||this._processAndNotifyCounterUpdate(t,n,o),s===qa&&cu.deleteLocalGroupCounters({groupID:t,groupCounterSeq:n,counterList:o})})}_processAndNotifyCounterUpdate(e,t,s){const{OuterEvent:n,notificationCenter:o}=this._core;cu.updateLocalGroupCounters({groupID:e,groupCounterSeq:t,counterList:s}),s.forEach(({Key:t,Value:s=0})=>{o.emitOuterEvent(n.GROUP_COUNTER_UPDATED,{name:n.GROUP_COUNTER_UPDATED,data:{groupID:e,key:t,value:s}})})}reset(){cu.reset()}},wu=new class{constructor(){this._name="InitGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return _e(this,void 0,void 0,function*(){const{groupID:t,groupAttributes:s}=e,{serverMainSequence:n,avChatRoomKey:o}=iu.getGroupAttributesCache(t),i=iu.convertKeyValueMapToList(s);try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:r})})}({groupID:t,avChatRoomKey:o,groupAttributeList:i,mainSequence:n},this._core),{AttrMainSeq:r,GroupAttr:a}=e||{},c=a.map(e=>{const{Key:t,seq:n}=e;return{key:t,value:s[t],sequence:n}});return iu.saveGroupAttributesCacheValuesCopy(t),iu.refreshGroupAttributesCache({groupID:t,serverMainSequence:r,groupAttributeList:c,operation:cc}),iu.emitGroupAttributesUpdated(t),su({groupAttributes:s},{message:` groupID:${t} serverMainSequence:${r}`})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Pu=new class{constructor(){this._name="SetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupAttributes",context:this}),t.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(e){return _e(this,void 0,void 0,function*(){const{groupID:t,groupAttributes:s,richStatusMode:n}=e,{serverMainSequence:o,avChatRoomKey:i,values:r}=iu.getGroupAttributesCache(t),a=iu.convertKeyValueMapToList(s).map(e=>{var t;const{key:s,value:n}=e;return{key:s,value:n,seq:(null===(t=r.get(e.key))||void 0===t?void 0:t.sequence)||0}});try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i,richStatusMode:r}=e,a={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"],AllowRoomEngineOpt:r};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:a})})}({groupID:t,avChatRoomKey:i,groupAttributeList:a,mainSequence:o,richStatusMode:n},this._core),{AttrMainSeq:r,GroupAttr:c}=e||{},u=c.map(e=>{const{Key:t,seq:n}=e;return{key:t,value:s[t],sequence:n}});return iu.saveGroupAttributesCacheValuesCopy(t),iu.refreshGroupAttributesCache({groupID:t,serverMainSequence:r,groupAttributeList:u,operation:uc}),iu.emitGroupAttributesUpdated(t),su({groupAttributes:s},{message:` groupID:${t} serverMainSequence:${r}`})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}setRichStatus(e){return _e(this,void 0,void 0,function*(){const{groupID:t,richStatus:s}=e;return this.setGroupAttributes({groupID:t,groupAttributes:s,richStatusMode:!0})})}},Gu=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteGroupAttributes",context:this}),t.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(e){return _e(this,void 0,void 0,function*(){const t="deleteGroupAttributes",{groupID:s,keyList:n=[],richStatusMode:o}=e;try{let e;e=0===n.length?yield this._clearGroupAttributes(s,{richStatusMode:o}):yield this._deleteGroupAttributes(s,{keyList:n,richStatusMode:o});const{resultList:i,serverMainSequence:r,operation:a,groupAttributeList:c}=e||{},u=`${this._name}.${t} ok. groupID:${s} operation: ${a}`;return iu.saveGroupAttributesCacheValuesCopy(s),iu.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:c,operation:a}),iu.emitGroupAttributesUpdated(s),su({keyList:i},{message:u})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}deleteRichStatus(e){return _e(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},e),{richStatusMode:!0}))})}_deleteGroupAttributes(e,t){return _e(this,void 0,void 0,function*(){const{serverMainSequence:s,avChatRoomKey:n,values:o}=iu.getGroupAttributesCache(e),{keyList:i,richStatusMode:r}=t,a=[],c=[];i.forEach(e=>{if(o.has(e)){const{sequence:t=0}=o.get(e)||{};c.push({key:e,seq:t}),a.push(e)}});const u=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i,richStatusMode:r}=e,a={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"],AllowRoomEngineOpt:r};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:a})})}({groupID:e,avChatRoomKey:n,groupAttributeList:c,mainSequence:s,richStatusMode:r},this._core),{AttrMainSeq:l}=u||{};return{resultList:a,serverMainSequence:l,groupAttributeList:c,operation:dc}})}_clearGroupAttributes(e,t){return _e(this,void 0,void 0,function*(){const{serverMainSequence:s,avChatRoomKey:n,values:o}=iu.getGroupAttributesCache(e),{richStatusMode:i}=t||{},r=[...o.keys()],a=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,avChatRoomKey:o,richStatusMode:i}=e,r={GroupId:s,AttrMainSeq:n,BytesKey:o,AttrControl:["RaceConflict"],AllowRoomEngineOpt:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:r})})}({groupID:e,avChatRoomKey:n,mainSequence:s,richStatusMode:i},this._core),{AttrMainSeq:c}=a||{};return{resultList:r,serverMainSequence:c,operation:lc}})}},Uu=new class{constructor(){this._name="GetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupAttributes",context:this}),t.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(e){return _e(this,void 0,void 0,function*(){const{groupID:t}=e,{avChatRoomKey:s,lastUpdateTime:n,localMainSequence:o,serverMainSequence:i}=iu.getGroupAttributesCache(t),{helper:{ChatError:r}}=this._core,a=`groupID:${t} localMainSequence:${o} serverMainSequence:${i} keyList:${e.keyList}`;if(Date.now()-n>=3e4||o<i)try{const n=yield this.getGroupAttributesFromServer({groupID:t,avChatRoomKey:s}),o=iu.getGroupAttributesCacheValues(e),{serverGroupAttributeList:i=[]}=n||{};return su({groupAttributes:o},{message:a,moreMessage:`from server, count:${i.length}`})}catch(e){throw new r({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}const c=iu.getGroupAttributesCacheValues(e);return su({groupAttributes:c},{message:a,moreMessage:"from cache"})})}getGroupAttributesFromServer(e){return _e(this,void 0,void 0,function*(){const{utils:{isUndefined:t},ssoLog:s}=this._core,{groupID:n,avChatRoomKey:o}=e,i=t(o)?gc:pc,r=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,groupType:n,avChatRoomKey:o}=e,i={GroupId:s,GroupType:n,Key:o};return t.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:i})})}({groupID:n,avChatRoomKey:o,groupType:i},this._core),{AttrMainSeq:a=0,GroupAttrAry:c}=r||{};s.debug("getGroupAttributesFromServer",`${this._name}._getGroupAttributesFromServer ok. groupID:${n} serverMainSequence:${a}`);const u=c.map(e=>{const{key:t,value:s,seq:n}=e;return{key:t,value:s,sequence:n}});return iu.refreshGroupAttributesCache({groupID:n,serverMainSequence:a,groupAttributeList:u,operation:hc}),{serverGroupAttributeList:c}})}},ku=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),wu.init(e),Pu.init(e),Gu.init(e),Uu.init(e),iu.init(e)}isGroupAttributesUpdated(e){return iu.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){const{to:t,elements:{newGroupProfile:s}}=e,{groupAttributeOption:n}=s,{serverMainSequence:o,withChangedAttributeInfo:i}=n,{localMainSequence:r}=iu.getGroupAttributesCache(t),a=o-r;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:${a}`),0!==a)if(iu.saveGroupAttributesCacheValuesCopy(t),1!==i||1!==a){if(iu.hasGroupAttributesCache(t)){const{avChatRoomKey:e}=iu.getGroupAttributesCache(t);Uu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{iu.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else iu.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:n})}reset(){iu.reset()}};function Fu(e,t="tips"){const{ClientSeq:s,From_Account:n,MsgClientTime:o,MsgPriority:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,TinyId:u,ToGroupId:l,GroupInfo:d,MsgBody:h}=e,p=function(e){const{GroupCode:t,GroupId:s,GroupName:n,GroupType:o,MsgFrom_AccountExtraInfo:i,From_Account:r,To_Account:a}=e;return{groupCode:t,groupID:s,groupName:n,type:o,messageFromAccountExtraInformation:i,from:r,to:a}}(d);return{clientSequence:s,from:n,clientTime:o,priority:i,random:r,sequence:a,time:c,tinyID:u,to:l,groupProfile:p,elements:"tips"===t?xu(h):$u(h)}}function xu(e){const t={};return Object.keys(e).forEach(s=>{var n,o;switch(s){case"MemberNum":t.memberCount=e[s];break;case"OpType":t.operationType=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"List_Account":t.userIDList=e[s];break;case"MsgMemberExtraInfo":t.memberInfoList=null===(n=e[s])||void 0===n?void 0:n.map(e=>Vu(e));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=Vu(e[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(e){const t={};return Object.keys(e).forEach(s=>{switch(s){case"GroupIntroduction":t.introduction=e[s];break;case"GroupName":t.groupName=e[s];break;case"GroupFaceUrl":t.avatar=e[s];break;case"GroupNotification":t.notification=e[s];break;case"ApplyJoinOption":t.joinOption=e[s];break;case"InviteJoinOption":t.inviteOption=e[s];break;case"ShutupAll":t.muteAllMembers=e[s];break;case"Owner_Account":t.ownerID=e[s];break;case"GroupAttrOption":t.groupAttributeOption=function(e){const{BytesChangedKeys:t,GroupAttrSeq:s,OpType:n,PushChangedAttrValFlag:o,GroupAttrInfo:i}=e,r=i.map(e=>{const{Key:t,Val:s,SubKeySeq:n}=e;return{key:t,value:s,sequence:n}});return{changedKeyList:t,groupAttributeList:r,serverMainSequence:s,operation:n,withChangedAttributeInfo:o}}(e[s]);break;case"MsgAppDefinedData":t.groupCustomField=null==(n=e[s])?void 0:n.map(e=>({key:e.Key,value:e.Value}));break;case"InviteOption":t.inviteOption=jc[e[s]]||e[s]}var n}),t}(e[s]);break;case"MsgMemberInfo":t.msgMemberInfo=null===(o=e[s])||void 0===o?void 0:o.map(e=>function(e){const{ShutupTime:t,User_Account:s}=e;return{muteTime:t,userID:s}}(e));break;case"OnlineMemberInfo":t.onlineMemberInfo=function(e){const{ExpireTime:t,OnlineMemberNum:s}=e;return{expireTime:t,onlineMemberNum:s}}(e[s]);break;case"GroupCounterInfo":t.groupCounterInfo=function(e){return e.map(e=>{const{GroupCounterSeq:t,GroupCounter:s,Type:n}=e;return{type:n,groupCounterSeq:t,counterList:s}})}(e[s])}}),t}function Vu(e){const{ImageUrl:t,NickName:s,Role:n,UserId:o}=e;return{avatar:t,nick:s,role:n,userID:o}}function $u(e){const t={};return Object.keys(e).forEach(s=>{switch(s){case"MsgKey":t.messageKey=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"ReportType":t.operationType=e[s];break;case"Authentication":t.authentication=e[s];break;case"MsgFlag":t.messageRemindType=e[s];break;case"UserDefinedField":t.userDefinedField=e[s];break;case"RemarkInfo":t.remarkInfo=e[s];break;case"BanDuration":t.duration=e[s];break;case"MuteTime":t.muteTime=e[s];break;case"MsgMemberExtraInfoList":t.inviteeInfoList=null==(n=e[s]||[])?void 0:n.map(e=>{const{UserId:t,ImageUrl:s,NickName:n}=e;return{userID:t,avatar:s,nick:n}});break;case"MemberList_Account":t.inviteeList=e[s]}var n}),t}class qu{constructor(e){this.type=Pa.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=xu(e);return new qu(t)}_initContent(e){Object.keys(e).forEach(t=>{switch(t){case"groupProfile":this._initGroupProfile(e[t]);break;case"operatorInfo":this._initOperatorInfo(e[t]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(e[t]);break;case"newGroupProfile":this._initNewGroupProfile(e[t]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[t]=e[t]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];Ic[n]&&(this.content.groupProfile[n]=e[n])}}_initOperatorInfo(e){this.content.operatorInfo={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];this.content.operatorInfo[n]=e[n]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach(t=>{e.forEach(e=>{t.userID===e.userID&&Object.assign(t,e)})}):this.content.memberList=e}_initNewGroupProfile(e){this.content.newGroupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];"muteAllMembers"!==n?this.content.newGroupProfile[n]=e[n]:this.content.newGroupProfile.muteAllMembers=1===e.muteAllMembers}}}var Bu=new class{constructor(){this._name="GroupTipsNotification"}init(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=e,{message:{messageFactory:o},OuterConstant:i}=e;null==o||o.registerElementClass(i.MSG_GRP_TIP,qu),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,n.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,n.EMIT_GROUP_TIPS_EVENT,this._emitGroupTipsEvent,this)}onNewGroupTips(e){const{data:t}=e||{},{messageList:s,conversationUpdateFieldList:n}=this._handleGroupTips(t);return s.length>0&&this._handleGroupTipMessage(s),{conversationUpdateFieldList:n,messageList:s}}_emitGroupTipsEvent(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,{messageList:n=[]}=(null===(t=null==e?void 0:e.result)||void 0===t?void 0:t[s.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(n.length>0){const{notificationCenter:e,OuterEvent:t}=this._core;e.emitOuterEvent(t.MESSAGE_RECEIVED,{name:t.MESSAGE_RECEIVED,data:n})}}_handleGroupTips(e,t=!0){const{Event:s,GroupTips:n}=e,o=new Map,i=[],r=[];for(let e=0,i=n.length;e<i;e++){const i=Fu(n[e],"tips");if(s===mc){if(ku.isGroupAttributesUpdated(i)){ku.handleGroupAttributesUpdated(i);continue}if(Nu.isGroupCounterUpdated(i)){Nu.handleGroupCounterUpdated(i);continue}}const{groupProfile:{groupID:a}}=i;if(!eu.hasLocalGroup(a))continue;const c=this._assembleMessage(i);if(s===mc&&(c._onlineOnlyFlag=!0,r.push(c)),s===_c){if(!this._core.message.messageDataHandler.storeConversationMessage(c)&&t)continue;r.push(c)}this._handleConversationOptions(o,c)}return i.push(...o.values()),{conversationUpdateFieldList:i,messageList:r}}_assembleMessage(e){const{OuterConstant:t,message:{messageFactory:s},common:{setGroupTipsUserInfo:n}}=this._core;e.flow="in",e.conversationType=t.CONV_GROUP;const o=s.createMessage(e);n(e.elements,o);const i=new qu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));return o.setElement(i),o.isSystemMessage=!1,o}_handleConversationOptions(e,t){const{common:{getMessagePreviewText:s},utils:{isObject:n},appStore:{conversationStore:o}}=this._core,{conversationID:i,conversationType:r}=t;let a;if(!o.getConversation(i)||!t._onlineOnlyFlag){if(e.has(i))a=e.get(i),"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||a.unreadCount++),a.type=r,a.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1)),a={conversationID:i,unreadCount:e,type:r,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}n(a.lastMessage)&&(a.lastMessage.messageForShow=s(a.lastMessage.type,a.lastMessage.payload)),e.set(i,a)}}_handleGroupTipMessage(e){const{OuterConstant:{GROUP_TIPS_OPERATION_TYPE:t}}=this._core;e.forEach(e=>{const{operationType:s}=e.payload;switch(s){case t.JOINED:this._handleNewMemberJoined(e);break;case t.QUITTED:this._handleMemberQuitted(e);break;case t.KICKED:this._handleMemberKicked(e);break;case t.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e);break;case t.ADMIN_SET:this._handleMemberGrantAdmin(e);break;case t.ADMIN_CANCELED:this._handleMemberRevokeAdmin(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){var t;const{newGroupProfile:s,groupProfile:n,operatorInfo:o}=e.payload,{groupID:i}=n,r=eu.getLocalGroup(i);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(i,s);break;case"groupName":r.name=s[e];break;case"groupCustomField":Array.isArray(r[e])&&Array.isArray(s[e])?Wc(r[e],s[e]):r[e]=s[e];break;default:r[e]=s[e]}});const{utils:{isUndefined:a}}=this._core;a(o)||(null===(t=null==r?void 0:r.selfInfo)||void 0===t?void 0:t.userID)!==o.userID||Object.keys(o).forEach(e=>{"nameCard"===e&&r.updateSelfInfo({nameCard:o[e]}),"role"===e&&this._updateSelfRole(r,o[e])}),eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){const{common:s,OuterConstant:n}=this._core,o=eu.getLocalGroup(e),i=s.getCurrentUserID(),{ownerID:r}=t;i===r&&o.updateGroup({ownerID:r,selfInfo:{role:n.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){const{OuterConstant:s}=this._core;let n=s.GRP_MBR_ROLE_MEMBER;t===fc?n=s.GRP_MBR_ROLE_OWNER:t===vc&&(n=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:n})}_handleGroupMemberCountUpdated(e){const{memberCount:t,groupProfile:{groupID:s}}=e.payload,n=eu.getLocalGroup(s),{utils:{isNumber:o}}=this._core;n&&o(t)&&n.memberCount!==t&&(n.memberCount=t,eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(s))}_handleGroupTipsRecover(e){const{utils:{isArray:t}}=this._core,{groupTipList:s}=(null==e?void 0:e.result)||{};t(s)&&s.forEach(e=>{const{messageList:t}=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1);this._handleGroupTipMessage(t)})}_handleMemberGrantAdmin(e){const{OuterConstant:t}=this._core,{groupProfile:s,userIDList:n}=e.payload,o=this._core.common.getCurrentUserID(),{groupID:i}=s,r=eu.getLocalGroup(i);r&&n.includes(o)&&(r.updateSelfInfo({role:t.GRP_MBR_ROLE_ADMIN}),eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(i))}_handleMemberRevokeAdmin(e){const{OuterConstant:t}=this._core,{groupProfile:s,userIDList:n}=e.payload,o=this._core.common.getCurrentUserID(),{groupID:i}=s,r=eu.getLocalGroup(i);r&&n.includes(o)&&(r.updateSelfInfo({role:t.GRP_MBR_ROLE_MEMBER}),eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(i))}};class ju{constructor(e){this.type=Pa.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=$u(e);return new ju(t)}_initContent(e){Object.keys(e).forEach(t=>{switch(t){case"remarkInfo":this.content.handleMessage=e[t];break;case"groupProfile":this._initGroupProfile(e[t]);break;case"memberInfoList":break;default:this.content[t]=e[t]}})}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];Ec[n]&&(this.content.groupProfile[n]=e[n])}}}var Hu=new class{constructor(){this._name="GroupSystemNotification"}init(e){this._core=e;const{message:{messageFactory:t},OuterConstant:{MSG_GRP_SYS_NOTICE:s}}=e;null==t||t.registerElementClass(s,ju)}onNewGroupSystemNotification(e){const{GroupTips:t=[],isInstantMessage:s=!0}=e;this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${t.length} isInstantMessage:${s}`);const{conversationUpdateFieldList:n,messageList:o}=this._handleGroupSystemNotification(t,s),{notificationCenter:i,OuterEvent:r}=this._core;n.length>0&&this._handleGroupSysTemMessage(s,o),!0===s&&o.length>0&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:o})}_handleGroupSystemNotification(e,t){const s=[];let n={};for(let o=0;o<e.length;o++){const i=Fu(e[o],"system"),{elements:{operationType:r}}=i;if(r===Rc)continue;const a=this._assembleMessage(i);this._core.message.messageDataHandler.storeConversationMessage(a)&&(s.push(a),n=this._handleConversationOptions(a,t))}return n.lastMessage=s[s.length-1],{conversationUpdateFieldList:s.length>0?[n]:[],messageList:s}}_assembleMessage(e){const{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:n}}=this._core;e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM;const o=t.createMessage(e),i=new ju(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));o.setElement(i),o.isSystemMessage=!0;const r=1===o.sequence&&1===o.random,a=2===o.sequence&&2===o.random;return(r||a)&&(o.sequence=n(),o.random=n(),o.generateMessageID()),o}_handleConversationOptions(e,t){const{OuterConstant:s}=this._core,n={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&n.unreadCount++,n}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{const{operationType:t}=e.payload;switch(t){case Cc:this._handleGroupJoinResult(e);break;case yc:this._handleMemberKicked(e);break;case Sc:this._handleGroupDismissed(e);break;case Mc:this._handleGroupInvitedResult(e);break;case Tc:this._handleGroupQuitResult(e);break;case Ac:this._handleMessageRemindTypeSynced(e);break;case Oc:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){const{groupProfile:t}=e.payload,{groupID:s,type:n}=t,o=eu.hasLocalGroup(s);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${s} type:${n} hasLocalGroup:${o}`),o||Kc(n)||(eu.updateLocalGroup([Object.assign({},t)]),eu.emitGroupListUpdate())}_handleMemberKicked(e){const{groupProfile:{groupID:t,type:s}}=e.payload;eu.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupDismissed(e){const{groupProfile:{groupID:t,type:s}}=e.payload;eu.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupInvitedResult(e){const{groupProfile:t}=e.payload,{groupID:s}=t,n=eu.hasLocalGroup(s);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${s} hasLocalGroup:${n}`),n||au.getGroupProfile({groupID:s}).then(e=>{const{data:{group:t}}=e;eu.updateLocalGroup([Object.assign({},t)]),eu.emitGroupListUpdate()})}_handleGroupQuitResult(e){const{groupProfile:{groupID:t,type:s}}=e.payload,n=eu.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${t} type:${s} hasLocalGroup:${n}`),n&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleMessageRemindTypeSynced(e){const{groupProfile:{groupID:t},messageRemindType:s}=e.payload;this._updateConversationProfile(t,{messageRemindType:s})}_handleAVChatRoomMemberBanned(e){const{groupProfile:{groupID:t,type:s}}=e.payload;this._deleteLocalGroup(t,s)}_deleteLocalGroup(e,t){if(Kc(t)){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`)}eu.deleteLocalGroup(e),eu.emitGroupListUpdate()}_updateConversationProfile(e,t){const{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:n}}=this._core,o=`${n}${e}`;s.getConversation(o)&&s.updateConversation(o,t)}},Ku=new class{init(e){this._core=e,e.ssoLog.debug("GroupNotificationHandler.init"),Bu.init(e),Hu.init(e);const{notificationCenter:t,InnerEvent:s}=e,{InnerEventSubType:n}=t;t.subscribeInnerEvent(s.MESSAGE_PUSH,n.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),t.subscribeInnerEvent(s.MESSAGE_PUSH,n.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){Hu.onNewGroupSystemNotification(e)}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const Wu={required:!0,rules:["string"],allowEmpty:!1},Yu={required:!0,rules:["number"],allowEmpty:!1},zu={required:!0,rules:["array"],allowEmpty:!1},Ju={required:!0,rules:["object"],allowEmpty:!1},Qu={createGroup:{name:Wu,type:Wu},dismissGroup:[Object.assign({key:"groupID"},Wu)],joinGroup:{groupID:Wu,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},Wu)],searchGroupByID:[Object.assign({key:"groupID"},Wu)],getGroupProfile:{groupID:Wu,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:Wu,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:Wu,newOwnerID:Wu},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},Wu)],handleGroupApplication:{handleAction:Wu},getGroupMemberList:{groupID:Wu},getGroupMemberProfile:{groupID:Wu,userIDList:zu,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:Wu,userIDList:zu},deleteGroupMember:{groupID:Wu,userIDList:zu},setGroupMemberMuteTime:{groupID:Wu,userID:Wu,muteTime:Object.assign(Object.assign({},Yu),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:Wu,userID:Wu,role:Wu},setGroupMemberNameCard:{groupID:Wu,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:Wu},setGroupMemberCustomField:{groupID:Wu,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:zu},markGroupMemberList:{groupID:Wu,markType:Object.assign(Object.assign({},Yu),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:zu},initGroupAttributes:{groupID:Wu,groupAttributes:Ju},setGroupAttributes:{groupID:Wu,groupAttributes:Ju},deleteGroupAttributes:{groupID:Wu,keyList:Object.assign(Object.assign({},zu),{allowEmpty:!0})},getGroupAttributes:{groupID:Wu,keyList:Object.assign(Object.assign({},zu),{allowEmpty:!0})},getGroupCounters:{groupID:Wu,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:Wu,counters:Ju},increaseGroupCounter:{groupID:Wu,key:Wu,value:Yu},decreaseGroupCounter:{groupID:Wu,key:Wu,value:Yu}},Xu={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var Zu=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=eu,this.groupAction=_u,this.groupAttribute=ku,this.groupMember=Du,this.groupCounter=Nu,this.name="Group"}install(e,t=[]){this._core=e,Pa.init(e),eu.init(e),_u.init(e,this),Du.init(e,this),vu.init(e),Nu.init(e),ku.init(e),Ku.init(e),e.helper.registerValidateConfig({auth:Xu,params:Qu}),this._installSubPlugins(t);const{notificationCenter:s,InnerEvent:n}=e;s.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){const{utils:{isArray:t}}=this._core;e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null===(t=e.install)||void 0===t||t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){eu.reset(),ku.reset(),Nu.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const el=new class{init(e){this.core=e}},tl="AV_MBR_LIST",sl="AV_BAN_MBR",nl={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},ol={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},il=60,rl=2603,al=2686,cl=2688,ul=3122;class ll{constructor(e){const{core:t,manager:s,groupID:n,getRequestParams:o,onSuccess:i,onFail:r}=e;this._name="Polling",this._core=t,this._manager=s,this._timeoutID=-1,this._isRunning=!1,this._groupID=n,this._getRequestParams=o,this._onSuccess=i,this._onFail=r}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return _e(this,void 0,void 0,function*(){try{const e=this._getRequestParams(this._groupID),t=yield function(e,t){return _e(this,void 0,void 0,function*(){const{longPollingKey:s,startSequence:n,startBroadcastSeq:o,simplifiedMessage:i}=e,r={Key:s,StartSeq:n,StartBroadcastSeq:o,DownsizeFlag:i,USP:1,HoldTime:90};return t.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:r})})}(e,this._core);this._onSuccess(this._groupID,t);const s=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(s)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class dl{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){const e=(null===(t=this._map.entries().next().value)||void 0===t?void 0:t[0])||"";this._map.delete(e)}this._map.set(e,1)}has(e){return this._map.has(e)}delete(e){this.has(e)&&this._map.delete(e)}clear(){this._map.clear()}}const hl=e=>e===nl.GROUP_TIPS_HAS_NO_ROAMING||e===nl.GROUP_TIPS_HAS_ROAMING,pl=e=>e===nl.GROUP_SYSTEM_MESSAGE;function gl(e){const t=function(e){const{E:t,MCT:s,MR:n,MP:o,MTS:i,GId:r,MS:a,CCD:c,F_Account:u,IsSys:l,GInf:d,MsgBody:h}=e,p=ge(e,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:t,MsgClientTime:s,MsgRandom:n,MsgPriority:o,MsgTimeStamp:i,ToGroupId:r,MsgSeq:a,CloudCustomData:c,From_Account:u,IsSystemMsg:l,GroupInfo:_l(d),MsgBody:ml(h)},p)}(e);return function(e){const{Event:t}=e;(hl(t)||pl(t))&&(e.From_Account=e.From_Account||"@TIM#SYSTEM"),(t===nl.BROADCAST_MESSAGE||(e=>e===nl.NORMAL_MESSAGE)(t))&&function(e){const{core:{OuterConstant:t}}=el;e.CloudCustomData=e.CloudCustomData||"",e.MsgBody=e.MsgBody.map(e=>{if(e.MsgType===t.MSG_CUSTOM){const{content:t={}}=e;e.content=Object.assign({Data:"",Desc:"",Ext:""},t)}return e})}(e),hl(t)&&function(e){const{GroupJoinType:t,MsgOperatorMemberExtraInfo:s={},MsgMemberExtraInfo:n,Operator_Account:o,List_Account:i,OpType:r}=e.MsgBody||{};"number"==typeof t||1!==r&&2!==r||(e.MsgBody.GroupJoinType=2===r?0:1),n||(e.MsgBody.MsgMemberExtraInfo=null==i?void 0:i.map(e=>({UserId:e}))),1!==r||n||(e.MsgBody.MsgMemberExtraInfo=[{UserId:s.UserId}]),e.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:o,ImageUrl:"",NickName:""},s)}(e),pl(t)&&function(e){const{MsgOperatorMemberExtraInfo:t={},Operator_Account:s}=e.MsgBody||{};e.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:s,ImageUrl:"",NickName:""},t),e.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*e.MsgTimeStamp},e.MsgBody),e.MsgBody=Object.keys(e.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((t,s)=>Object.assign(Object.assign({},t),{[s]:e.MsgBody[s]}),{})}(e)}(t),t}function _l(e){const t=e||{},{GN:s,GT:n,F_Hd:o,F_NN:i,F_Ll:r}=t,a=ge(t,["GN","GT","F_Hd","F_NN","F_Ll"]),c=Object.assign({GroupName:s,GroupType:n},a);return o&&(c.From_AccountHeadurl=o),i&&(c.From_AccountNick=i),r&&(c.From_AccountLevel=r),c}function ml(e){let t=e;Array.isArray(e)||(t=[e]);const s=t.map(e=>{const{O_Account:t,Opt:s,L_Account:n,RT:o,UDF:i,OpInf:r,OnlineInf:a,MsgMemberExtraInfo:c}=e,u=ge(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),l=Object.assign({Operator_Account:t,OpType:s,List_Account:n,ReportType:o,UserDefinedField:i},u);return r&&(l.MsgOperatorMemberExtraInfo=function(e){const{Img:t,NN:s}=e,n=ge(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},n)}(r)),c&&(l.MsgMemberExtraInfo=function(e){return null==e?void 0:e.map(e=>{const{Img:t,NN:s}=e,n=ge(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},n)})}(c)),a&&(l.OnlineMemberInfo=function(e){const{ET:t,Num:s}=e;return{ExpireTime:t,OnlineMemberNum:s}}(a)),l});return Array.isArray(e)?s:s[0]}var fl=new class{constructor(){this._name="MessageParser",this._sequenceList=new dl(200),this._messageIDList=new dl(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(e,t,s=!1){this._sortServerMessageList({groupID:e,serverMessageList:t,isHistoryMessage:s});const n=this._handleMessageList(e,t);if(0===n.length)return;if(!s){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,o=(e=>{const{core:{common:{getMessagePreviewText:t}}}=el;return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(n[n.length-1]);t.updateConversation(`${s}${e}`,{lastMessage:o})}this._checkMessageStacked(n);const o=n.filter(e=>!0===e.isModified),i=n.filter(e=>!1===e.isModified),{OuterEvent:{MESSAGE_RECEIVED:r,MESSAGE_MODIFIED:a}}=this._core;o.length>0&&this._emitEvent({name:a,data:o}),i.length>0&&this._emitEvent({name:r,data:i})}_sortServerMessageList(e){const{groupID:t,serverMessageList:s,isHistoryMessage:n}=e;let o=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!n?(s.sort((e,t)=>e.MS-t.MS),o=s.map(e=>e.MS)):(s.sort((e,t)=>e.MsgSeq-t.MsgSeq),o=s.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${t} count:${o.length} sequenceList:${o}`),o.length=0}_handleMessageList(e,t){var s;const{message:{messageDataHandler:n,messageHelper:o}}=this._core,i=this._avChatRoomHandler.isPollingSimplifiedMessage(),r=[],a=t.length;for(let c=0;c<a;c++){let a=t[c];if(i&&(a=gl(a)),pl(a.Event)&&Object.values(ol).includes(a.MsgBody.ReportType)){this._onGroupDismissed(e);break}if(null===this._filterMessageItem(a))continue;this._patchMessageType(a);const u=o.parseServerGroupMessage(a),l=this._createMessage(u);if(l.level=a.GroupInfo.From_AccountLevel,hl(a.Event)){const e=Object.assign(Object.assign({},u),{elements:Object.assign({},(null===(s=null==u?void 0:u.elements)||void 0===s?void 0:s.content)||{})});if(this._avChatRoomHandler.isGroupAttributesUpdated(e)){this._avChatRoomHandler.handleGroupAttributesUpdated(e);continue}if(this._avChatRoomHandler.isGroupCounterUpdated(e)){this._avChatRoomHandler.handleGroupCounterUpdated(e);continue}}null!==this._filterDuplicateMessage(l)&&(n.isMessageSentByCurrentInstance(l)||(1===u.isModified&&(l.isModified=!0),hl(a.Event)&&this._updateLocalOnlineMemberCountFromTips(a),r.push(l)))}return r}_patchMessageType(e){const{OuterConstant:t}=this._core;hl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),pl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){const{Event:t}=e;return Object.values(nl).includes(t)?(e=>e===nl.MESSAGE_REVOKED)(t)?(this._handleMessageRevoked(e),null):(e=>e===nl.LIVE_CUSTOM_DATA)(t)?(this._onLiveCustomData(e),null):(e=>e===nl.MESSAGE_REACTION)(t)?null:e:(console.warn(`${this._name}.onMessageReceived unknown event:${t}`),null)}_createMessage(e){const{message:{messageFactory:t},OuterConstant:s}=this._core;let n=s.CONV_GROUP;e.elements.type===s.MSG_GRP_SYS_NOTICE&&(n=s.CONV_SYSTEM);const o=!!e.isSystemMessage,i=t.createMessage(Object.assign(Object.assign({},e),{conversationType:n,isSystemMessage:o,flow:"in"}));return i.setElement(e.elements),i}_filterDuplicateMessage(e){const{common:t}=this._core;if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}const s=this._messageIDList.has(e.ID);return s?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:${s}`),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){const{OuterConstant:t,OuterEvent:{MESSAGE_REVOKED:s}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:o},RevokerInfo:{Revoker_Account:i,Reason:r=""}}=e,a=[];o.forEach(e=>{const{TinyId:s,MsgClientTime:o,Random:c,MsgSeq:u}=e,l={conversationID:`${t.CONV_GROUP}${n}`,ID:`${s}-${o}-${c}`,revoker:i,revokeReason:r,revokerInfo:{userID:i,nick:"",avatar:""},sequence:u};a.push(l)}),0!==a.length&&this._emitEvent({name:s,data:a})}_onLiveCustomData(e){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:t}}=this._core,{ToGroupId:s,MsgSeq:n,MsgTimeStamp:o,MsgBody:i}=e,r=(null==i?void 0:i.Content)||(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:r}),console.log(`${this._name}._onLiveCustomData groupID:${s} sequence:${n} time:${o} data:${r}`)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){const{length:t}=e;if(t>=100&&this._reportMessageStackedCount<5){const e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${t} groupID:${e.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(e){const{message:{messageHelper:t},OuterEvent:{MESSAGE_RECEIVED:s}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),o=[],i=e.length;for(let s=0;s<i;s++){let i=e[s];n&&(i=gl(i));const r=t.parseServerGroupMessage(i);if(!Object.values(nl).includes(i.Event)){console.warn(`${this._name}.onBroadcastMessageReceived unknown event:${i.Event}`);continue}const a=this._createMessage(r);a.isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(o.push(a),this._broadcastMessageIDMap.set(a.ID,1))}o.length>0&&this._emitEvent({name:s,data:o})}_updateLocalOnlineMemberCountFromTips(e){const{utils:{isEmpty:t}}=this._core,{ToGroupId:s,MsgBody:{OnlineMemberInfo:n}}=e;if(t(n))return;const{OnlineMemberNum:o=0,ExpireTime:i=il}=n,r=Date.now();let a=this._avChatRoomHandler.getLocalOnlineMemberCount(s);t(a)?a={lastReqTime:0,lastSyncTime:0,latestUpdateTime:r,memberCount:o,expireTime:i}:(a.latestUpdateTime=r,a.memberCount=o),this._avChatRoomHandler.updateLocalOnlineMemberCount(s,a)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const vl=e=>{const{core:{store:t}}=el;return(t.get("cloudConfig")||{})[e]},Il=e=>{const{core:{utils:{isUndefined:t}}}=el;return!t(e)},El=()=>{const e=vl("polling_interval");return Il(e)?parseInt(e,10):300},Cl=()=>{const e=vl("polling_simplified_msg");return Il(e)?parseInt(e,10):0};var yl=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(e){return _e(this,void 0,void 0,function*(){const{appStore:{groupStore:t},OuterConstant:s}=this._core,n=t.getGroup(e);return n?n.type===s.GRP_AVCHATROOM?this._getOnlineMemberCount(e):this._parentPlugin.groupAction.getGroupOnlineMemberCount(e):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(e){return _e(this,void 0,void 0,function*(){const t="_getOnlineMemberCount",{utils:{isEmpty:s}}=this._core,n=Sl.getLocalOnlineMemberCount(e);if(s(n)||this._isExpired(e)){const{memberCount:s=0}=yield this._getOnlineMemberCountFromServer(e);return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${s} from server.`),{code:0,data:{memberCount:s}}}return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${n.memberCount} from local.`),{code:0,data:{memberCount:n.memberCount}}})}_isExpired(e){const t=Sl.getLocalOnlineMemberCount(e),s=Date.now(),n=s-t.lastSyncTime>1e3*t.expireTime,o=s-t.latestUpdateTime>1e4,i=s-t.lastReqTime>3e3;return n&&o&&i}_getOnlineMemberCountFromServer(e){return _e(this,void 0,void 0,function*(){const t="_getOnlineMemberCountFromServer";try{const t=yield function(e,t){return _e(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})})}(e,this._core),{OnlineMemberNum:s=0,ExpireTime:n=il}=t||{},o=Date.now(),i={lastSyncTime:o,latestUpdateTime:o,lastReqTime:o,memberCount:s,expireTime:n};return Sl.updateLocalOnlineMemberCount(e,i),{memberCount:s}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},Sl=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,fl.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){const{OuterConstant:{GRP_AVCHATROOM:t}}=this._core,{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){const{MsgBody:n,GroupInfo:{GroupId:o,GroupType:i}}=s[e],r=Object.values(ol).includes(n.ReportType);i===t&&r&&this.reset(o)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||El()}isPollingSimplifiedMessage(){return 0!==Cl()}isGroupAttributesUpdated(e){return this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e)}updateLocalOnlineMemberCount(e,t){const{notificationCenter:s,OuterEvent:{GROUP_ONLINE_MEMBER_COUNT_CHANGED:n}}=this._core;this._onlineMemberCountMap.set(e,t),s.emitOuterEvent(n,{name:n,data:{groupID:e,count:t.memberCount}})}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){const{OuterConstant:{GRP_LIVE:e}}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=[...this._joinedGroupMap.values()].filter(t=>t.type===e)),t}handleJoinGroupResult(e){return _e(this,void 0,void 0,function*(){const{utils:{isUndefined:t},OuterConstant:{CONV_GROUP:s},apiMap:{getConversationProfile:n},OuterConstant:o}=this._core,{longPollingKey:i,group:r,historyMessageList:a=[]}=e,{groupID:c}=r;return yield this._preCheck(r),this._joinedGroupMap.set(c,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),n(`${s}${c}`),yl.getGroupOnlineMemberCount(c),a.length>0&&fl.onMessageReceived(c,a,!0),t(i)?{code:0,data:{status:o.JOIN_STATUS_SUCCESS,group:r}}:{code:0,data:this.startMessageLongPolling(e)}})}isGroupCounterUpdated(e){return this._parentPlugin.groupCounter.isGroupCounterUpdated(e)}handleGroupCounterUpdated(e){this._parentPlugin.groupCounter.handleGroupCounterUpdated(e)}_preCheck(e){return _e(this,void 0,void 0,function*(){const{common:t,OuterConstant:s,helper:n,apiMap:{quitGroup:o},ssoLog:i}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const e=vl("polling_count_limit");return Il(e)&&e>0?parseInt(e,10):20})())throw new n.ChatError({code:cl,message:"the count of longPolling exceeds the max limit"});return}if(0===this._joinedAVChatRoomCount())return;if(e.type===s.GRP_LIVE)return;const[r,a]=this._joinedGroupMap.entries().next().value;if(a.selfInfo.role===s.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(r);else try{yield o(r)}catch(e){i.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${r} info:`,e)}this.reset(r)})}startMessageLongPolling(e){const{OuterConstant:t}=this._core,{longPollingKey:s,startSequence:n=1,group:o}=e,{groupID:i}=o;return this._pollingRequestInfoMap.set(i,{longPollingKey:s,startSequence:n}),this._pollingIntervalMap.set(i,El()),this._startPolling(i),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:o}}_startPolling(e){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${e}`),this._pollingInstanceMap.has(e)){const t=this._pollingInstanceMap.get(e);return void((null==t?void 0:t.isRunning())||null==t||t.start())}const t=new ll({core:this._core,manager:this,groupID:e,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});t.start(),this._pollingInstanceMap.set(e,t)}_handleRequestParams(e){const{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:Cl()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Cl()}}_handleSuccess(e,t){const{ErrorCode:s}=t;if(0!==s){const{longPollingKey:t,startSequence:n}=this._pollingRequestInfoMap.get(e)||{};return void console.warn(`${this._name}._handleSuccess groupID:${e} key:${t} startSeq:${n} errorCode:${s}`)}this._hasJoinedAVChatRoom(e)&&this._handleResponseData(e,t)}_handleResponseData(e,t){const{Key:s,NextSeq:n,NextBroadcastSeq:o,RspMsgList:i=[],RspBroadcastMsgList:r=[]}=t;if(s&&n&&this._pollingRequestInfoMap.set(e,{longPollingKey:s,startSequence:n}),o&&o>this._startBroadcastSequence&&(this._startBroadcastSequence=o),i.length>0)0!==this._getPollingNoMessageCount(e)&&(this._updatePollingNoMessageCount(e,0),this._pollingIntervalMap.set(e,El())),fl.onMessageReceived(e,i);else{let t=this._getPollingNoMessageCount(e);if(t+=1,this._updatePollingNoMessageCount(e,t),t===(()=>{const e=vl("polling_no_msg_count");return Il(e)?parseInt(e,10):20})()){const t=El()+(()=>{const e=vl("polling_interval_plus");return Il(e)?parseInt(e,10):2e3})();this._pollingIntervalMap.set(e,t)}}r.length>0&&fl.onBroadcastMessageReceived(r)}_handleFailure(e,t){const{ssoLog:s,utils:{safeStringify:n}}=this._core;s.warn("polling",`${this._name}._handleFailure groupID:${e} error: ${n(t)}`)}_joinedAVChatRoomCount(){const{OuterConstant:e}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=this.getJoinedGroups().filter(t=>t.type===e.GRP_AVCHATROOM)),t.length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(e,t){this._joinedGroupMap.set(e,t),this._parentPlugin.groupDataHandler.updateLocalGroup([t])}handleLiveHistoryMessages(e,t){fl.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){if(!this._membersReqInfoMap.has(e))return this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1;let{startTime:t,requestCount:s}=this._membersReqInfoMap.get(e);const{interval:n,count:o}=(()=>{const e=vl("av_members_freq_limit");if(Il(e)){const{interval:t,count:s}=JSON.parse(e);if(s>0&&t>0)return{interval:t,count:s}}return{interval:30,count:4}})();return Date.now()-t>1e3*n?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(s+=1,this._membersReqInfoMap.set(e,{startTime:t,requestCount:s}),s>o)}_stopPolling(e){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${e}`),e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`);const n=this._pollingInstanceMap.get(e);return null==n||n.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),this._onlineMemberCountMap.delete(e),this._pollingIntervalMap.delete(e),this._pollingNoMessageCountMap.delete(e),void this._membersReqInfoMap.delete(e)}for(const e of this._pollingInstanceMap.values())null==e||e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(e,t){this._pollingNoMessageCountMap.set(e,t)}_getPollingNoMessageCount(e){return this._pollingNoMessageCountMap.get(e)||0}_reportLongPollingCount(){const e=this._joinedGroupMap.size;if(e>1){const{common:t,OuterConstant:s,ssoLog:n}=this._core,o=t.isUnlimitedAVChatRoom()?1:0,i=[],r=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:e,type:t})=>{t===s.GRP_LIVE?r.push(e):i.push(e)}),n.info("longPollingCount",String(e),{moreMessage:`av:${i.join(",")} live:${r.join(",")} code: ${o}`,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,fl.reset()}},Ml=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}joinGroup(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.joinGroup(e),{data:{status:n,group:{type:o}}}=s;return o===t.GRP_AVCHATROOM?n===t.JOIN_STATUS_ALREADY_IN_GROUP?s:Sl.handleJoinGroupResult(s.data):s})}},Tl=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}quitGroup(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.quitGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&Sl.reset(e),s})}},Rl=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}dismissGroup(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.dismissGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&Sl.reset(e),s})}},Al=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupMemberList(e){return _e(this,void 0,void 0,function*(){const{appStore:{groupStore:t},helper:s,OuterConstant:n}=this._core,{groupID:o}=e,i=t.getGroup(o);if((null==i?void 0:i.type)===n.GRP_AVCHATROOM&&s.checkBusinessCapabilityBits(tl)){if(Sl.isOverFrequencyLimit(o))throw{code:2996,message:`Over frequency limit: get_members-${o}`};return this._getGroupMemberList(e)}return this._parentPlugin.groupMember.getGroupMemberList(e)})}_getGroupMemberList(e){return _e(this,void 0,void 0,function*(){const t="_getGroupMemberList",{helper:s}=this._core;try{const s=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,offset:n=0}=e,o={GroupId:s,Timestamp:n};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:o})})}(e,this._core),{MemberList:n=[],NextTimestamp:o=0}=s||{},i=this._handleMemberList(n);return console.log(`${this._name}.${t} ok, groupID:${e.groupID} count:${i.length} nextOffset:${o}`),{code:0,data:{memberList:i,offset:o}}}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}})}_handleMemberList(e){return e.map(e=>{const{Member_Account:t,NickName:s="",Avatar:n="",Remark:o="",JoinTime:i=0,Marks:r=[]}=e;return{userID:t,nick:s,avatar:n,remark:o,joinTime:i,marks:r,isOnline:!0}})}},Ol=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}deleteGroupMember(e){return _e(this,void 0,void 0,function*(){const t="deleteGroupMember",{appStore:{groupStore:s},utils:{isUndefined:n},helper:o,OuterConstant:i}=this._core,{groupID:r}=e,a=s.getGroup(r);if(n(a))throw new o.ChatError({functionName:t,code:rl});if(a.type===i.GRP_AVCHATROOM){if(o.checkBusinessCapabilityBits(sl))return this._deleteGroupMember(e);throw new o.ChatError({functionName:t,code:ul})}return this._parentPlugin.groupMember.deleteGroupMember(e)})}_deleteGroupMember(e){return _e(this,void 0,void 0,function*(){const t="_deleteGroupMember",{appStore:{groupStore:s},helper:n,ssoLog:o}=this._core,{groupID:i,duration:r=0,userIDList:a}=e;if(0===r)throw new n.ChatError({functionName:t,code:al});try{return yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,userIDList:n,duration:o,reason:i}=e,r={GroupId:s,Members_Account:n,Duration:o,Description:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:r})})}(e,this._core),o.debug(t,`${this._name}.${t} ok, groupID:${i}`),{code:0,data:{group:s.getGroup(i),userIDList:a}}}catch(e){throw new n.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Dl=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return _e(this,void 0,void 0,function*(){const t="markGroupMemberList",{groupID:s,markType:n,enableMark:o,userIDList:i=[]}=e,r=this._generateRequestData(e);try{const e=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,operationType:n,memberList:o}=e,i={GroupId:s,CommandType:n,MemberList:o};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:i})})}(r,this._core),{MemberList:a=[]}=e||{},{successUserIDList:c,failureUserIDList:u}=this._handleResult(a,i);return{code:0,data:{successUserIDList:c,failureUserIDList:u},successLog:{message:`${this._name}.${t} ok, groupID:${s} markType:${n} enableMark:${o} success:${c.length} fail:${u.length}`}}}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){const{groupID:t,markType:s,enableMark:n,userIDList:o=[]}=e,i=!0===n?1:2,r=[...o];return r.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:t,operationType:i,memberList:r.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){const s=[],n=[];return e.length===t.length?(s.push(...t),{successUserIDList:s,failureUserIDList:n}):(t.forEach(t=>{e.find(e=>e.Member_Account===t)?s.push(t):n.push(t)}),{successUserIDList:s,failureUserIDList:n})}},bl=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),Ml.init(e,t),Tl.init(e,t),Rl.init(e,t),Al.init(e,t),yl.init(e,t),Ol.init(e,t),Dl.init(e)}},Ll=new class{constructor(){this._name="LiveHandler"}init(e){this._core=e;const{helper:t,ssoLog:s}=e;t.registerExperimentalAPI("startMessageLongPolling",this),t.registerExperimentalAPI("stopMessageLongPolling",this),s.debug("LiveHandler.init")}startMessageLongPolling(e){const{common:t,utils:{isEmpty:s},OuterConstant:n,ssoLog:o}=this._core,{groupID:i,longPollingKey:r,longPollingSequence:a=1}=e;if(s(r))return o.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Sl.hasPollingInstance(i)&&this.stopMessageLongPolling({groupID:i});const c=Sl.getJoinedLiveList(),u=t.isUnlimitedAVChatRoom();!u&&c.length>0&&this.stopMessageLongPolling({groupID:c[0].groupID}),o.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${u} groupID:${i} longPollingKey:${r} longPollingSequence:${a}`);const l={groupID:i,type:n.GRP_LIVE};return Sl.updateLocalLiveGroup(i,l),this._getLiveHistoryMessages({groupID:i,longPollingKey:r,startSequence:a}),Sl.startMessageLongPolling({group:l,longPollingKey:r,startSequence:a})}stopMessageLongPolling(e){const{groupID:t}=e;return Sl.reset(t),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${t}`),Promise.resolve({groupID:t})}_getLiveHistoryMessages(e){return _e(this,void 0,void 0,function*(){const{ssoLog:t}=this._core,{groupID:s}=e;try{const n=yield function(e,t){return _e(this,void 0,void 0,function*(){const{groupID:s,longPollingKey:n,startSequence:o}=e,i={GroupId:s,LongPollingKey:n,PullPreSeq:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:i})})}(e,this._core),{RspMsgList:o=[]}=n||{};t.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${s} count:${o.length}`),o.length>0&&Sl.handleLiveHistoryMessages(s,o)}catch(e){t.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${s} info:${e.message}`)}})}},Nl=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,el.init(e),Sl.init(e,t),bl.init(e,t),Ll.init(e);const{notificationCenter:s,InnerEvent:n}=e,{InnerEventSubType:o}=s;s.subscribeInnerEvent(n.MESSAGE_PUSH,o.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Sl.onAVChatRoomSystemNotification(e)}_reset(){Sl.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const wl=new class{init(e){this.core=e}},Pl="message",Gl="user",Ul={OR:"or",AND:"and"},kl=20,Fl=20,xl=20,Vl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},$l={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Ul.OR,Ul.AND].includes(e)||"keywordListMatchType should be OR or AND"},ql={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&e>=1&&e<=100||"count must be a number between 1 and 100"},Bl={required:!1,rules:["string"],allowEmpty:!0},jl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=wl.core;if(!Array.isArray(e))return"groupTypeList should be an array";const s=[t.GRP_PUBLIC,t.GRP_COMMUNITY,t.GRP_WORK,t.GRP_MEETING];let n=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){n=!0;break}return!n||"groupTypeList should be supported group type"}},Hl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=wl.core,s=[t.MSG_TEXT,t.MSG_IMAGE,t.MSG_AUDIO,t.MSG_FILE,t.MSG_VIDEO,t.MSG_LOCATION,t.MSG_CUSTOM,t.MSG_MERGER];let n=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){n=!0;break}return!n||"messageTypeList should be supported message type"}},Kl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=wl.core;return!(!(null==e?void 0:e.startsWith(t.CONV_C2C))&&!(null==e?void 0:e.startsWith(t.CONV_GROUP))&&e!==t.CONV_SYSTEM)||"conversationID is invalid"}},Wl=e=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:t=>"number"==typeof t&&t>=0||`${e} should be a number >= 0';`}),Yl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=wl.core;return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},zl={searchCloudMessages:{keywordList:Vl,keywordListMatchType:$l,cursor:Bl,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Hl,conversationID:Kl,timePosition:Wl("timePosition"),timePeriod:Wl("timePeriod")},searchCloudUsers:{keywordList:Vl,keywordListMatchType:$l,cursor:Bl,count:ql,miniBirthday:Wl("miniBirthday"),maxBirthday:Wl("maxBirthday"),gender:Yl},searchCloudGroupMembers:{keywordList:Vl,keywordListMatchType:$l,cursor:Bl,count:ql,groupTypeList:jl,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Vl,keywordListMatchType:$l,cursor:Bl,count:ql,groupTypeList:jl}},Jl={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Ql=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,wl.init(e),e.helper.registerApi({apiName:"searchCloudMessages",context:this}),e.helper.registerApi({apiName:"searchCloudUsers",context:this}),e.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),e.helper.registerApi({apiName:"searchCloudGroups",context:this}),e.helper.registerValidateConfig({auth:Jl,params:zl})}searchCloudMessages(e){return _e(this,void 0,void 0,function*(){try{const{OuterConstant:t,helper:s}=this._core,{conversationID:n,timePeriod:o,timePosition:i}=e,r=ge(e,["conversationID","timePeriod","timePosition"]),a=Object.assign({count:100},r);n&&(n.startsWith(t.CONV_C2C)?a.account=n.replace(t.CONV_C2C,""):n.startsWith(t.CONV_GROUP)&&(a.groupID=n.replace(t.CONV_GROUP,""))),this._setTimeRangeParams(a,{timePeriod:o,timePosition:i});const c=yield function(e){return _e(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,senderUserIDList:o,messageTypeList:i,endTime:r,startTime:a,cursor:c,account:u,groupID:l}=e,d={Count:t,KeywordList:s,MatchType:n,SendUserIDList:o,MsgTypeList:i,EndTime:r,StartTime:a,Cursor:c,PeerAccount:u,GroupID:l};return wl.core.common.buildAndSendPacket({servcmd:"message_search.query",data:d})})}(a);if(!c)return{code:0,data:{}};const{ErrorCode:u,ErrorInfo:l,TotalCount:d,Cursor:h="",ConversationMsgs:p=[]}=c;if(0!==u)throw{errorCode:u,errorInfo:l};const g=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} res: totalCount:${d}`,_=p.map(n=>{const{MsgList:o,Count:i,GroupID:r,UserID:a}=n,c=r?`${t.CONV_GROUP}${r}`:`${t.CONV_C2C}${a}`;if(this._isSearchingAllConversations(e)&&i>1)return{conversationID:c,messageCount:i,messageList:[]};const u=o.map(e=>s.isEmpty(r)?function(e,t){const s=t.OuterConstant.CONV_C2C,n=t.message.messageHelper.parseServerPushMessage(e),o=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return o.setElement(n.elements),o}(e,this._core):function(e,t){const s=t.OuterConstant.CONV_GROUP,n=t.message.messageHelper.parseServerGroupMessage(e),o=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return o.setElement(n.elements),o}(e,this._core));return{conversationID:c,messageCount:i,messageList:u}});return{code:0,data:{searchResultList:_,cursor:h,totalCount:d},successLog:{message:g}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Pl,functionName:"searchCloudMessages"})}})}searchCloudUsers(e){return _e(this,void 0,void 0,function*(){var t;try{const{keywordListMatchType:s,count:n=Fl}=e,o=ge(e,["keywordListMatchType","count"]),i=Object.assign({count:n,keywordListMatchType:s===Ul.AND?1:0},o);this._setBirthdayRangeParams(i,e);const r=yield function(e){return _e(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,miniBirthday:o,maxBirthday:i,cursor:r,gender:a}=e,c={Count:t,Keywords:s,KeywordMatchType:n,Cursor:r,UserBirthStart:o,UserBirthEnd:i,Gender:a};return wl.core.common.buildAndSendPacket({servcmd:"user_search.query",data:c})})}(i);if(!r)return{error:0,data:{}};const{ErrorCode:a,ErrorInfo:c,TotalCount:u,Cursor:l="",Users:d=[]}=r;if(0!==a)throw{errorCode:a,errorInfo:c};const h=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${u}`,p=[];for(let e=0,s=d.length;e<s;e++){const{UserID:s,ProfileItems:n}=d[e];if(s===this._core.OuterConstant.USER_NOT_FOUND||""===s)continue;const o=n.map(e=>({tag:e.Tag,value:e.StrValue})),i=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,o);p.push(i)}return{code:0,data:{searchResultList:p,cursor:l,totalCount:u},successLog:{message:h}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(e){return _e(this,void 0,void 0,function*(){try{const{count:t=xl,keywordListMatchType:s}=e,n=ge(e,["count","keywordListMatchType"]),o=Object.assign({count:t,keywordListMatchType:s===Ul.AND?1:0},n),i=yield function(e){return _e(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,groupTypeList:o,cursor:i,groupIDList:r}=e,a={Count:t,Keywords:s,KeywordMatchType:n,Cursor:i,GroupType:o,GroupIdList:r};return wl.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:a})})}(o);if(!i)return{code:0,data:{}};const{ErrorCode:r,ErrorInfo:a,GroupMembers:c=[],Cursor:u,TotalCount:l}=i;if(0!==r)throw{errorCode:r,errorInfo:a};const d=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${l}`,h=new Map;return c.forEach(e=>{const{GroupID:t,GroupName:s,GroupType:n,GroupFaceUrl:o,GroupMemberUserName:i,GroupMemberUserID:r,GroupMemberNameCard:a,GroupMemberAvatar:c=""}=e,u={groupID:t,name:s,type:n,avatar:o},l={userID:r,nick:i,nameCard:a,avatar:c};if(h.has(t)){const e=h.get(t);e.memberList.push(l),h.set(t,e)}else h.set(t,{groupInfo:u,memberList:[l]})}),{code:0,data:{searchResultList:[...h.values()],cursor:u,totalCount:l},successLog:{message:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(e){return _e(this,void 0,void 0,function*(){try{const{count:t=kl,keywordListMatchType:s}=e,n=ge(e,["count","keywordListMatchType"]),o=Object.assign({count:t,keywordListMatchType:s===Ul.AND?1:0},n),i=yield function(e){return _e(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,groupTypeList:o,cursor:i}=e,r={Count:t,Keywords:s,KeywordMatchType:n,Cursor:i,GroupType:o};return wl.core.common.buildAndSendPacket({servcmd:"group_search.query",data:r})})}(o);if(!i)return{code:0,data:{}};const{ErrorCode:r,ErrorInfo:a,Groups:c,Cursor:u,TotalCount:l}=i;if(0!==r)throw{errorCode:r,errorInfo:a};const d=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${l}`;return{code:0,data:{searchResultList:(null==c?void 0:c.map(e=>function(e){const{GroupFaceUrl:t,GroupID:s,GroupIntroduction:n,GroupMemberNum:o,GroupName:i,GroupOwnerTinyID:r,GroupOwnerUserID:a,GroupOwnerUserName:c,GroupType:u,GroupAddOption:l,GroupInviteOption:d}=e;return{avatar:t,groupID:s,introduction:n,memberCount:o,name:i,ownerTinyID:r,ownerID:a,ownerNick:c,type:u,joinOption:l,inviteOption:d}}(e)))||[],cursor:u,totalCount:l},successLog:{message:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&t>0&&(e.startTime=s&&s>0?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&s>0&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s}){const{helper:n}=this._core;let o=e;throw 60020===e?o="SearchUnable":s!==Pl&&27003===e?o="SearchParamsError":s!==Pl&&60018===e&&(o="SearchOverLimit"),new n.ChatError({code:o,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){const{miniBirthday:s,maxBirthday:n}=t;void 0!==s&&(e.miniBirthday=s,void 0===n&&(e.maxBirthday=4294967295)),void 0!==n&&(e.maxBirthday=n)}};function Xl(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}const Zl="qualityStat",ed="im-ssolog-quality-stat";var td;!function(e){e[e.ONLINE=8]="ONLINE"}(td||(td={}));const sd="networkRTT",nd="messageE2EDelay",od="sendMessageC2C",id="sendMessageGroup",rd="sendMessageGroupAV",ad="sendMessageRichMedia",cd="cosUpload",ud="messageReceivedGroup",ld="messageReceivedGroupAVPush",dd="messageReceivedGroupAVPull",hd={[sd]:2,[nd]:3,[od]:4,[id]:5,[rd]:6,[ad]:7,[ud]:8,[ld]:9,[dd]:10,[cd]:11},pd=[od,id,rd,ad,cd],gd=[ud,ld,dd],_d=[sd,nd,od,id,rd,ad,cd,ud,ld,dd],md={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},fd="quality_stat";var vd=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(md))}init(e){this._core=e,Object.values(pd).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){const{name:t,message:s,error:n,startTs:o}=e,{SEND_MESSAGE_STAT:i}=this._core.constants;switch(t){case i.TOTAL_COUNT:this._handleTotalCount(s);break;case i.SUCCESS_COUNT:this._handleSuccessCount(s);break;case i.FAILED_COUNT:this._handleFailedCount(s,n);break;case i.SEND_COST:this._handleSendCost(s,o)}}getStatResult(e){const t=this._messageStatsMap.get(e);if(!t||0===t.totalCount)return null;const{totalCount:s,successCount:n,failedCountOfUserSide:o}=t,i=Xl(n/s*100,2),r=n+o,a=Xl(r/s*100,2),c=this._calcAverageValue(t,e);return this._resetStat(e),{total_count:s,success_count_business:n,percent_business:i,success_count_platform:r,percent_platform:a,average_value:c}}_handleTotalCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.totalCount++}_handleSuccessCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.successCount++}_handleFailedCount(e,t){var s;const n=null!==(s=null==t?void 0:t.code)&&void 0!==s?s:null==t?void 0:t.errorCode;if(this._isUserSideError(n)){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.failedCountOfUserSide++}}_handleSendCost(e,t){const s=this._getSendMessageSpecifiedKey(e),n=s&&this._messageStatsMap.get(s);n&&(n.costSum+=Date.now()-t,n.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||e>=120001&&e<=13e4||e>=10100&&e<=10200}_getSendMessageSpecifiedKey(e){const{MSG_IMAGE:t,MSG_AUDIO:s,MSG_VIDEO:n,MSG_FILE:o,CONV_C2C:i,CONV_GROUP:r,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([t,s,n,o].includes(e.type))return ad;if(e.conversationType===i)return od;if(e.conversationType===r){const{groupStore:t}=this._core.appStore,s=t.getGroup(e.to);if(!s)return;const{type:n}=s;return n===a?rd:id}}_calcAverageValue(e,t){return 0===e.costCount?0:t===cd?Math.round(1e3*e.fileSizeSum/e.costSum):Math.round(e.costSum/e.costCount)}_resetStat(e){const t=this._messageStatsMap.get(e);t&&(t.totalCount=0,t.successCount=0,t.failedCountOfUserSide=0,t.costSum=0,t.costCount=0,t.fileSizeSum=0)}},Id=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){this._core=e;const{OuterEvent:t,notificationCenter:s}=e;this._initStatsMap(),s.subscribeOuterEvent(t.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){const t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:n},ssoLog:o}=this._core;if(s(t)||!this._currentCycleStats.has(t))return void o.warn("addMessageSequence",`${Zl}.addMessageSequence invalid key:${t}`);const{conversationID:i,sequence:r}=e,a=i.replace(n,""),c=this._lastCycleStats.get(t);if(0===c.size||!c.has(a))return void this._addToCurrentCycle(t,a,r);const u=c.get(a);r>u.minSeq&&r<u.maxSeq?this._insertToLastCycle(r,u):this._addToCurrentCycle(t,a,r)}getStatResult(e){const t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let s=0,n=0;return t.forEach(e=>{const{sortedSequences:t,minSeq:o,maxSeq:i}=e;t.length>0&&(n+=t.length,s+=i-o+1)}),0===s?null:(this._transferCycleDataOptimized(e),{total_count:s,success_count_business:n,percent_business:Xl(n/s*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(gd).forEach(e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)})}_onMessageReceived(e){const{data:t=[]}=e;t.forEach(e=>{this.addMessageSequence(e)})}_transferCycleDataOptimized(e){const t=this._currentCycleStats.get(e);if(!t)return;const s=new Map;t.forEach((e,t)=>{const n=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;s.set(t,{sortedSequences:n,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,s),this._currentCycleStats.set(e,new Map)}_getReceivedMessageSpecifiedKey(e){const{OuterConstant:{CONV_GROUP:t,GRP_AVCHATROOM:s}}=this._core;if(e.conversationType===t&&!0!==(null==e?void 0:e._onlineOnlyFlag)){const{groupStore:t}=this._core.appStore,n=t.getGroup(e.to);if(!n)return null;const{type:o}=n;return o===s?dd:ud}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);const s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,n=e.length-1;for(;s<=n;){const o=Math.floor((s+n)/2);if(e[o]===t)return o;e[o]<t?s=o+1:n=o-1}return s}_addToCurrentCycle(e,t,s){let n=this._currentCycleStats.get(e).get(t);n?(n.sortedSequences.push(s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s),n.dirty=!0):(n={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,n))}},Ed=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){this._core=e;const{OuterEvent:{MESSAGE_RECEIVED:t},notificationCenter:s}=e;s.subscribeOuterEvent(t,this._onMessageReceived,this)}addMessageDelay(e){const{timeManager:t}=this._core.common,s=t.getServerTimeSeconds()-e;s>0&&(this._totalDelay+=s,this._totalCount++,s<=1?this._countLessThan1s++:s<=3&&this._countLessThan3s++)}getStatResult(){if(0===this._totalCount)return null;const e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),e}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){const{data:t=[]}=e,{OuterConstant:{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:n}}=this._core,o=[s,n];t.forEach(e=>{!o.includes(e.type)&&e.clientTime>0&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Xl(this._totalDelay/e,1)}_calculatePercentage(e,t){return Xl(e/t*100,2)}},Cd=new class{init(e){this.core=e}},yd=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:o,DESTROY:i},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:a}}=e;Cd.init(e),vd.init(e),Id.init(e),Ed.init(e),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(n,this._handleQualityStat,this),s.subscribeInnerEvent(o,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){const{store:e,helper:t,utils:{isUndefined:s}}=this._core,n=e.get("cloudConfig")||{},{q_rpt_interval:o}=n,i=s(o)?12e4:Number(o);t.taskScheduler.addTask({id:fd,intervalMs:i,callback:this.report,context:this})}report(){this._wholePeriod=!0;const e=[..._d.map(e=>{const t=this._buildQualityReportItem(e);return t?Object.assign(Object.assign({},t),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){const{constants:{QUALITY_METRICS:t}}=this._core,{label:s,data:n}=e;s===t.MESSAGE_SEND_SUCCESS_RATE&&vd.dispatchSendStats(n)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},n=e.get("instance")||{},{sdkAppId:o}=n,{q_rpt_sdkappid_bl:i=[]}=s;if(!t.isEmpty(i))return i.split(",").map(e=>Number(e)).includes(o)}_isTinyIDInWhitelist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},n=e.get("login")||{},o=Number(n.tinyID),{q_rpt_tinyid_wl:i=[]}=s;if(!t.isEmpty(i))return i.split(",").includes(o)}_buildQualityReportItem(e){const t=this._getStatResultByKey(e);if(null===t)return null;const s={quality_type:hd[e],timestamp:Date.now(),network_type:td.ONLINE,extension:""};return Object.assign(Object.assign({},s),t)}_getStatResultByKey(e){switch(e){case nd:return Ed.getStatResult();case od:case id:case rd:case ad:case cd:return vd.getStatResult(e);case ud:case ld:case dd:return Id.getStatResult(e);default:return null}}_uploadQualityReports(e){return _e(this,void 0,void 0,function*(){try{const t={header:this._core.common.getCommonHead(),quality:e};yield function(e){const{common:t,channel:s}=Cd.core,n="imopenstat.tim_web_report_v2",o=t.generateSSOLogProtocolData({servcmd:n,data:e}),i=`${o.head.seq}${n}`;return s.sendPacket(o,{requestId:i})}(t),this._reportIndex++,this._wholePeriod=!1}catch(t){console.warn("doReport failed. error:",t),this._pendingReports=this._pendingReports.concat(e),this._cacheFailedLogs()}})}_cacheFailedLogs(){const e=this._pendingReports,t=`${Zl}._cacheFailedLogs`;let s=[...this._failedLogsCache.get(ed)||[],...e];s.length>10&&(s=s.slice(s.length-10),console.log(`${t} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(ed,s),console.log(`${t} count: ${s.length}`),this._pendingReports=[]}_reset(){const{helper:e}=this._core;e.taskScheduler.removeTask(fd)}_dispose(){const{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:n}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(n,this._dispose,this),this._reset(),Ed.dispose(),Id.dispose()}};const Sd=new class{init(e){this.core=e}};function Md(e){return _e(this,void 0,void 0,function*(){var t;const{message:s,user:n,appStore:o,constants:{OuterConstant:i}}=Sd.core,r=o.conversationStore.getConversationMap();if(r.has(e)){const s=null===(t=r.get(e))||void 0===t?void 0:t.userProfile;if(s&&e.startsWith(i.CONV_C2C)){const{avatar:t,nick:n}=s;Sd.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:n,isSentByMe:!1})}}const{data:a}=(yield n.userProfile.getMyProfile())||{};if(a){const{avatar:t,nick:n}=a;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:n,isSentByMe:!0})}})}function Td(e){return _e(this,void 0,void 0,function*(){const t=e.map(e=>e.revoker);try{const s=yield function(e){return _e(this,void 0,void 0,function*(){var t,s;const n=yield null===(t=Sd.core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(s=n.data)||void 0===s?void 0:s.reduce((e,{userID:t,nick:s,avatar:n})=>(e[t]={nick:s||"",avatar:n||""},e),{}):null})}(t);s&&e.forEach(e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}const Rd=1,Ad=2,Od=20,Dd=2500,bd=1,Ld=300;function Nd(e){return _e(this,void 0,void 0,function*(){var t,s;const{appStore:n,utils:{isEmpty:o},common:{getCurrentUserID:i},notificationCenter:r,OuterEvent:a,OuterConstant:{CONV_C2C:c}}=Sd.core,{messageList:u,conversationID:l}=e,d=n.conversationStore.getConversationMap();let h=null===(t=d.get(l))||void 0===t?void 0:t.peerReadTime;if(!h){const e=l.replace(c,""),t=yield function(e){return _e(this,void 0,void 0,function*(){const t={To_Account:e};return Sd.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:t})})}([e]);if(t){const{ReadTime:e}=t;h=null==e?void 0:e[0],d.has(l)&&(d.get(l).peerReadTime=h)}}if(d.has(l)){const e=null===(s=d.get(l))||void 0===s?void 0:s.lastMessage;o(e)||e.fromAccount===i()&&e.lastTime<=h&&!e.isPeerRead&&(e.isPeerRead=!0,n.conversationStore.updateConversation(l,{lastMessage:e}))}const p=[];u.forEach(e=>{e.time<=h&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,p.push(e))}),p.length>0&&r.emitOuterEvent(a.MESSAGE_READ_BY_PEER,{name:a.MESSAGE_READ_BY_PEER,data:p})})}var wd=new class{init(e){this._core=e,e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(e){return _e(this,void 0,void 0,function*(){try{const{message:t,OuterConstant:{Direction:s,CONV_C2C:n,CONV_GROUP:o},InnerEvent:{HISTORY_MESSAGE_FETCHED:i},notificationCenter:r}=this._core,{conversationID:a,nextReqMessageID:c}=e,u=Od;if("@TIM#SYSTEM"===a)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const l=this._getAvailableLocalMessagesCount({conversationID:a,nextReqMessageID:c});if(this._needFetchHistoryMessageList({conversationID:a,availableLocalMessagesCount:l,targetCount:u})){let e=null;if(a.startsWith(o)?e=yield t.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:a,sequence:Number(c),count:u,direction:s.FORWARD,shouldMarkCompleted:!0}):a.startsWith(n)&&(e=yield t.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:a,messageID:c,count:u,direction:s.FORWARD,shouldMarkCompleted:!0})),e){const{nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:o,messageList:u}=e,d=t.messageDataHandler.prependLocalMessageList({messageList:u,conversationID:a});!function(e){const{appStore:t,message:s,OuterConstant:n}=Sd.core,o=t.conversationStore.getConversation(e),i=s.messageDataHandler.getLocalMessageList(e);if(!o||0===i.length||e===n.CONV_SYSTEM)return;const r=[];for(let e=0;e<i.length;e++)"in"!==i[e].flow?"out"!==i[e].flow||i[e].isRead||i[e].setIsRead(!0):r.push(i[e]);let a=0;if(o.type===n.CONV_C2C){const e=r.slice(-o.unreadCount).filter(e=>e.isRevoked).length;a=r.length-o.unreadCount-e}else a=r.length-o.unreadCount;for(let e=0;e<a&&!r[e].isRead;e++)r[e].setIsRead(!0)}(a),yield Md(a),a.startsWith(n)&&(yield Nd({messageList:u,conversationID:a}));const h=this._core.message.messageDataHandler.getLocalMessageList(a).slice(0,d.length+l),p=h.filter(e=>e.isRevoked);yield Td(p),r.emitInnerEvent(i,d);const g={nextReqMessageID:o?"":String(s),messageList:h,isCompleted:o},_=h.map(e=>e.sequence);return{code:0,data:g,successLog:{message:`conversationID: ${a} nextReqMessageID: ${c} availableLocalMessagesCount: ${l} sequenceList: ${JSON.stringify(_)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:a,nextReqMessageID:c,count:u}),successLog:{message:`conversationID: ${a} nextReqMessageID: ${c} availableLocalMessagesCount: ${l}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(e){return _e(this,void 0,void 0,function*(){var t,s;const{OuterConstant:{Direction:n,CONV_C2C:o,CONV_GROUP:i}}=this._core,{conversationID:r,sequence:a,time:c,direction:u=n.FORWARD}=e,{utils:{isEmpty:l},message:d,notificationCenter:h,InnerEvent:{HISTORY_MESSAGE_FETCHED:p}}=this._core;if(![n.BACKWARD,n.FORWARD].includes(u))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:g=Od}=e;g=g>Od?Od:g;let _=null;if(r.startsWith(i)){if(_=yield d.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:r,sequence:a,count:g,direction:u}),_){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,messageList:i,invisibleSequenceList:r}=_;if(this._core.message.messageDataHandler.storeSparseMessageList(i),h.emitInnerEvent(p,i),u===n.FORWARD){const t=o&&e<1;return{code:0,data:{messageList:i,isCompleted:t,nextMessageSeq:t?"":e}}}if(u===n.BACKWARD){if(l(i)&&l(r))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(t=null==i?void 0:i[i.length-1])||void 0===t?void 0:t.sequence)||0,n=(null===(s=null==r?void 0:r[r.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter(e=>e.sequence>=a),isCompleted:!o,nextMessageSeq:o?Math.max(e,n)+1:""}}}return{code:0,data:_}}}else if(r.startsWith(o)&&(_=yield d.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:r,count:g+1,time:c,direction:u}),_)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=_;return h.emitInnerEvent(p,e),s||(u===n.FORWARD?e.shift():e.pop()),d.messageDataHandler.storeSparseMessageList(e),yield Nd({messageList:e,conversationID:r}),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(e){return _e(this,void 0,void 0,function*(){var t;const{appStore:s,common:{ChatError:n,getCurrentUserID:o},OuterConstant:{CONV_C2C:i,CONV_GROUP:r},apiMap:a,message:c}=this._core,u=s.conversationStore.getConversation(e);if(!u)throw new n({code:Dd});const l={fromAccount:o()},{type:d}=u;d===i?(l.type=Rd,l.toAccount=e.replace(i,"")):d===r&&(l.type=Ad,l.toGroupID=e.replace(r,""));try{yield null===(t=null==a?void 0:a.setMessageRead)||void 0===t?void 0:t.call(a,{conversationID:e});const s=yield function(e){return _e(this,void 0,void 0,function*(){const{fromAccount:t,type:s,toAccount:n,toGroupID:o}=e,i={From_Account:t,Type:s,To_Account:n,ToGroupid:o};return Sd.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:i})})}(l);return s&&(c.messageDataHandler.deleteConversationMessageList(e),c.messageHistory.completedHistoryConversations.delete(e),c.messageHistory.clearHistoryMessageListFetchAnchors(e),this._updateConversationLastMessage(e)),{code:0,data:{conversationID:e},successLog:{message:`convID:${e}`}}}catch(t){const{errorCode:s}=t;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:s,moreMessage:`convID:${e}`})}})}_updateConversationLastMessage(e){const{appStore:t}=this._core;t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const{OuterConstant:{CONV_C2C:s,CONV_GROUP:n}}=this._core,o=this._core.message.messageDataHandler.getLocalMessageList(e),{length:i}=o;if(!t)return i;let r=-1;return(null==e?void 0:e.startsWith(s))?r=o.findIndex(e=>e.ID===t):(null==e?void 0:e.startsWith(n))&&(r=o.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===r?0:r}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){const{message:n}=this._core;return t<s&&!n.messageHistory.completedHistoryConversations.has(e)}_getMessageListFromMemory(e){return _e(this,arguments,void 0,function*({conversationID:e,nextReqMessageID:t,count:s}){const{OuterConstant:{CONV_C2C:n},message:o}=this._core,i=this._core.message.messageDataHandler.getLocalMessageList(e),r=i.length;let a=r,c={isCompleted:!1,nextReqMessageID:"",messageList:[]},u=0,l=r;return t?t&&(l=i.findIndex(s=>e.startsWith(n)?s.ID===t:String(s.sequence)===t),u=l>s?l-s:0,a=l):u=r>s?r-s:0,c.messageList=i.slice(u,l),c.isCompleted=a<=s&&o.messageHistory.completedHistoryConversations.has(e),c.isCompleted?c.nextReqMessageID="":c.nextReqMessageID=this._generateNextReqMessageID({conversationID:e,targetIndex:u}),e.startsWith(n)&&(yield Md(e),yield Nd({messageList:c.messageList,conversationID:e})),c})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},Pd=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n,InnerEvent:o}}=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),e.notificationCenter.subscribeInnerEvent(o.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(e){const{conversationList:t}=(null==e?void 0:e.result)||{},{OuterConstant:s,utils:{isArray:n}}=this._core;if(n(t)){const e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return _e(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=[],n=[];return yield Promise.all(null==e?void 0:e.map(e=>_e(this,void 0,void 0,function*(){const{groupProfile:{groupID:o}={},lastMessage:{lastSequence:i}={}}=e,r=`${t.CONV_GROUP}${o}`;let a=this._getLocalLastMessageSequence(r);this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:i})&&(yield this._recoverGroupHistoryForConversation({conversationID:r,localLastMessageSequence:a,serverLastMessageSequence:i,groupTipList:n})),s.push(r.replace(t.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:s,groupTipList:n}})}_recoverGroupHistoryForConversation(e){return _e(this,arguments,void 0,function*({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:n}){try{const{utils:{isArray:o,isObject:i,isEmpty:r},OuterEvent:a,OuterConstant:c,notificationCenter:u,message:l,appStore:d,common:{getMessagePreviewText:h}}=this._core,p=s-t,g=Math.min(20,p),_={},m=yield l.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:e,sequence:t+g,direction:c.Direction.FORWARD,count:g}),{nextReqMessageIDFromServer:f,hasNoMoreHistoryMessage:v,messageList:I,serverGroupTipList:E}=m;o(E)&&n.push(...E);const C=v&&f<0,y=[];if(o(I)&&(I.forEach(e=>{l.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===c.CONV_SYSTEM&&(e.isSystemMessage=!1),l.messageDataHandler.storeConversationMessage(e)&&!r(e.payload)&&(y.push(e),e._isExcludedFromLastMessage||(_.lastMessage=Object.assign({},e)))}),y.length>0&&u.emitOuterEvent(a.MESSAGE_RECEIVED,{name:a.MESSAGE_RECEIVED,data:y})),!C&&I.length>0){const t=I[I.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:n})}i(_.lastMessage)&&(_.lastMessage.messageForShow=h(_.lastMessage.type,_.lastMessage.payload),d.conversationStore.updateConversation(e,_))}catch(t){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${e}`,{error:t})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:e}=this._core,t=e.messageDataHandler.getContinuousMessagesByConversation();for(const[e,s]of t){const t=Array.from(s.values());if((null==t?void 0:t.length)>0){const s=t[t.length-1];e.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(e,s.time):e.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(e,s.sequence)}}}_getLocalLastMessageSequence(e){const{message:t}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=t.messageDataHandler.getLocalMessageList(e),n=s[s.length-1];return null==n?void 0:n.sequence}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const n=s-t;return 0!==s&&t>0&&n>=bd&&n<Ld}_syncC2COfflineMessage(e){const{conversationList:t}=(null==e?void 0:e.result)||{},{OuterConstant:s,utils:{isArray:n}}=this._core;if(n(t)){const e=[];return t.forEach(t=>{t.type===s.CONV_C2C&&e.push(t)}),this._recoverC2CHistoryMessage(e)}}_recoverC2CHistoryMessage(e){return _e(this,void 0,void 0,function*(){yield Promise.all(null==e?void 0:e.map(e=>_e(this,void 0,void 0,function*(){const{conversationID:t,lastMessage:{lastTime:s}={}}=e,n=this._getLocalLastMessageTime(t);this._shouldRecoverC2CHistory({localLastMessageTime:n,serverLastMessageTime:s})&&(yield this._recoverHistoryForC2CConversation({conversationID:t,localLastMessageTime:n,serverLastMessageTime:s}))})))})}_shouldRecoverC2CHistory(e){const{localLastMessageTime:t,serverLastMessageTime:s}=e,n=s-t;return t>0&&n>=1&&n<=600}_recoverHistoryForC2CConversation(e){return _e(this,void 0,void 0,function*(){var t;const{conversationID:s,localLastMessageTime:n,serverLastMessageTime:o}=e,{utils:{isArray:i,isObject:r,isEmpty:a,safeStringify:c},OuterEvent:u,OuterConstant:l,notificationCenter:d,message:h,appStore:p,common:{getMessagePreviewText:g}}=this._core;try{const e={},c=yield h.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:s,direction:l.Direction.BACKWARD,time:n,count:20});if(a(c))return;const{hasNoMoreHistoryMessage:_,messageList:m}=c,f=[];i(m)&&(m.forEach(t=>{h.messageDataHandler.storeConversationMessage(t)&&!a(t.payload)&&(f.push(t),t._isExcludedFromLastMessage||(e.lastMessage=Object.assign({},t)))}),f.length>0&&d.emitOuterEvent(u.MESSAGE_RECEIVED,{name:u.MESSAGE_RECEIVED,data:f}));const v=null===(t=m[m.length-1])||void 0===t?void 0:t.time;!_&&v>o&&(yield this._recoverHistoryForC2CConversation({conversationID:s,localLastMessageTime:v,serverLastMessageTime:o})),r(e.lastMessage)&&(e.lastMessage.messageForShow=g(e.lastMessage.type,e.lastMessage.payload),p.conversationStore.updateConversation(s,e))}catch(e){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${s} error: ${c(e)}`)}})}_getLocalLastMessageTime(e){const{message:t}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(e))return this._lastMessageTimeMapOnDisconnect.get(e);const s=t.messageDataHandler.getLocalMessageList(e),n=s[s.length-1];return null==n?void 0:n.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},Gd=new class{constructor(){this.name="HistoryMessage"}install(e){this._core=e,Sd.init(e),wd.init(e),Pd.init(e),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),Pd.dispose()}_reset(){Pd.reset()}},Ud=new class{init(e){this.core=e}},kd=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(e){const{helper:{registerExperimentalAPI:t}}=e;this._core=e,t("reportModalView",this),t("reportTUIFeatureUsage",this),t("reportRoomEngineEvent",this)}reportModalView(e){const{ssoLog:t,utils:{safeStringify:s,isString:n}}=this._core;try{if(!n(e))throw new Error("reportModalView data is not a string");t.createSSOLogData({method:"reportModalView",message:e,eventType:30}).end(!0)}catch(e){t.debug(`reportModalView Report failed: ${s(e)}`)}}reportTUIFeatureUsage(e){const{ssoLog:t,utils:{safeStringify:s,isEmpty:n}}=this._core,{atomicStoreID:o}=e;try{n(o)||this._reportedAtomicStoreIDs.has(o)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${e.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:o}),this._reportedAtomicStoreIDs.add(o))}catch(e){t.debug(`reportTUIFeatureUsage Report failed: ${s(e)}`)}}reportRoomEngineEvent(e){const{utils:{safeStringify:t},ssoLog:s}=this._core;try{s.debug(`reportRoomEngineEvent Report: ${t(e)}`);const{eventId:n,eventCode:o,eventResult:i,eventMessage:r,moreMessage:a,extensionMessage:c}=e;s.createSSOLogData({method:c,code:n,message:r,eventType:30,costTime:o,uiPlatform:i,moreMessage:a}).end(!0)}catch(e){s.debug(`reportRoomEngineEvent Report failed: ${t(e)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},Fd=new class{constructor(){this.name="DataReport"}install(e){this._core=e;const{notificationCenter:t,InnerEvent:{LOGOUT:s,DESTROY:n}}=e;Ud.init(e),kd.init(e),t.subscribeInnerEvent(s,this._reset,this),t.subscribeInnerEvent(n,this._dispose,this)}_reset(){kd.reset()}_dispose(){const{notificationCenter:e,InnerEvent:{LOGOUT:t,DESTROY:s}}=this._core;e.unSubscribeInnerEvent(t,this._reset,this),e.unSubscribeInnerEvent(s,this._dispose,this),kd.dispose()}};let xd=Ss.STANDARD,Vd=[];function $d(e,t){const{operationType:s,memberInfoList:n,operatorInfo:o}=e||{};let i={};if(Ce(n)?Ce(o)||(i=o):s!==vs.JOINED&&s!==vs.KICKED&&s!==vs.ADMIN_SET&&s!==vs.ADMIN_CANCELED||(i=Object.assign({},n[0])),!Ce(i)){const{nick:e="",avatar:s=""}=i;t.nick=e,t.avatar=s}}xd=Ss.STANDARD,Vd=[Vn,xn,qn,Qn,eo,yd,Gd,Fd,Pi,Xr,wa,Zu,Nl,Ql,Do];var qd=Object.freeze({__proto__:null,ChatError:Ys,WorkflowManager:rn,buildAndSendPacket:hn,get builtInPlugins(){return Vd},checkBusinessCapabilityBits:on,deepMerge:vn,getCurrentUserID:mn,getErrorMessage:Ws,getMessagePreviewText:yn,isC2CConv:e=>t(e)&&e.slice(0,3)===ps.CONV_C2C,isCommunity:cn,isGroupConv:e=>t(e)&&e.slice(0,5)===ps.CONV_GROUP,isInternational:Ks,isTopic:un,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=zt.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:an,registerInterceptor:sn,registerValidateConfig:nn,requireAuth:zs,get sdkEdition(){return xd},setGroupTipsUserInfo:$d,t:En,updateGroupAtInfo:(e,t)=>{const{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=Cs;if(function(e,t){const{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=Cs,{groupID:i,sequence:r}=e;let a=!1;return cn({groupID:i})?(t.forEach(t=>{t.messageSequence===r&&(t.atTypeArray.includes(s)&&e.groupAtType.includes(n)&&(t.atTypeArray=[o]),t.atTypeArray.includes(n)&&e.groupAtType.includes(s)&&(t.atTypeArray=[o],t.__random=e.__random,t.__sequence=e.__sequence),a=!0)}),a):a}(e,t))return;let i=[...e.groupAtType];i.includes(s)&&i.includes(n)&&(i=[o]);const r={from:e.from,groupID:e.groupID,topicID:e.topicID,messageSequence:e.sequence,atTypeArray:i,__random:e.__random,__sequence:e.__sequence};t.push(r)},validateAndExecute:tn,validateParameters:Js});class Bd{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Bd._instance||(Bd._instance=new Bd),Bd._instance}static setInstance(e){Bd._instance=e}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(e,t){let s=[];s=n(e)?e:[e];const o=s.findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=o>-1?s.splice(o,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&Jt(e.install)?(t.add(e.name),Jt(e.getInstalledSubPlugins)?e.install(Jd.getInstance().exposeApiForPlugin(),i):e.install(Jd.getInstance().exposeApiForPlugin()),Jt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Jt(e)?(t.add(e.name),e(Jd.getInstance().exposeApiForPlugin()),Jt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null===(e=zt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}}var Hd=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s){const{emit:n=!0,needSort:o=!1}=s||{},i=this._conversationMap.get(e);i&&!Ce(t)&&(Object.keys(t).forEach(e=>{i[e]=t[e]}),n&&zt.notificationCenter.emitInnerEvent(ss.CONVERSATION_UPDATED,{needSort:o}))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),zt.notificationCenter.emitInnerEvent(ss.CONVERSATION_UPDATED))}},Kd=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const s=this._groupMap.get(e);s&&!Ce(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},Wd=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,s){var n;const{operation:o,updateUnreadCount:i=!0}=s,r=ge(s,["operation","updateUnreadCount"]),a=[];for(const s of t){const t=null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.get(s);if(!t)return!1;Object.keys(r).forEach(e=>{t[e]=r[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(o,{conversationID:e,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){var t;return[...(null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){const{conversationID:s}=t;un(s)?zt.notificationCenter.emitInnerEvent(ls[e],t):zt.notificationCenter.emitInnerEvent(e,t)}},Yd=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(e){return this.userProfileMap.get(e)}getFriend(e){return this.friendMap.get(e)}},zd=Object.freeze({__proto__:null,conversationStore:Hd,groupStore:Kd,messageStore:Wd,userStore:Yd});class Jd{static getInstance(){return Jd._instance||(Jd._instance=new Jd),Jd._instance}static setInstance(e){Jd._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:zt.notificationCenter.subscribeOuterEvent.bind(zt.notificationCenter),off:zt.notificationCenter.unSubscribeOuterEvent.bind(zt.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Bd.getInstance().installExternalPlugin.bind(Bd.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){zt.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){zt.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){zt.ssoLog.debug("setLogLevel",e),zt.ssoLog.setLogLevel(e)}setApplicationID(e){zt.store.set("instance",{applicationID:e})}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){const{common:{timeManager:t},utils:{safeStringify:s}}=zt,{apiName:n,context:o,methodName:i=n,matcher:r}=e;this._apiHandlersMap[n]||(this._apiHandlersMap[n]=[]),this._apiHandlersMap[n].push({context:o,methodName:i,matcher:r}),this._apiMap[n]&&1!==this._apiHandlersMap[n].length||(this._apiMap[n]=(...e)=>{const o=t.getServerTimeMs();let r=0;"login"===n&&(r=4),Ds.includes(n)&&zt.ssoLog.debug(n,`${n} start params: ${s(e)}`),tn(i,e);const a=this._apiHandlersMap[n];for(const s of a)if(!s.matcher||s.matcher(e))try{const t=s.context[s.methodName].bind(s.context)(...e);return this._isPromiseLike(t)?this._handleAsyncResult(t,n,r,o):(this._reportApiSuccessLog({result:t,apiName:n,eventType:r,startTime:o}),t)}catch(e){throw zt.ssoLog.error(n,`${n} fail ${(null==e?void 0:e.errorMessage)||(null==e?void 0:e.message)})`,{error:e,costTime:t.getServerTimeMs()-o,eventType:r,method:n}),e}})}registerExperimentalAPI(e,t,s){const n=s||e;this._experimentalApiMap[e]=t[n].bind(t)}destroy(){return _e(this,void 0,void 0,function*(){var e,t;try{(null===(e=zt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield this._apiMap.logout()),zt.notificationCenter.emitInnerEvent(ss.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{zt.notificationCenter.emitOuterEvent(es.SDK_DESTROY,{SDKAppID:null===(t=zt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),an.clear(),Bd.getInstance().clear(),rn.getInstance().destroy(),zt.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:ss,InnerEventSubType:zt.notificationCenter.InnerEventSubType,OuterEvent:es,OuterConstant:Cs,SignalingEvent:ns,helper:Object.assign(Object.assign(Object.assign({},zt.utils),zt.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:sn,registerValidateConfig:nn,checkBusinessCapabilityBits:on,registerWorkflowStep:rn.getInstance().registerWorkflowStep.bind(rn.getInstance()),ChatError:Ys}),apiMap:this._apiMap},zt),{constants:Object.assign(Object.assign({},ws),zt.constants),common:Object.assign(Object.assign(Object.assign({},qd),zt.common),{workflowManager:rn.getInstance()}),utils:zt.utils,appStore:zd})}callExperimentalAPI(e,t){return zt.ssoLog.debug(`callExperimentalAPI.${e} start params: ${zt.utils.safeStringify(t)}`),this._experimentalApiMap[e]?this._experimentalApiMap[e](t):(zt.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${e} not found, params: ${zt.utils.safeStringify(t)}`),Promise.reject(new Ys({code:ys.INVALID_OPERATION})))}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,n){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:n}),e)).catch(e=>{throw zt.ssoLog.error(t,`${t} fail ${(null==e?void 0:e.errorMessage)||(null==e?void 0:e.message)})`,{error:e,costTime:zt.common.timeManager.getServerTimeMs()-n,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:n,eventType:o}=e;const{timeManager:i}=zt.common,{successLog:{message:r,moreMessage:a}={message:"",moreMessage:""}}=t||{},c=i.getServerTimeMs();"login"===s&&(n+=i.getTimeOffsetWithServer()),Ds.includes(s)&&zt.ssoLog.info(s,`${s} success ${r} ${a}`,{costTime:c-n,eventType:o,message:r,moreMessage:a}),(null==t?void 0:t.successLog)&&delete t.successLog}}class Qd{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:e,store:t}=zt;t.set("login",{isReady:!1}),Jd.getInstance().registerApi({apiName:"login",context:this}),Jd.getInstance().registerApi({apiName:"logout",context:this}),Jd.getInstance().registerApi({apiName:"getLoginUser",context:this}),Jd.getInstance().registerApi({apiName:"isReady",context:this}),Jd.getInstance().registerApi({apiName:"getServerTime",context:this}),Jd.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),e.subscribeInnerEvent(ss.RECONNECTED,this._reLogin,this),zt.notificationCenter.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}login(e){return _e(this,void 0,void 0,function*(){var t;const{sdkEdition:s}=zt.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Ys({functionName:"login",code:ys.REPEAT_LOGIN});const n=yield this._performLogin(e);this._validateAfterLogin(n),this._handleLoginSuccess(n),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const o=null===(t=zt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),{appId:i,href:r}=zt.store.get("instance")||{},{instanceID:a,customStatus:c}=n||{};return{code:0,data:n,successLog:{message:s,moreMessage:`socketID:${o} instanceID:${a} customStatus:${c} href: ${r} appId: ${i}`}}}catch(e){const{errorCode:t}=e;t!==ys.REPEAT_LOGIN&&(this._latestLoginAt=0);const s=new Ys({functionName:"login",code:t});throw console.error(s),s}})}_reLogin(){return _e(this,void 0,void 0,function*(){var e;try{if(!this._isLoginIn())return;const t=yield Hs(this._customLoginInfo);if(t){const{instanceID:s,customStatus:n}=t;zt.store.set("login",{statusInstanceId:s}),rn.getInstance().executeWorkflow(Ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:n,statusType:ds.USER_STATUS_ONLINE});const o=null===(e=zt.channel.getSocketAdapter())||void 0===e?void 0:e.getId();zt.ssoLog.info("reLogin",`socketId:${o} instanceId:${s}`)}}catch(e){console.warn(e)}})}logout(){return _e(this,arguments,void 0,function*(e=bs.USER_INITIATED){const{ssoLog:t}=zt;t.debug("logout",`logout start logoutReason: ${e}`);try{yield this._performLogout(e),t.info("logout","logout success"),zt.ssoLog.uploadSSOLogData()}catch(e){const{errorCode:t}=e;throw new Ys({functionName:"logout",code:t})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?mn():""}isReady(){var e;return null===(e=zt.store.get("login"))||void 0===e?void 0:e.isReady}setCustomLoginInfo(e=""){this._customLoginInfo=e}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),rn.getInstance().reset(),zt.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:e}=zt.common;return e.getServerTimeMs()}_updateAndEmitSDKReady(){zt.store.set("login",{isReady:!0}),setTimeout(()=>{zt.notificationCenter.emitOuterEvent(es.SDK_READY,{name:es.SDK_READY})},1)}_updateAndEmitSDKNotReady(){zt.store.set("login",{isReady:!1}),zt.notificationCenter.emitOuterEvent(es.SDK_NOT_READY,{name:es.SDK_NOT_READY})}_validateAfterLogin(e){const t="login";if(!e)throw new Ys({functionName:t,message:"login response is empty"});const{tinyID:s,a2Key:n}=e||{};if(!s)throw new Ys({functionName:t,code:ys.NO_TINYID});if(!n)throw new Ys({functionName:t,code:ys.NO_A2KEY})}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Ws({code:"RepeatLogin",replacement1:null===(e=zt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return _e(this,void 0,void 0,function*(){const{userID:t,userSig:s}=e;return zt.store.set("login",{userId:t,userSig:s}),this._latestLoginAt=Date.now(),Hs(this._customLoginInfo)})}_ensureAsyncComplete(){return _e(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){const{timeManager:t}=zt.common,{helloInterval:s,timeStamp:n,customStatus:o,purchaseBits:i}=e,r=1e3*n;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=s||120,this._updateLoginStore(e),zt.user.userStatus.setCustomStatus(o),rn.getInstance().executeWorkflow(Ms.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),zt.common.taskScheduler.addTask({id:Gs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(e){return _e(this,void 0,void 0,function*(){const{logoutReason:t}=e,s="im_open_status.wslogout",n=zt.common.generateProtocolData({servcmd:s,data:{wslogout_type:t,isWebUniapp:0}}),o=`${n.head.seq}${s}`;return yield zt.channel.sendPacket(n,{requestId:o})})}({logoutReason:e})}_updateLoginStore(e){const{a2Key:t,tinyID:s,instanceID:n,authKey:o}=e;zt.store.set("login",{a2Key:t,tinyID:s,statusInstanceId:n,authKey:o,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return _e(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=zt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),s=`${t.head.seq}${e}`;return zt.channel.sendPacket(t,{requestId:s})}()}catch(e){zt.ssoLog.warn("_sendOnlinePresenceRequest",` error:${e.message}`)}})}_isLoginIn(){var e;return!0===(null===(e=zt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){zt.common.taskScheduler.removeTask(Gs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",zt.store.clear("login"),zt.store.set("login",{isReady:!1}),zt.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:e}=zt;e.unSubscribeInnerEvent(ss.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this)}}const Xd={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Zd={logout:!0};class eh{constructor(){this.loginAction=new Qd,this.kickedOutHandler=new js,this.loginAction.init(),this.kickedOutHandler.init(),nn({auth:Zd,params:Xd})}}var th,sh,nh;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(th||(th={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(sh||(sh={})),function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem",e.MSG_IMAGE="TIMImageElem",e.MSG_AUDIO="TIMSoundElem",e.MSG_FILE="TIMFileElem",e.MSG_VIDEO="TIMVideoFileElem",e.MSG_GRP_TIP="TIMGroupTipElem",e.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",e.MSG_MERGER="TIMRelayElem"}(nh||(nh={}));const oh={1:sh.MSG_PRIORITY_HIGH,2:sh.MSG_PRIORITY_NORMAL,3:sh.MSG_PRIORITY_LOW,4:sh.MSG_PRIORITY_LOWEST},ih=0,rh=1;var ah;!function(e){e.IN="in",e.OUT="out"}(ah||(ah={}));const ch=2,uh={};function lh(e){if(!e)return 0;if(void 0===uh[e]){const t=new Date,s=`3${t.getHours()}`.slice(-2),n=`0${t.getMinutes()}`.slice(-2),o=`0${t.getSeconds()}`.slice(-2);uh[e]=parseInt([s,n,o,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${uh[e]}`)}else uh[e]+=1;return uh[e]}class dh{constructor(e){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=sh.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=zt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:s,currentUser:n,needReadReceipt:o,isSupportExtension:i,customModerationConfigurationId:r,to:a,from:c,nick:u="",avatar:l="",time:d,messageControlInfo:h,tinyID:p,cloudCustomData:g="",messageLifeTime:_,messageVersion:m=0,conversationType:f,sequence:v,checkResult:I=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:y,isSystemMessage:S=!1,status:M=rs.SUCCESS,revokeReason:T="",conversationSubType:R,clientSequence:A,protocol:O="JSON",revokerInfo:D={userID:"",nick:"",avatar:""},readReceiptInfo:b={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:L,groupProfile:N,atUserList:w,flow:P,isRead:G=!1,priority:U=sh.MSG_PRIORITY_NORMAL,onlineOnlyFlag:k=!1,nameCard:F="",quoteInfo:x}=e;var V;this.clientTime=t,this.senderTinyID=s||p,this.needReadReceipt=!0===o||1===o,this.isSupportExtension=!0===i||1===i,this._cmConfigID=r,this.to=a,this.nick=u,this.avatar=l,this.protocol=O,this.random=void 0===L?(V=V||99999999,Math.round(Math.random()*V)):L,this.time=d||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!(null==h?void 0:h.excludedFromLastMessage),this._isExcludedFromUnreadCount=!!(null==h?void 0:h.excludedFromUnreadCount),this.isModified=!!m,this.cloudCustomData=g,this.messageLifeTime=_,this.from=c||null,this.sequence=v||0,this.conversationType=f||th.CONV_C2C,this.hasRiskContent=I>1,this.version=m,this.isPlaceMessage=E,this.isRevoked=2===E||8===C,this.isSystemMessage=S,this.readReceiptInfo=b,this.revokeReason=T,this.revokerInfo=D,this._receiverList=y,this.conversationSubType=R,this.revoker=(null==D?void 0:D.revoker)||"",this.clientSequence=A||v||0,this.status=M,this.atUserList=w||[],this.flow=P,this.isRead=G,this.priority=U,this._onlineOnlyFlag=k,this.nameCard=F,this.quoteInfo=x,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(N)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(e=>e.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,s;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(s=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===s?void 0:s.call(t):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:s=0}=e;this.conversationType===th.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=s)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:s,MsgFrom_AccountExtraInfo:n,GroupType:o}=e,{NameCard:i}=n||{};"string"==typeof t&&(this.nick=t),"string"==typeof s&&(this.avatar=s),"string"==typeof i&&(this.nameCard=i),this.conversationSubType=o}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const s=this.conversationType;s!==th.CONV_SYSTEM?(t=s===th.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${s}${t}`:null):this.conversationID=th.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=lh(e)),0===this.sequence&&this.conversationType===th.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===th.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class hh{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:s,Ext:n,Desc:o}=t;return new hh({data:s,description:o,extension:n})}constructor(e){this.type=nh.MSG_CUSTOM;const{data:t="",description:s="",extension:n=""}=e;this.content={data:t,description:s,extension:n}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{data:n,description:o,extension:i}=s;return{MsgType:this.type,MsgContent:{Data:n,Ext:i,Desc:o}}}validateBeforeSend(){const{isEmpty:e}=zt.utils,t=[this.content.data,this.content.description,this.content.extension].some(t=>!e(t));return{isValid:t,error:t?null:{message:"content can not be empty"}}}}class ph{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:s}=t;return new ph({text:s})}constructor(e){this.type=is.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e,t;return(null===(t=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===t?void 0:t.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{text:n}=s;return{MsgType:this.type,MsgContent:{Text:n}}}}var gh=new class{constructor(){this._elementClassMap={[nh.MSG_CUSTOM]:hh,[nh.MSG_TEXT]:ph}}init(){Jd.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Jd.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var s;void 0!==(s=t).prototype&&"constructor"in s.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:s=ah.OUT}=e,{userId:n}=zt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:s,currentUser:n})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:n})&&(e.flow=ah.OUT);const o=Object.assign(Object.assign({},e),{currentUser:n});return new dh(o)}createCustomMessage(e){const t=mn(),s=this.createMessage(Object.assign(Object.assign({},e),{from:t})),n=this._elementClassMap[nh.MSG_CUSTOM];if(!s)return null;if(n){const t=new n(e.payload);s.setElement(t)}return s}createTextMessage(e){var t;if(!e)return null;const s="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",n=new ph({text:s}),o=mn(),i=zt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}_updateWithSenderInfo(e){var t,s;const{nick:n,avatar:o,conversationType:i,to:r}=e,{userId:a,tinyID:c}=zt.store.get("login")||{},u=Yd.getUserProfile(a);return e.nick=n||(null==u?void 0:u.nick)||"",e.avatar=o||(null==u?void 0:u.avatar)||"",e.tinyID=e.tinyID||c||"",e.from=a,e.status=rs.UNSENT,e.flow=ah.OUT,i===ps.CONV_GROUP&&(e.nameCard=null===(s=null===(t=Kd.getGroup(r))||void 0===t?void 0:t.selfInfo)||void 0===s?void 0:s.nameCard),e}_isMultiEndpointSyncMessage(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===ah.IN}_isSendByCurrentInstance(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===ah.OUT}};const _h={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},mh={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},fh={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function vh(e,t){return Object.keys(t).forEach(s=>{const{range:n,defaultValue:o}=t[s];e[s]=n.includes(e[s])?e[s]:o}),e}function Ih(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function Eh(e){const{androidInfo:t={},androidOPPOChannelID:s=""}=e,n=t.OPPOChannelID||s,o=vh(t,mh),{sound:i="",FCMChannelID:r=""}=o,a=ge(o,["sound","FCMChannelID"]);return Object.assign(Object.assign({},a),{Sound:Ih(i),OPPOChannelID:n,GoogleChannelID:r})}function Ch(t){const{apnsInfo:s={},ignoreIOSBadge:n=!1,disableVoipPush:o}=t,i=vh(s,fh),{ignoreIOSBadge:r,disableVoipPush:a,enableIOSBackgroundNotification:c}=i,u=ge(i,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),l=!0===r||!0===n?1:0;let d;return e(o)||(d=!1===o?1:0),e(a)||(d=!1===a?1:0),Object.assign(Object.assign({},u),{BadgeMode:l,IsVoipPush:d,ContentAvailable:c?1:0})}function yh(e){return zt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:Ch(e),AndroidInfo:Eh(e)}:_h}function Sh(e){const{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:n,IsPeerRead:o,IsSyncMsg:i,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:u,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:p,TinyId:g,MsgCheckResult:_,CloudCustomData:m,MsgVersion:f,MsgFlagBits:v,RevokerInfo:I,InnerSdkCustomData:E}=e;let C,{From_Account:y,To_Account:S}=e;if(1===i){const e=S;S=y,y=e}if(I){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;C={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:y,avatar:t,nick:s,needReadReceipt:1===n,isSyncMessage:i,clientTime:a,messageLifeTime:c,random:u,sequence:l,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:p,to:S,tinyID:g,checkResult:_,cloudCustomData:m,revokerInfo:C,messageVersion:f,messageFlagBits:v,readReceiptSentByPeer:o,elements:Ah(r),onlineOnlyFlag:0===c,quoteInfo:Dh(E)}}function Mh(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:u,MsgCheckResult:l}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,to:a,elements:Ah(s),messageVersion:c,cloudCustomData:u,checkResult:l}}function Th(e){const{ClientSeq:t,From_Account:s,GroupInfo:n,MsgBody:o,MsgClientTime:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:u,SupportMessageExtension:l,TinyId:d,CloudCustomData:h,MsgVersion:p,MsgCheckResult:g,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:f,GroupAtInfo:v,OnlineOnlyFlag:I,InnerSdkCustomData:E}=e;let C,y=sh.MSG_PRIORITY_NORMAL;if(Object.keys(oh).includes(String(e.MsgPriority))&&(y=oh[e.MsgPriority]),f){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=f;C={reason:e,revoker:t,revokerFromUin:s,userID:t}}const S=function(e){const t=[];return Array.isArray(e)&&e.forEach(e=>{e.GroupAtAllFlag===ih?t.push(e.GroupAt_Account):e.GroupAtAllFlag===rh&&t.push(Cs.MSG_AT_ALL)}),t}(v);return{clientSequence:t,from:s,groupProfile:n,clientTime:i,priority:y,random:r,sequence:a,time:c,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:l,tinyID:d,cloudCustomData:h,messageVersion:p,checkResult:g,needReadReceipt:_,isPlaceMessage:m,revokerInfo:C,atUserList:S,elements:Ah(o),to:Rh(e),onlineOnlyFlag:1===I,quoteInfo:Dh(E)}}function Rh(e){const{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=zt,{ToGroupId:n,GroupInfo:{MillionGroupFlag:o=0,TopicId:i}={}}=e;return o!==s||t(i)?n:i}function Ah(e){if(!e)return null;if(Array.isArray(e))return e.map(e=>{const t=zt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)});const t=zt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function Oh(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:u,CloudCustomData:l,MsgCheckResult:d}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,groupID:a,topicID:c,elements:Ah(s),messageVersion:u,cloudCustomData:l,checkResult:d}}function Dh(e){const{utils:{isString:t,safeStringify:s},ssoLog:n}=zt;if(!t(e))return null;try{const{messageID:t,messageTime:s,messageSequence:n}=JSON.parse(e).businessQuote;return{msgID:t,messageTime:s,messageSequence:n}}catch(e){return n.debug("_parseServerQuoteInfo",s(e)),null}}function bh({conversationUpdateFields:e,message:t}){const{conversationID:s,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,u=!r&&i===ah.IN;e.has(s)?(e.get(s).lastMessage=c,u&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:n,subType:o,unreadCount:u?1:0,lastMessage:c})}function Lh(e){return e.filter(e=>{const t=!Ce(null==e?void 0:e._elements),s=1===(null==e?void 0:e.isPlaceMessage);return t||zt.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:${e.sequence}`),t&&!s})}function Nh(e){const{messageDataHandler:t}=zt.message;return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var wh=Object.freeze({__proto__:null,autoIncrementIndex:lh,filterValidMessages:Lh,parseServerGroupMessage:Th,parseServerPushC2CModifyMessage:Mh,parseServerPushGroupModifyMessage:Oh,parseServerPushMessage:Sh,parseServerPushMessageElement:Ah,shouldStoreMessage:Nh,updateConversationFields:bh});const{isPlainObject:Ph}=zt.utils;function Gh(e,t={}){const{onlineUserOnly:s,messageControlInfo:n}=t;let{offlinePushInfo:o}=t;e.conversationType===th.CONV_C2C&&!0===s&&(o?o.disablePush=!0:o={disablePush:!0});let i="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(i=e.cloudCustomData);const r=[];if(n&&Ph(n)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=n;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===s&&r.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:o}}function Uh(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(!t&&!s)return;const n=[];return t&&n.push("ForbidBeforeSendMsgCallback"),s&&n.push("ForbidAfterSendMsgCallback"),n}function kh(e,t){return _e(this,void 0,void 0,function*(){const s=e.conversationType===th.CONV_GROUP?function(e,t){var s;const o=Gh(e,t),{onlineUserOnly:i,cloudCustomData:r,messageControlInfo:a,offlinePushInfo:c}=o,u=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let l;return n(e._receiverList)&&e._receiverList.length>0&&(l=e._receiverList,e._receiverList.length>50&&(l=e._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(s=zt.store.get("login"))||void 0===s?void 0:s.userId,GroupId:e.to,MsgBody:u,CloudCustomData:r,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:i?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:yh(c),SendMsgControl:i?void 0:a,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:l,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:Uh(t),InnerSdkCustomData:Fh(e)}}}(e,t):function(e,t){var s;const n=Gh(e,t),{onlineUserOnly:o,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=n,c=!0===o?0:void 0,u=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(s=zt.store.get("login"))||void 0===s?void 0:s.userId,To_Account:e.to,MsgBody:u,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:yh(a),ForbidCallbackControl:Uh(t),InnerSdkCustomData:Fh(e)}}}(e,t),o=yield hn(s);return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null})}function Fh(e){if(zt.utils.isObject(e.quoteInfo)){const{msgID:t,messageSequence:s,messageTime:n}=e.quoteInfo;return JSON.stringify({businessQuote:{messageID:t,messageSequence:s,messageTime:n}})}}const{isPlainObject:xh}=zt.utils,{MSG_AUDIO:Vh,MSG_FILE:$h,MSG_IMAGE:qh,MSG_VIDEO:Bh,MSG_MERGER:jh}=Cs;class Hh{init(){Jd.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![Vh,$h,qh,Bh,jh].includes(e[0].type)})}sendMessage(e,t){return _e(this,void 0,void 0,function*(){const{TOTAL_COUNT:s,SEND_COST:n,SUCCESS_COUNT:o,FAILED_COUNT:i}=Os;if(!(e instanceof dh))throw new Ys({code:ys.MSG_INSTANCE_REQUIRED});const r=e.validateBeforeSend();if(!r.isValid){const{code:e,message:t=""}=r.error||{};throw new Ys({code:e,message:t})}this._reportMessageSendQuality({name:s,message:e});let a=!1;const{messageDataHandler:c}=zt.message||{};try{const{messageControlInfo:s}=t||{};let i=null;c.addRandomOfSentMessage(e.random);const r=Date.now();if(e.conversationType===th.CONV_C2C?(a=!0===(null==t?void 0:t.onlineUserOnly),i=yield kh(e,t)):e.conversationType===th.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(e),i=yield kh(e,t)),i){const{messageDropReason:t,sequence:u,time:l}=i;if(this._updateNickAndAvatarOfSentMessageByMe(e),t&&this._logRateLimitInfo(e,u,t),this._reportMessageSendQuality({name:o,message:e}),this._reportMessageSendQuality({name:n,message:e,startTs:r}),!0===e.isResend){const t=c.findMessage(e.ID);t&&(zt.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${t.ID}`),c.deleteConversationMessage(t))}return e.status=rs.SUCCESS,e.time=l,e.conversationType===th.CONV_GROUP&&(e.sequence=u),a?e._onlineOnlyFlag=!0:(c.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),{code:0,data:{message:e}}}}catch(t){e.status=rs.FAIL,c.removeRandomOfSentMessage(e.random);let{errorCode:s}=t||{},n=(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)||"";throw this._hasRiskContent(s)&&(e.hasRiskContent=!0),a||this._isRejectedByRestApi(s)||c.storeConversationMessage(e),this._reportMessageSendQuality({name:i,message:e,error:t}),new Ys({code:s,message:n,data:{message:e},moreMessage:`type:${e.type} from:${e.from} to:${e.to}`})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:n}=e,o=un(s)?ss.TOPIC_NEW_MESSAGE:ss.NEW_MESSAGE;zt.notificationCenter.emitInnerEvent(o,{result:{conversationUpdateFieldList:[{conversationID:s,type:n,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&xh(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t,s){const n=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${s}`;zt.ssoLog.warn("messageDropReason",n)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=zt.message||{};let s=!1;const{conversationID:n}=e,o=t.getLatestMsgSentByMe(n);if(o){const{nick:i,avatar:r}=o;i===e.nick&&r===e.avatar||(s=!0),s&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(e){return _e(this,void 0,void 0,function*(){var t,s,n;const{to:o,from:i}=e;let r=o,a=Kd.getGroup(r);if(cn({groupID:r})&&(null==a?void 0:a.isSupportTopic))throw new Ys({code:ys.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(un(o)&&([r]=o.split(fs.TOPIC),a=Kd.getGroup(r)),!a&&"function"==typeof(null===(t=Jd.getInstance().getApiMap())||void 0===t?void 0:t.getGroupProfile)){const e=yield Jd.getInstance().getApiMap().getGroupProfile({groupID:r});if((null===(n=null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.group)||void 0===n?void 0:n.type)===Cs.GRP_AVCHATROOM){const e=Ws({code:ys.MSG_SEND_FAIL_NOT_IN_AV,replacement1:i,replacement2:r});throw new Ys({code:ys.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){zt.notificationCenter.emitInnerEvent(ss.QUALITY_STAT,{label:As.MESSAGE_SEND_SUCCESS_RATE,data:e})}}var Kh=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){zt.notificationCenter.subscribeInnerEvent(ss.LOGOUT,this._reset,this),zt.notificationCenter.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}get _messagesByConversation(){return Wd.getMessages()}storeConversationMessage(e,t=!1){if(pe)return!0;const{conversationID:s}=e;if(!s)return!1;if(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),this._shouldSkipStoreMessage(e,t))return!1;const n=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(s).set(n,e),this._updateLatestMessageMap(e),!0}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const s=this._getUniqueIdOfMessage(e),n=this._messagesByConversation.get(e.conversationID);if(null==n?void 0:n.has(s)){const e=null==n?void 0:n.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:s=""}=e,n=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(s)&&(null===(t=this._messagesByConversation.get(s))||void 0===t||t.delete(n))}modifyConversationMessage(e,t){var s;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(e,n);if(o){const{messageVersion:n,elements:i,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:${n}`),o.version<n){const t=this._getUniqueIdOfMessage(o),a=ye(i);return(null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.has(t))?Wd.updateMessage(e,[t],{isModified:!0,version:n,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:as.modify}):(o.version=n,o._elements=a,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=r,o.isModified=!0,o.hasRiskContent=c),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var s;if(this._messagesByConversation.has(e))return null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(t);if(this._sparseMessagesByConversation.has(e)){const s=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<s.length;e++)if(this._getUniqueIdOfMessage(s[e])===t)return s[e]}return null}findMessage(e){let t=null;const s=Array.from(this._messagesByConversation.values());for(const n of s)if(t=Array.from(n.values()).find(t=>t.ID===e)||null,t)break;if(!t){const s=Array.from(this._sparseMessagesByConversation.values());for(const n of s)if(t=n.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:e,sequence:t,random:s,revoker:n}){const o=this._messagesByConversation.get(e);let i=null;if(o){const r=Array.from(o.values());if(i=this._findMessageBySequenceAndRandom({messageList:r,random:s,sequence:t}),i){const t=this._getUniqueIdOfMessage(i);return Wd.updateMessage(e,[t],{isRevoked:!0,revoker:n,operation:as.revoke}),i}}if(this._sparseMessagesByConversation.has(e)){const o=Array.from(this._sparseMessagesByConversation.get(e).values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:s,sequence:t}),i)return i.isRevoked=!0,i.revoker=n,i}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:n}){for(let o=0;o<t.length;o+=1){const i=t[o];if(i.sequence===s&&(e(n)||i.random===n))return i}return null}prependLocalMessageList(e){const{messageList:t,conversationID:s}=e;if(0===t.length)return[];if(pe)return t;const n=[],o=[],i=this._messagesByConversation.get(s)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);i.has(t)||(n.push(e),o.push([t,e]))}if(o.length>0){const e=new Map([...o,...i.entries()]);this._messagesByConversation.set(s,e),this._updateLatestMessageSentByMe(s),this._updateLatestMessageSentByPeer(s)}return n}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],s=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const n=this._sparseMessagesByConversation.get(t);for(let t=0;t<s;t++){const s=e[t];n.has(s.ID)||n.set(s.ID,s)}}_updateLatestMessageSentByMe(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length)for(let t=s.length-1;t>=0;t--)if("out"===s[t].flow){this._setLatestMsgSentByMe(e,s[t]);break}}_updateLatestMessageSentByPeer(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length&&e.startsWith("C2C"))for(let t=s.length-1;t>=0;t--)if("in"===s[t].flow){this._setLatestMsgSentByPeer(e,s[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:s,random:n,sequence:o,time:i}=e;return`${t}-${s}-${n}-${o}-${i}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.add(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:s,latestNick:n,isSentByMe:o=!0}=e,i=this._messagesByConversation.get(t);if(!i)return;const r=Array.from(i.values()),a=o?"out":"in";r.forEach(e=>{const{nick:t,avatar:o,flow:i}=e;i===a&&(t!==n&&(e.nick=n),o!==s&&(e.avatar=s))})}isInMessageList(e){var t;const{conversationID:s}=e;if(!s)return!1;if(!this._messagesByConversation.has(s))return!1;const n=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(s))||void 0===t?void 0:t.has(n)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){const t=this._messagesByConversation.get(e);return t?[...t.values()]:[]}getSparseMessageList(e){const t=this._sparseMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),zt.notificationCenter.unSubscribeInnerEvent(ss.LOGOUT,this._reset,this),zt.notificationCenter.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this)}};function Wh(e,t){const s=Hd.getConversation(e);if(null==s?void 0:s.lastMessage){const{lastMessage:n}=s,{lastTime:o,lastSequence:i,version:r}=n,{time:a,sequence:c,messageVersion:u,elements:l,cloudCustomData:d}=t;o===a&&i===c&&r!==u&&(n.type=l[0].type,n.payload=l[0].content,n.messageForShow=yn(n.type,n.payload),n.cloudCustomData=d,n.version=u,Hd.updateConversation(e,{lastMessage:n}))}}class Yh{init(){Jd.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(e){return _e(this,void 0,void 0,function*(){const{to:t,payload:s,sequence:n,conversationType:o,random:i,time:r,from:a,type:c}=e;if(this._canModifyMessageElement(c)){const t=(null==e?void 0:e._elements)||[];t.length>=1&&(t[0].type=c,t[0].content=s)}try{let s=null,c=null;if(o===th.CONV_C2C?s=yield function(e){return _e(this,void 0,void 0,function*(){const{from:t,to:s,version:n=0,sequence:o,random:i,time:r,type:a,cloudCustomData:c}=e,u={From_Account:t,To_Account:s,MsgVersion:n,MsgSeq:o,MsgRandom:i,MsgTime:r,MsgType:a,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:c},l=yield hn({servcmd:"openim.modify_c2c_msg",data:u});if(l){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=l;return{elements:Ah(e),messageVersion:t,cloudCustomData:s}}})}(e):o===th.CONV_GROUP&&(s=yield function(e){return _e(this,void 0,void 0,function*(){const{to:t,version:s=0,sequence:n,cloudCustomData:o}=e,i={GroupId:t,MsgVersion:s,MsgSeq:n,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:o},r=yield hn({servcmd:"openim.modify_group_msg",data:i});if(r){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=r;return{elements:Ah(e),messageVersion:t,cloudCustomData:s}}})}(e)),s){let u=`${o}${t}`;return t===mn()&&o===th.CONV_C2C&&(u=`${o}${a}`),c={conversationType:o,from:a,to:t,time:r,random:i,sequence:n,elements:null==s?void 0:s.elements,cloudCustomData:null==s?void 0:s.cloudCustomData,messageVersion:null==s?void 0:s.messageVersion,conversationID:u},this._handleModifyMessageSuccess(c),{code:0,data:{message:e},successLog:{message:`to:${t}`}}}}catch(e){const{errorCode:t}=e||{};throw new Ys({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:s,message:n}=zt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&zt.notificationCenter.emitOuterEvent(es.MESSAGE_MODIFIED,{name:es.MESSAGE_MODIFIED,data:[n]}),zt.notificationCenter.emitInnerEvent(ss.MESSAGE_MODIFIED,{conversationID:t,message:n}),Wh(t,e)}_canModifyMessageElement(e){return[nh.MSG_TEXT,nh.MSG_CUSTOM,nh.MSG_LOCATION,nh.MSG_FACE].includes(e)}}class zh{init(){const{notificationCenter:e}=zt,{InnerEventSubType:t}=e;rn.getInstance().registerWorkflowStep(Ms.RECEIVE_C2C_NEW_MESSAGE,Ts.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),rn.getInstance().registerWorkflowStep(Ms.RECEIVE_C2C_NEW_MESSAGE,Ts.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),rn.getInstance().registerWorkflowStep(Ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ts.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(ss.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(ss.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){rn.getInstance().executeWorkflow(Ms.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:s}=zt.message||{},n=[],o=new Map;return t.C2cMsgArray.forEach(e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let i=1===t.isModified;s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t._onlineOnlyFlag?s.isMessageSentByCurrentInstance(t)||n.push(t):Nh(t)&&(s.storeConversationMessage(t)&&bh({conversationUpdateFields:o,message:t}),s.isMessageSentByCurrentInstance(t)&&!i||n.push(t))}),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[Ts.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(s)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[Ts.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(s)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[];t.length>0&&zt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const s=null==e?void 0:e.filter(e=>!(null==e?void 0:e.isModified));s.length>0&&zt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:s})}_generateC2CMessage(e){const t=th.CONV_C2C,s=Sh(e),n=zt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:ah.IN})),{elements:o}=s;return n.setElement(o),n}_updateMessageProfile(s){var n;const{messageDataHandler:o}=zt.message||{},i=null===(n=zt.store.get("login"))||void 0===n?void 0:n.userId,{from:r,nick:a,avatar:c,conversationID:u=""}=s;if(r!==i){const n=o.getLatestMsgSentByPeer(u);if(n){const{nick:i,avatar:r}=n;e(a)||e(c)?(s.nick=t(i)?i:s.nick,s.avatar=t(r)?r:s.avatar):a===i&&c===r||(o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:c,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:u,nick:a,avatar:c}))}}else{const e=o.getLatestMsgSentByMe(u);!e||a===e.nick&&c===e.avatar||o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:c,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:s,avatar:n}=e,o=Hd.getConversation(t),{userProfile:i={}}=o||{};i.avatar===n&&i.nick===s||Hd.updateConversation(t,{userProfile:Object.assign(Object.assign({},i),{nick:s,avatar:n})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=zt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&zt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),zt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Wh(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t;const s=th.CONV_C2C;let n=Mh(e);const{to:o,from:i}=n;let r=`${s}${o}`;o===(null===(t=zt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${s}${i}`),n=Object.assign({conversationType:s,conversationID:r},n),this._updateMessageListDueToModify(n)})}_dispose(){const{notificationCenter:e}=zt,{InnerEventSubType:t}=e;zt.notificationCenter.unSubscribeInnerEvent(ss.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),zt.notificationCenter.unSubscribeInnerEvent(ss.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),zt.notificationCenter.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this)}}class Jh{init(){const{notificationCenter:e}=zt,{InnerEventSubType:t}=e;rn.getInstance().registerWorkflowStep(Ms.RECEIVE_GROUP_NEW_MESSAGE,Ts.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),rn.getInstance().registerWorkflowStep(Ms.RECEIVE_GROUP_NEW_MESSAGE,Ts.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(ss.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(ss.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&rn.getInstance().executeWorkflow(Ms.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:s}=zt.message,n=[],o=new Map,i=null==t?void 0:t.GroupMsgArray;return null==i||i.forEach(e=>{if(1===e.GroupInfo.NotVisible)return;const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let i=1===t.isModified;s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t._onlineOnlyFlag?s.isMessageSentByCurrentInstance(t)||n.push(t):Nh(t)&&s.storeConversationMessage(t)&&(n.push(t),bh({conversationUpdateFields:o,message:t}))}),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEvents(e){var t;const{messages:s}=(null===(t=e.result)||void 0===t?void 0:t[Ts.HANDLE_GROUP_NEW_MESSAGE])||{},n=(null==s?void 0:s.filter(e=>!0===(null==e?void 0:e.isModified)))||[];n.length>0&&zt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:n});const o=(null==s?void 0:s.filter(e=>!(null==e?void 0:e.isModified)))||[];o.length>0&&zt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:o})}_generateGroupMessage(e){const t=th.CONV_GROUP,s=Th(e),n=zt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:ah.IN})),{elements:o}=s;return n.setElement(o),n}updateMessageProfile(e){var t;const{messageDataHandler:s}=zt.message||{},n=null===(t=zt.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a="",_elements:c}=e;if(o===n){const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}else if(o===Cs.CONV_SYSTEM){const{operationType:t,memberInfoList:s,operatorInfo:n}=c;let o={};if(Ce(s)?Ce(n)||(o=n):[vs.JOINED,vs.KICKED,vs.ADMIN_SET,vs.ADMIN_CANCELED].includes(t)&&(o=Object.assign({},s[0])),!Ce(o)){const{nick:t="",avatar:s=""}=o;e.nick=t,e.avatar=s}}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=zt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&zt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),Wh(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{const t=th.CONV_GROUP;let s=Oh(e);const{topicID:n,groupID:o}=s,i=n||o,r=`${t}${i}`;s=Object.assign({conversationType:t,conversationID:r,to:i},s),this._updateMessageListDueToModify(s)})}_dispose(){const{notificationCenter:e}=zt,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}}=e;e.unSubscribeInnerEvent(ss.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(ss.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var t,s;const{GroupId:n,GroupType:o}=(null===(s=null===(t=null==e?void 0:e.GroupMsgArray)||void 0===t?void 0:t[0])||void 0===s?void 0:s.GroupInfo)||{},i=o===ms.GRP_AVCHATROOM;return!(!Kd.getGroup(n)&&i)}}var Qh=new class{constructor(){this.c2cMessageReceiver=new zh,this.groupMessageReceiver=new Jh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Xh={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>function(e){var t;return"string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))||"payload.text must be a string"}(e)}}},Zh={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var ep=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(e){return _e(this,void 0,void 0,function*(){try{const{conversationID:t,count:s,direction:o,sequence:i,messageSequenceList:r,shouldMarkCompleted:a=!1,getType:c}=e,u=t.replace(ps.CONV_GROUP,""),l=[];let d=i;if(o===cs.BACKWARD){if("number"!=typeof i)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};d=i+s-1}const h=yield function(e){return _e(this,void 0,void 0,function*(){const{groupID:t,count:s,messageSequence:o,messageSequenceList:i,getType:r}=e,a={GroupId:t,ReqMsgNumber:s,WithRecalledMsg:1,Version:1,GetType:r};return o&&(a.ReqMsgSeq=o),n(i)&&i.length>0&&(a.ReqMsgSeqList=i),yield hn({servcmd:"group_open_http_svc.group_msg_get",data:a})})}({groupID:u,count:s,messageSequence:d,messageSequenceList:r,getType:c});if(h){const{RspMsgList:e=[],NextReqMsgSeq:s=0,IsFinished:n,InvisibleMsgSeq:r}=h,c=`groupID:${u} sequence:${i} reqSeq:${d} direction:${o} complete:${n} nextSequence:${s} remoteMsgCount:${e.length} invisibleSequenceList:${r}`,p=[];for(let t=0;t<e.length;t++){const s=e[t];s.From_Account===Cs.CONV_SYSTEM&&l.push(s);const n=this._parseMessage(s);p.push(n)}p.reverse();let g=n===ch;o===cs.BACKWARD&&(g=p[p.length-1].sequence>=i),g&&a&&this.completedHistoryConversations.add(t);const _=Lh(p);return zt.ssoLog.info("getGroupRoamingMessagesByAnchor",c),{messageList:_,invisibleSequenceList:r,nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:g,serverGroupTipList:l}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new Ys({code:t,message:s})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}isHistoryMessageFetchCompleted(e){return this.completedHistoryConversations.has(e)}_parseMessage(e){var t;const s=ps.CONV_GROUP;4===e.Event&&(e.MsgBody.MsgType=Cs.MSG_GRP_TIP);const n=Th(e),o=gh.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return $d((null===(t=n.elements)||void 0===t?void 0:t.content)||{},o),o.setElement(n.elements),o}getC2CRoamingMessagesByAnchor(e){return _e(this,void 0,void 0,function*(){var t;try{const{conversationID:s,count:n,messageID:o,time:i,direction:r,shouldMarkCompleted:a=!1}=e;let c=i,u="";if(!i){const e=o?zt.message.messageDataHandler.findMessage(o):null;if(c=(null==e?void 0:e.time)||0,o&&this._historyMessageListFetchAnchors.has(s)){const e=this._historyMessageListFetchAnchors.get(s);c=e.lastMessageTime,u=e.messageKey}}const l=s.replace(ps.CONV_C2C,""),d=yield function(e){return _e(this,void 0,void 0,function*(){const{peerAccount:t,count:s,lastMessageTime:n,messageKey:o,direction:i}=e;return hn({servcmd:"openim.getroammsg",data:{Peer_Account:t,MaxCnt:s,WithRecalledMsg:1,LastMsgTime:n,MsgKey:o,GetDirection:i}})})}({count:n,lastMessageTime:c,messageKey:u,peerAccount:l,direction:r});if(d){const{MsgList:e=[],Complete:n,MsgKey:o,LastMsgTime:i}=d;this._historyMessageListFetchAnchors.set(s,{messageKey:o,lastMessageTime:i});const r=[];for(let t=0;t<e.length;t++){const s=e[t],n=this._parseC2CMessage(s);r.push(n)}const c=Lh(r),u=null===(t=c[0])||void 0===t?void 0:t.ID,l=1===n;return l&&a&&this.completedHistoryConversations.add(s),{messageList:c,nextReqMessageIDFromServer:u,lastMessageTime:i,hasNoMoreHistoryMessage:l}}}catch(e){throw zt.ssoLog.debug("getC2CRoamingMessagesByAnchor",Se(e)),e}})}_parseC2CMessage(e){const t=ps.CONV_C2C,s=Sh(e),n=gh.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}reset(){this._historyMessageListFetchAnchors.clear(),this.completedHistoryConversations.clear()}};class tp{constructor(){this.messageHelper=wh,this.messageFactory=gh,this.messageSender=new Hh,this.messageAction=new Yh,this.messageReceiver=Qh,this.messageDataHandler=Kh,this.messageHistory=ep,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),nn({auth:Zh,params:Xh}),zt.notificationCenter.subscribeInnerEvent(ss.LOGOUT,this._reset,this),zt.notificationCenter.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}_reset(){this.messageHistory.reset()}_dispose(){this._reset(),zt.notificationCenter.unSubscribeInnerEvent(ss.LOGOUT,this._reset,this),zt.notificationCenter.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this)}}const sp="Tag_Profile_IM_",np={NICK:`${sp}Nick`,GENDER:`${sp}Gender`,BIRTHDAY:`${sp}BirthDay`,LOCATION:`${sp}Location`,SELFSIGNATURE:`${sp}SelfSignature`,ALLOWTYPE:`${sp}AllowType`,LANGUAGE:`${sp}Language`,AVATAR:`${sp}Image`,MESSAGESETTINGS:`${sp}MsgSettings`,ADMINFORBIDTYPE:`${sp}AdminForbidType`,LEVEL:`${sp}Level`,ROLE:`${sp}Role`},op="Tag_Profile_Custom",ip="profileCustomField",rp="USER_STATUS",ap=1,cp=1e3,up={userID:"",nick:"",gender:"Gender_Type_Unknown",birthday:0,location:"",selfSignature:"",allowType:"AllowType_Type_AllowAny",language:0,avatar:"",messageSettings:0,adminForbidType:"AdminForbid_Type_None",level:0,role:0,lastUpdatedTime:0,profileCustomField:[]},lp=new Map([[np.NICK,"nick"],[np.GENDER,"gender"],[np.BIRTHDAY,"birthday"],[np.LOCATION,"location"],[np.SELFSIGNATURE,"selfSignature"],[np.ALLOWTYPE,"allowType"],[np.LANGUAGE,"language"],[np.AVATAR,"avatar"],[np.MESSAGESETTINGS,"messageSettings"],[np.ADMINFORBIDTYPE,"adminForbidType"],[np.LEVEL,"level"],[np.ROLE,"role"]]);var dp=new class{createProfile(e,t){const s={userID:e,profileCustomField:[]};return t.forEach(e=>{const{tag:t,value:n}=e;t&&t.indexOf(op)>-1?s.profileCustomField.push({key:t,value:n}):lp.has(t)&&(s[lp.get(t)]=n)}),Object.assign(Object.assign({},up),s)}parseProfileItem(e=[]){const t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.Value})}),t}parseProfileList(e=[]){const t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.ValueBytes})}),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach(s=>{s!==ip&&t.push({tag:np[s.toUpperCase()],value:e[s]})}),e.profileCustomField&&n(e.profileCustomField)&&e.profileCustomField.forEach(e=>{t.push({tag:e.key,value:e.value})}),t}normalizeProfileFields(e){const t={},s=[];return e.forEach(e=>{const{tag:n,value:o}=e;if(n&&n.indexOf(op)>-1&&s.push({key:n,value:o}),lp.has(n)&&void 0!==o){const e=lp.get(n);t[e]=o}}),s.length>0&&(t.profileCustomField=s),t}};const{generateProtocolData:hp}=zt.common;function pp(e){return _e(this,void 0,void 0,function*(){const t="profile.portrait_get_all",s={From_Account:mn(),UserItem:[]};e.forEach(e=>{s.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});const n=hp({servcmd:t,data:s}),o=`${n.head.seq}${t}`,i=yield zt.channel.sendPacket(n,{requestId:o});if(i)return function(e){const{ActionStatus:t,ErrorCode:s,ErrorDisplay:n,ErrorInfo:o,UserProfileItem:i}=e,r=[];return i.map(e=>{const{To_Account:t,CustomSequence:s,ResultCode:n,ResultInfo:o,StandardSequence:i,ProfileItem:a}=e,c=dp.parseProfileItem(a);r.push({userId:t,customSequence:s,resultCode:n,resultInfo:o,standardSequence:i,profileItem:c})}),{actionStatus:t,errorCode:s,errorDisplay:n,errorInfo:o,userProfile:r}}(i)})}function gp(e){return Yd.getFriendMap().has(e)}const{isEmpty:_p}=zt.utils;class mp{constructor(){this._strangerProfileMap=new Map}init(){Jd.getInstance().registerApi({apiName:"getMyProfile",context:this}),Jd.getInstance().registerApi({apiName:"getUserProfile",context:this}),Jd.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=dp.createProfile.bind(dp);const{notificationCenter:e}=zt;rn.getInstance().registerWorkflowStep(Ms.SYNC_SERVER_INFO_AFTER_LOGIN,Ts.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(ss.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(ss.LOGOUT,this._reset,this),e.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}getMyProfile(){return _e(this,void 0,void 0,function*(){try{const e=mn(),t=yield pp([e]);if(t){const s=this._handleProfileFormResponse(t)[0];return Yd.getUserProfileMap().set(e,s),{code:0,data:s}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new Ys({functionName:"getMyProfile",code:t,message:s})}})}getUserProfile(e){return _e(this,void 0,void 0,function*(){try{let{userIDList:t}=e;const{userIdListToRequest:s,profileFromCache:o}=this._filterRequestAndCacheUsers(t);if(0===s.length)return{code:0,data:o,successLog:{message:`userIDList.length:${t.length}`}};s.length>cp&&(zt.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),s.length=cp);const{data:i,error:r}=yield this._batchFetchUserProfiles(s),a=s.length,c=i.length,u=a-c;if(0===o.length&&a===u&&!_p(r))throw r;if(n(i))return i.forEach(e=>{gp(e.userID)?Yd.getUserProfileMap().set(e.userID,e):this._strangerProfileMap.set(e.userID,e)}),{code:0,data:i.concat(o),successLog:{message:`getUserProfile query:${a} success:${c} fail:${u} from cache:${o.length}`}}}catch(e){const{errorCode:t}=e;throw new Ys({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return _e(this,void 0,void 0,function*(){const e=mn(),t=Yd.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()})}updateMyProfile(e){return _e(this,void 0,void 0,function*(){const t=mn(),s={};for(const t in e)void 0!==e[t]&&(s[t]=e[t]);const n=dp.convertParamsToProfile(s);try{const e={From_Account:t,ProfileItem:n};yield function(e){return _e(this,void 0,void 0,function*(){const t="profile.portrait_set",s=hp({servcmd:t,data:e}),n=`${s.head.seq}${t}`,o=yield zt.channel.sendPacket(s,{requestId:n});if(o){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:n}=o;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:n}}})}(e);const o=Yd.getUserProfile(t);let i;i=o?Object.assign(Object.assign({},o),s):dp.createProfile(t,n);const r=!Qt(o,i,["lastUpdatedTime"]);return i.lastUpdatedTime=Date.now(),Yd.getUserProfileMap().set(t,i),r&&this._emitProfileUpdated(i),{code:0,data:i,successLog:{message:`profileArray: ${zt.utils.safeStringify(n)}`}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new Ys({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(e){return _e(this,void 0,void 0,function*(){const t=mn(),s=Date.now(),n=Yd.getUserProfile(t);let o={};o=n?Object.assign(n,e):dp.createProfile(t,e),o.lastUpdatedTime=s,Yd.getUserProfileMap().set(t,o)})}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:s,ProfileList:n}=e;return{userId:t,pushType:s,profileList:dp.parseProfileList(n)}}(e.ProfileDataMod[0]);if(_p(t))return;const{isProfileUpdated:s,profile:n}=this._handleProfileModified(t);s&&this._emitProfileUpdated(n)}_emitProfileUpdated(e){zt.notificationCenter.emitInnerEvent(ss.PROFILE_UPDATE,{name:ss.PROFILE_UPDATE,data:[e]}),zt.notificationCenter.emitOuterEvent(es.PROFILE_UPDATED,{name:es.PROFILE_UPDATED,data:[e]}),Hd.updateConversation(`C2C${null==e?void 0:e.userID}`,{userProfile:e})}_dispose(){const{notificationCenter:e}=zt;e.unSubscribeInnerEvent(ss.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(ss.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:s}=e,n=Yd.getUserProfile(t);if(!(mn()===t||gp(t)&&n))return{isProfileUpdated:!1,profile:null};const o=dp.normalizeProfileFields(s),i=Object.keys(o).some(e=>e===ip?this._isCustomFieldChanged(n.profileCustomField,o.profileCustomField):n[e]!==o[e]);if(!i)return{isProfileUpdated:!1,profile:n};const r=Date.now(),a=Object.prototype.hasOwnProperty.call(o,ip)?this._mergeProfileCustomField(n.profileCustomField,o.profileCustomField):n.profileCustomField,c=Object.assign(Object.assign(Object.assign({},n),o),{profileCustomField:a,lastUpdatedTime:r});return Yd.getUserProfileMap().set(t,c),{isProfileUpdated:i,profile:c}}_filterRequestAndCacheUsers(e){const t=[],s=[];return e.forEach(e=>{const n=Yd.getUserProfileMap().has(e);gp(e)&&n?s.push(Yd.getUserProfile(e)):this._isStrangerAndProfileValid(e)?s.push(this._strangerProfileMap.get(e)):t.push(e)}),{userIdListToRequest:t,profileFromCache:s}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const s=t.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!_p(e.profileItem)),n=Date.now();return s.map(e=>{const t=dp.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=n,t})}_isStrangerAndProfileValid(e){var t;if(!gp(e)){const{lastUpdatedTime:s=0}=this._strangerProfileMap.get(e)||{},n=(null===(t=zt.store.get("cloudConfig"))||void 0===t?void 0:t.stranger_profile_expiration_time)||6e5;return Date.now()-s<=n}return!1}_chunkUserIDList(e,t){return Array.from({length:Math.ceil(e.length/t)},(s,n)=>e.slice(n*t,(n+1)*t))}_batchFetchUserProfiles(e){return _e(this,void 0,void 0,function*(){const t=[],s=[];let o={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(pp(e))}),(yield Promise.allSettled(t)).forEach(e=>{if("fulfilled"===e.status){const t=e.value,o=this._handleProfileFormResponse(t);n(o)&&s.push(...o)}else if("rejected"===e.status){const{code:t,message:s}=e.reason||{};o={errorCode:t,message:s}}}),{data:s,error:o}})}_isCustomFieldChanged(e=[],t=[]){if(!n(t)||0===t.length)return!1;if(!n(e)||0===e.length)return!0;const s=new Map(e.map(e=>[e.key,e.value]));return t.some(e=>s.get(e.key)!==e.value)}_mergeProfileCustomField(e=[],t=[]){const s=n(e)?e.map(e=>Object.assign({},e)):[];return n(t)&&0!==t.length?(t.forEach(({key:e,value:t})=>{const n=s.find(t=>t.key===e);n?n.value=t:s.push({key:e,value:t})}),s):s}_reset(){Yd.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const fp=new Map,vp=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=vp.length;e<t;e++)fp.set(e,vp[e]);function Ip(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let s="";if(t.length%4==1)return"";for(let e,n,o=0,i=0;n=t.charAt(i++);~n&&(e=o%4?64*e+n:n,o++%4)?s+=String.fromCharCode(255&e>>(-2*o&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);try{return decodeURIComponent(escape(s))}catch(e){return console.warn(e),""}}const{isEmpty:Ep}=zt.utils,{generateProtocolData:Cp}=zt.common;function yp(e){return _e(this,void 0,void 0,function*(){const t="im_open_status.ws_get_user_status",s=Cp({servcmd:t,data:{To_Account:e}}),n=`${s.head.seq}${t}`,o=yield zt.channel.sendPacket(s,{requestId:n});if(o)return function(e){const{ErrorCode:t,ErrorInfo:s,ErrorList:n=[],UserStatusList:o=[]}=e,i=o.map(e=>{const{To_Account:t,Status:s,CustomStatus:n,Detail:o=[]}=e;return{userID:t,statusType:s,customStatus:Ip(n),onlineDevices:Sp(o)}}),r=n.map(e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:Ep(s)?t:s,code:n,message:o}});return{errorCode:t,errorInfo:s,successUserList:i,failureUserList:r}}(o)})}function Sp(e){const t=[];return null==e||e.forEach(e=>{const{Platform:s,Status:n}=e;"Online"===n&&t.push(s)}),t}class Mp{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=zt;Jd.getInstance().registerApi({apiName:"getUserStatus",context:this}),Jd.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Jd.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Jd.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),rn.getInstance().registerWorkflowStep(Ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ts.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(ss.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(ss.LOGOUT,this._reset,this),e.subscribeInnerEvent(ss.DESTROY,this._dispose,this)}setSelfStatus(e){return _e(this,void 0,void 0,function*(){const t=mn(),{customStatus:s}=e;try{return yield function(e){return _e(this,void 0,void 0,function*(){const t="im_open_status.ws_set_custom_status",s=Cp({servcmd:t,data:{CustomStatus:e}}),n=`${s.head.seq}${t}`,o=yield zt.channel.sendPacket(s,{requestId:n});if(o){const{ErrorCode:e,ErrorInfo:t}=o;return{errorCode:e,errorInfo:t}}})}(s),this._customStatus=s,{code:0,data:{userID:t,statusType:ap,customStatus:s},successLog:{message:`customStatus: ${s}`}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new Ys({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(e){return _e(this,void 0,void 0,function*(){const{userIDList:t=[]}=e;if(this._isOnlyMeInArray(t))return this._getMyStatus();const s=yield this._getUserStatus(t);return Object.assign(Object.assign({},s),{successLog:{message:`userIDList length: ${t.length}`}})})}setCustomStatus(e){const t=Ip(e);this._customStatus=t}subscribeUserStatus(e){return _e(this,void 0,void 0,function*(){try{const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const s=this._getMaxUserCount("subscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return _e(this,void 0,void 0,function*(){const{channel:t}=zt,s="im_open_status.ws_status_subscribe",n=Cp({servcmd:s,data:{To_Account:e}}),o=`${n.head.seq}${s}`;return yield t.sendPacket(n,{requestId:o})})}(n),i=this._parseResponse(o);return{code:0,data:{failureUserList:i},successLog:{message:`userID length:${t.length} failCount: ${i.length}`}}}catch(e){const{errorCode:t}=e;throw new Ys({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(e){return _e(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,s=this._getMaxUserCount("unsubscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return _e(this,void 0,void 0,function*(){const{channel:t}=zt,s="im_open_status.ws_status_unsubscribe";let n={};n=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const o=Cp({servcmd:s,data:n}),i=`${o.head.seq}${s}`;return yield t.sendPacket(o,{requestId:i})})}(n),i=this._parseResponse(o);return{code:0,data:{failureUserList:i},successLog:{message:`userID length:${t.length} failCount: ${i.length}`}}}catch(e){const{errorCode:t}=e;throw new Ys({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},s=t.map(e=>{const{To_Account:t,Status:s,CustomStatus:n,Platform:o}=e,i={userID:t,statusType:s,customStatus:Ip(n)};return o&&(i.onlineDevices=o),i});this._emitUserStatusUpdatedEvent(s)}_onReOnline(e){const t=Ip(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const s={userID:mn(),statusType:ap,customStatus:t};this._emitUserStatusUpdatedEvent(s)}_emitUserStatusUpdatedEvent(e){zt.notificationCenter.emitOuterEvent(es.USER_STATUS_UPDATED,{name:es.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){const{ErrorList:t=[]}=e;return t.map(e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:zt.utils.isEmpty(s)?t:s,code:n,message:o}})}_checkBusinessCapabilityBits(e){if(!zt.store.get("commercialConfig").get(rp))throw new Ys({functionName:e,code:ys.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=zt.store.get("cloudConfig")||{},s={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:n,default:o}=s[e],i=t[n]||o;return parseInt(i,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:mn(),statusType:ap,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(e){return _e(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const t=this._getMaxUserCount("query"),s=this._sliceUserIDList(e,t),n=yield yp(s),{successUserList:o,failureUserList:i}=n||{};return{code:0,data:{successUserList:o,failureUserList:i}}}catch(e){const{errorCode:t}=e;throw new Ys({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){const t=mn();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=zt;e.unSubscribeInnerEvent(ss.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(ss.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const Tp={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(e){for(const t of e){if("object"!=typeof t)return"Each item in profileCustomField must be an object";if("string"!=typeof(null==t?void 0:t.key))return"Each item.key in profileCustomField must be a string";if(!(null==t?void 0:t.key.startsWith(op)))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},Rp={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Ap{constructor(){this.userProfile=new mp,this.userStatus=new Mp,this.userProfile.init(),this.userStatus.init(),nn({auth:Rp,params:Tp})}}function Op(e){const s=[];if(!t(e))return s;const n=e.length;if(0===n)return s;for(let t=n-1;t>=0;t--)"1"===e[t]&&s.push(2**(n-t-1));return s}var Dp,bp,Lp;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(Dp||(Dp={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(bp||(bp={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(Lp||(Lp={}));class Np{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Dp.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:e}=zt;rn.getInstance().registerWorkflowStep(Ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ts.CONVERSATION_RECOVER,this._syncConversationList,this),rn.getInstance().registerWorkflowStep(Ms.SYNC_SERVER_INFO_AFTER_LOGIN,Ts.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(ss.LOGOUT,this._reset,this),e.subscribeInnerEvent(ss.DESTROY,this._dispose,this),zt.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===Dp.RESOLVED}_syncConversationListAfterLogin(){return _e(this,void 0,void 0,function*(){return this._pagingStatus=Dp.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return _e(this,void 0,void 0,function*(){const{ssoLog:e,utils:{safeStringify:t}}=zt;e.debug("_syncConversationList","start");try{const t=yield this._pagingGetConversationList(!0);this._pagingStatus=Dp.RESOLVED;const{conversationList:s=[]}=t||{};return e.info("_syncConversationList",`success count:${s.length}`),t}catch(s){const{errorCode:n,errorInfo:o}=s,i=new Ys({code:n,message:o});e.error("_syncConversationList",`fail ${t(s)}`,{error:i})}})}_pagingGetConversationList(e){return _e(this,void 0,void 0,function*(){try{const t=[];this._pagingStatus=Dp.PENDING;const s=yield function(e){return _e(this,void 0,void 0,function*(){const{fromAccount:t,pagingTimeStamp:s,pagingStartIndex:n,pagingPinnedTimeStamp:o,pagingPinnedStartIndex:i}=e;return hn({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:t,StartIndex:n,TimeStamp:s,TopStartIndex:i,TopTimeStamp:o}})})}({fromAccount:mn(),pagingTimeStamp:e?this._pagingTimeStamp:0,pagingStartIndex:e?this._pagingStartIndex:0,pagingPinnedTimeStamp:e?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:e?this._pagingPinnedStartIndex:0}),{CompleteFlag:n,SessionItem:o=[],TimeStamp:i,StartIndex:r,TopTimeStamp:a,TopStartIndex:c}=s||{};let u=[];if(1===n&&(this._pagingStatus=Dp.RESOLVED),o.length>0&&(u=this._getConversationOptions(o),t.push(...u)),zt.notificationCenter.emitInnerEvent(ss.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:u}),this._pagingTimeStamp=i,this._pagingStartIndex=r,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=c,1!==n){const{conversationList:s}=yield this._pagingGetConversationList(e);t.push(...s)}return{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){const{utils:{isUndefined:t}}=zt,s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===bp.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===bp.C2C&&!function(e){let t;return e.startsWith(Cs.CONV_C2C)&&(t=e.replace(Cs.CONV_C2C,"")),"@TLS#ERROR"===t||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s,n,o,i,r,a,c;const u=this._createUserprofile(e);return{conversationID:`${Cs.CONV_C2C}${e.userID}`,type:Cs.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(t=e.lastMsg)||void 0===t?void 0:t.elements[0])?null===(s=e.lastMsg)||void 0===s?void 0:s.elements[0].type:null,payload:(null===(n=e.lastMsg)||void 0===n?void 0:n.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(r=null===(i=null===(o=e.lastMsg)||void 0===o?void 0:o.elements)||void 0===i?void 0:i[0])||void 0===r?void 0:r.cloudCustomData)||"",isRevoked:e.lastMessageFlag===Lp.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null===(c=null===(a=e.lastMsg)||void 0===a?void 0:a.revokerInfo)||void 0===c?void 0:c.revoker)||null},unreadCount:0,userProfile:u,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:Op(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t;const{userID:s,nick:n,peerAvatar:o}=e,i=[{tag:"Tag_Profile_IM_Nick",value:n},{tag:"Tag_Profile_IM_Image",value:o}];return null===(t=zt.user.userProfile)||void 0===t?void 0:t.createProfile(s,i)}_computeIsPeerRead(e){const t=mn(),{lastC2CMsgFromAccount:s,time:n,c2cPeerReadTime:o}=e;return s===t&&n<=o}_assembleGroupOption(e){var t,s,n,o,i;return{conversationID:`${Cs.CONV_GROUP}${e.groupID}`,type:Cs.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null===(n=null===(s=null===(t=e.lastMsg)||void 0===t?void 0:t.elements)||void 0===s?void 0:s[0])||void 0===n?void 0:n.cloudCustomData)||"",isRevoked:e.lastMessageFlag===Lp.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(i=null===(o=e.lastMsg)||void 0===o?void 0:o.revokerInfo)||void 0===i?void 0:i.revoker)||null}),groupProfile:{groupID:e.groupID,name:e.groupNick,avatar:e.groupImage,type:e.groupType,nextMessageSeq:e.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(e),peerReadTime:0,isPinned:1===e.isPinned,version:0,customData:e.customMark||"",markList:Op(e.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(e.messageRemindType),subType:e.groupType}}_convertConversationKey(e){return e.map(e=>({type:e.Type,userID:e.To_Account,nick:e.C2cNick,peerAvatar:e.C2cImage,time:e.MsgTimeStamp,sequence:e.MsgSeq,lastC2CMsgFromAccount:e.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(e.LastMsg),lastMessageFlag:e.LastMsgFlags,c2cPeerReadTime:e.C2cPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,msgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(e){var t,s,n;const{utils:{isEmpty:o}}=zt;if(o(e))return null;let i="",r=null;if(!o(e.GroupTips)){const{From_Account:s,GroupName:n}=(null===(t=e.GroupTips)||void 0===t?void 0:t.GroupInfo)||{};i=Cs.MSG_GRP_TIP,r=Object.assign(Object.assign({},this._parseContent(i,e.GroupTips.MsgBody)),{groupProfile:{from:s,groupName:n}})}return e.MsgBody&&(i=null===(s=e.MsgBody[0])||void 0===s?void 0:s.MsgType,r=this._parseContent(i,e.MsgBody[0])),{event:e.Event,elements:[{type:i,content:r,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(n=e.RevokerInfo)||void 0===n?void 0:n.Revoker_Account}}}_parseContent(e,t){var s;if(!t)return t;const n=zt.message.messageFactory.getElementClass(e);return n?null===(s=n.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return ge(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=Cs.MSG_REMIND_ACPT_AND_NOTE:1===e?t=Cs.MSG_REMIND_DISCARD:2===e?t=Cs.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=Cs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t;const{utils:{isUndefined:s}}=zt,{event:n,elements:o=[]}=e.lastMsg||{};return s(n)?{type:o[0]?o[0].type:null,payload:o[0]?this._amendLayersOverLimitProp(o[0].content):null}:{type:Cs.MSG_GRP_TIP,payload:(null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.content)||{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,n=t-s;return n>0?n:0}_reset(){this._pagingStatus=Dp.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:e}=zt;e.unSubscribeInnerEvent(ss.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(ss.DESTROY,this._dispose,this)}}class wp{constructor(){this.syncConversationHandler=new Np,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${et}`);var Pp={create:function(e){var t,s;const{SDKAppID:n,testEnv:o=!1,devMode:i=!1,unlimitedAVChatRoom:r=!1,scene:a="",oversea:c=!1,instance:u,disableIndependentDomain:l=!1,proxyServer:d=""}=e;let h=n;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(h))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(h=Number(h),an.has(h))return an.get(h);let p=null;if(u)p=u,p._workflowManager&&rn.setInstance(p._workflowManager),p._pluginManager&&p._pluginManager.installBuiltInPlugin(Vd),u.isReady()&&(null===(s=(t=rn.getInstance()).executeWorkflow)||void 0===s||s.call(t,Ms.SYNC_SERVER_INFO_AFTER_LOGIN));else{const e=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();zt.init({sdkAppId:h,instanceId:e,testEnv:o,devMode:i,unlimitedAVChatRoom:r,disableIndependentDomain:l,scene:a,oversea:c,sdkEdition:xd,version:et,proxyServer:d}),rn.getInstance().init(),zt.message=new tp,zt.user=new Ap,zt.login=new eh,zt.conversation=new wp,Bd.getInstance().installBuiltInPlugin(Vd),p=Jd.getInstance().exposeApiForClient(),p._workflowManager=rn.getInstance(),p._pluginManager=Bd.getInstance();const{utils:{IS_WORKER_AVAILABLE:t,USER_AGENT:s,getPlatformType:u,isIOSWebView:g}}=zt,_=`instanceID:${e} SDKAppID:${n} platform:${K} host:${u()} isIOSWebView:${g} workerAvailable:${t} UserAgent:${s}`;zt.ssoLog.info("sdkConstruct",_)}return an.set(h,p),p},TSignaling:ns,EVENT:es,VERSION:et,TYPES:Cs};return Pp}()}(ue);var le=X(ue.exports);const de=new t,he=Object.freeze(["onEnterRoom","onExitRoom","onSwitchRole","onError","onWarnning","onRemoteUserEnterRoom","onRemoteUserLeaveRoom","onUserVideoAvailable","onUserSubStreamAvailable","onUserAudioAvailable","onUserVoiceVolume","onNetworkQuality","onFirstVideoFrame","onSendFirstLocalVideoFrame","onSendFirstLocalAudioFrame","onMicDidReady"]);function pe(e){const t=le&&le.EVENT||{};switch(e){case"SDK_READY":return t.SDK_READY||"sdkStateReady";case"KICKED_OUT":return t.KICKED_OUT||"kickedOut";case"USER_SIG_EXPIRED":return t.USER_SIG_EXPIRED||"userSigExpired";case"ROOM_CUSTOM_DATA_RECEIVED":return t.ROOM_CUSTOM_DATA_RECEIVED;default:return null}}class ge{constructor(e){const s=e||{};this._emitter=new t,this._sdkAppId=s.SDKAppID||s.sdkAppID||0,this._userId="",this._userSig="",this._isExternalChat=!1,this._chatListenersBound=!1,this._trtcCloud=null,this._trtcListenersBound=!1,this._trtcListenerHandlers=null,this._callInfo=T(),this._callsInFlight=!1,this._terminalId="",this._viewLayout=new Y;const n=s.chat||s.tim;n&&(this._isExternalChat=!0,this._chat=n)}static createInstance(e){return ge.instance||(ge.instance=new ge(e)),ge.instance}static once(e,t){"ready"===e?"function"==typeof t&&Promise.resolve().then(()=>{try{t()}catch(e){console.error("[call-engine-wx] ready callback threw:",e)}}):de.once(e,t)}async login(e){const t=e||{},s=t.userID,n=t.userSig,o=t.sdkAppID||t.SDKAppID||this._sdkAppId;if(!s||!n)throw _e(p.ERR_FAILED,"login: userID and userSig are required");!this._sdkAppId&&o&&(this._sdkAppId=o),this._userId=s,this._userSig=n,this._bindChatListenersOnce();try{if(this._chat=le.create({SDKAppID:this._sdkAppId,devMode:!0}),this._isLogined())return void this._emitOnceReady();let e;try{e=await this._chat.login({userID:s,userSig:n});try{this.getTRTCCloudInstance()}catch(e){}}catch(e){const t=e&&e.code,s=e&&e.message||"";if(2024===t||2025===t)return console.warn("[call-engine-wx] login: tolerated lite-chat code",t,s),void this._emitOnceReady();if(this._chatReadyFired&&(/timeout/i.test(s)||"NETWORK_TIMEOUT"===t))return console.warn("[call-engine-wx] login: chat.login() rejected with",s||t,"AFTER SDK_READY — treating as success"),void this._emitOnceReady();throw e}if(e&&e.data&&e.data.repeatLogin)return void this._emitOnceReady();this._emitOnceReady()}catch(e){const t=e&&e.code||p.ERR_FAILED,s=e&&e.message||"login failed";throw this._emitter.emit(g.ERROR,{code:t,message:s}),_e(t,s)}}async logout(){this._clearCallInfo();try{this._chat&&"function"==typeof this._chat.logout&&await this._chat.logout()}finally{this._userId="",this._userSig=""}}async destroyInstance(){ge.instance=null;try{await this.logout()}catch(e){}this._unbindChatListeners(),this._unbindTRTCListeners(),this._emitter.removeAllListeners(),this._trtcCloud=null}on(e,t){this._emitter.on(e,t)}off(e,t){this._emitter.off(e,t)}once(e,t){this._emitter.once(e,t)}getTim(){return this._chat}getTRTCCloudInstance(){if(this._trtcCloud)return this._trtcCloud;if(!ce||"function"!=typeof ce.getTRTCShareInstance)throw _e(p.ERR_FAILED,"[call-engine-wx] @tencentcloud/trtc-component-wx is not installed or does not expose getTRTCShareInstance().");return this._trtcCloud=ce.getTRTCShareInstance(),this._bindTRTCListenersOnce(),this._trtcCloud}setLogLevel(e){try{this._chat&&"function"==typeof this._chat.setLogLevel&&this._chat.setLogLevel(e)}catch(e){}}async calls(t){if(console.warn("---\x3e calls 入参 ",JSON.stringify(t)),!this._isLogined()&&!this._chatReadyFired)throw _e(p.ERR_FAILED,"calls: not logged in. Call login() first and wait for SDK_READY.");if(this._callsInFlight)throw _e(p.ERR_FAILED,"calls: a previous calls() is still in progress");if(this._callInfo.status!==e.CallStatus.NONE)throw _e(p.ERR_FAILED,"calls: there is an active call already; hang up before starting a new one");if(!E(t?.userIDList)||0===t?.userIDList?.length)throw _e(p.ERR_FAILED,"calls: userIDList cannot be empty");if(t?.type!==e.CallMediaType.AUDIO&&t?.type!==e.CallMediaType.VIDEO)throw _e(p.ERR_FAILED,"calls: invalid mediaType");const s=this._getLoginUserId();if(!s)throw _e(p.ERR_FAILED,"calls: cannot resolve login user id");var n;this._callInfo=T({...t,strRoomId:(n=t?.strRoomID,n||`roomId_${Math.floor(1e6*Math.random())}`),status:e.CallStatus.WAITING,role:e.CallRole.CALLER,inviter:s}),this._callsInFlight=!0;let o=!1;try{try{await this._enterTRTCRoom(),o=!0}catch(e){this._safeLeaveTRTCRoom();const t=e&&e.code||p.ERR_FAILED,s=e&&e.message||"enter TRTC room failed";throw this._emitter.emit(g.ERROR,{code:t,message:s}),_e(t,s)}const t=await q.startCall({chat:this._chat,...this._callInfo,userIdList:this._callInfo.inviteeList});if(0!==t.errCode)throw this._safeLeaveTRTCRoom(),o=!1,this._emitter.emit(g.ERROR,{code:t.errCode,message:t.errMsg}),_e(t.errCode,t.errMsg||"start_call failed");this._callInfo.callId=t.inviteId,this._callInfo.callStartTime=Date.now();let s=0;for(const n of t.callResultList)switch(n.resultCode){case e.CallInvitationResultCodeType.INVITED:this._emitter.emit(g.USER_ENTER,n.userId);break;case e.CallInvitationResultCodeType.SUCCESS:this._emitter.emit("onUserInviting",n.userId);break;case e.CallInvitationResultCodeType.LINE_BUSY:this._emitter.emit("onUserLineBusy",n.userId),s++}if(s>=this._callInfo.inviteeList.length){const s=t.callResultList[t.callResultList.length-1];return this._safeLeaveTRTCRoom(),o=!1,this._emitter.emit(g.ON_CALL_NOT_CONNECTED,{callInfo:{...this._callInfo},userId:s?s.userId:"",reason:e.CallEndReason.LINE_BUSY}),this._clearCallInfo(),{inviteId:t.inviteId,roomId:this._callInfo,callResultList:t.callResultList}}return q.startHeartBeat({chat:this._chat,callId:this._callInfo.callId,userId:this._callInfo.inviter,onTimeout:t=>{this._callInfo.callId===t&&(this._emitter.emit(g.ON_CALL_NOT_CONNECTED,{callInfo:{...this._callInfo},userId:this._callInfo.inviter,reason:e.CallEndReason.LINE_BUSY}),this._safeLeaveTRTCRoom(),this._clearCallInfo())}}),{inviteId:t.inviteId,roomId:this._callInfo,callResultList:t.callResultList}}catch(e){throw o&&this._safeLeaveTRTCRoom(),this._clearCallInfo(),e}finally{this._callsInFlight=!1}}async accept(){if(!this._isLogined()&&!this._chatReadyFired)throw _e(p.ERR_FAILED,"accept: not logged in. Call login() first and wait for SDK_READY.");if(this._callInfo.role!==e.CallRole.CALLEE)throw _e(p.ERR_FAILED,"accept: current role is not CALLEE");if(this._callInfo.status!==e.CallStatus.WAITING)throw _e(p.ERR_FAILED,`accept: invalid call status ${this._callInfo.status}; expected WAITING`);const t=this._callInfo.callId;if(!t)throw _e(p.ERR_FAILED,"accept: no active invitation (callId is empty)");let s=!1;try{await this._enterTRTCRoom(),s=!0;const n=this._getOrCreateTerminalId(),o=await q.accept({chat:this._chat,callId:t,terminalId:n});if(0!==o.errCode)throw _e(o.errCode,o.errMsg||"handle_call(accept) failed");return this._callInfo.status=e.CallStatus.CALLING,this._callInfo.callStartTime=Date.now(),this._emitter.emit(g.ON_CALL_BEGIN,{callInfo:{...this._callInfo}}),q.startHeartBeat({chat:this._chat,callId:this._callInfo.callId,userId:this._getLoginUserId(),onTimeout:t=>{this._callInfo.callId===t&&(this._emitter.emit(g.ON_CALL_NOT_CONNECTED,{callInfo:{...this._callInfo},userId:this._getLoginUserId(),reason:e.CallEndReason.LINE_BUSY}),this._safeLeaveTRTCRoom(),this._clearCallInfo())}}),{callId:t,roomId:this._callInfo.roomId}}catch(e){s&&this._safeLeaveTRTCRoom(),this._clearCallInfo();const t=e&&e.code||p.ERR_FAILED,n=e&&e.message||"accept failed";throw this._emitter.emit(g.ERROR,{code:t,message:n}),_e(t,n)}}async reject(){if(!this._isLogined()&&!this._chatReadyFired)throw _e(p.ERR_FAILED,"reject: not logged in. Call login() first and wait for SDK_READY.");if(this._callInfo.role!==e.CallRole.CALLEE)throw _e(p.ERR_FAILED,"reject: current role is not CALLEE");if(this._callInfo.status!==e.CallStatus.WAITING)throw _e(p.ERR_FAILED,`reject: invalid call status ${this._callInfo.status}; expected WAITING`);const t=this._callInfo.callId;if(!t)throw _e(p.ERR_FAILED,"reject: no active invitation (callId is empty)");const s={...this._callInfo};try{const n=this._getOrCreateTerminalId(),o=await q.reject({chat:this._chat,callId:t,terminalId:n});return 0!==o.errCode&&console.warn("[call-engine-wx] reject: backend reported error",o.errCode,o.errMsg),this._emitter.emit(g.ON_CALL_END,{callInfo:s,reason:e.CallEndReason.REJECT,userId:this._getLoginUserId()}),{callId:t}}finally{this._clearCallInfo()}}async hangup(){if(!this._isLogined()&&!this._chatReadyFired)throw _e(p.ERR_FAILED,"hangup: not logged in. Call login() first and wait for SDK_READY.");if(this._callInfo.status!==e.CallStatus.CALLING&&this._callInfo.status!==e.CallStatus.WAITING)throw _e(p.ERR_FAILED,`hangup: invalid call status ${this._callInfo.status}; expected CALLING or WAITING`);const t=this._callInfo.callId;if(!t)throw _e(p.ERR_FAILED,"hangup: no active call (callId is empty)");const s=this._callInfo.role===e.CallRole.CALLER&&this._callInfo.status===e.CallStatus.WAITING,n={...this._callInfo};try{if(s){const e=this._callInfo.inviter||this._getLoginUserId(),s=Array.isArray(this._callInfo.inviteeList)?this._callInfo.inviteeList.slice():[];if(s.length>0){const n=await q.cancel({chat:this._chat,inviter:e,callId:t,calleeList:s});0!==n.errCode&&console.warn("[call-engine-wx] hangup(cancel): backend reported error",n.errCode,n.errMsg)}}else{const e=this._getOrCreateTerminalId(),s=await q.hangup({chat:this._chat,callId:t,terminalId:e});0!==s.errCode&&console.warn("[call-engine-wx] hangup: backend reported error",s.errCode,s.errMsg)}return this._safeLeaveTRTCRoom(),this._emitter.emit(g.ON_CALL_END,{callInfo:n,reason:s?e.CallEndReason.CANCELED:e.CallEndReason.HANGUP,userId:this._getLoginUserId()}),{callId:t}}finally{this._clearCallInfo()}}setLayoutTemplate(e){this._viewLayout.setLayoutTemplate(e),this._recalcAndEmitLayout()}setLargeViewUser(e){this._viewLayout.setLargeViewUser(e),this._recalcAndEmitLayout()}toggleViewReversed(){this._viewLayout.toggleViewReversed(),this._recalcAndEmitLayout()}_buildLayoutState(){const t=this._getLoginUserId()||"",s=this._callInfo||{},n=s.inviter||"",o=Array.isArray(s.inviteeList)?s.inviteeList:[],i="number"==typeof s.status?s.status:j.NONE,r=new Set,a=[],c=(e,t)=>{e&&!r.has(e)&&(r.add(e),a.push({id:e,status:t}))};c(t,i),n&&c(n,i);for(const e of o)c(e,i);return{selfId:t,selfStatus:i,mediaType:"number"==typeof s.mediaType?s.mediaType:e.CallMediaType.VIDEO,allParticipants:a,inviter:n,inviteeList:o}}_recalcAndEmitLayout(){try{this._viewLayout.recalculate(this._buildLayoutState())&&this._emitter.emit(g.VIEW_LAYOUT_CHANGED,this._viewLayout.toJsonObject())}catch(e){console.warn("[call-engine-wx] _recalcAndEmitLayout failed:",e&&e.message)}}async openCamera(e,t){let s;if(s=void 0===t?-1:t?1:0,C(this?._trtcCloud?.startLocalPreview))return this._trtcCloud.startLocalPreview(e,s)}async closeCamera(){if(C(this?._trtcCloud?.stopLocalPreview))return this._trtcCloud.stopLocalPreview()}async switchCamera(e){C(this?._trtcCloud?.switchCamera)&&await this._trtcCloud.switchCamera(!!e)}async openMicrophone(){C(this?._trtcCloud?.startLocalAudio)&&await this._trtcCloud.startLocalAudio()}async closeMicrophone(){C(this?._trtcCloud?.stopLocalAudio)&&await this._trtcCloud.stopLocalAudio()}async selectAudioPlaybackDevice(t){if(!C(this?._trtcCloud?.setAudioRoute))return;const s=t===e.AudioPlayBackDevice.EAR||1===t?e.AudioPlayBackDevice.EAR:e.AudioPlayBackDevice.SPEAKER;await this._trtcCloud.setAudioRoute(s)}async startRemoteView(e){if(!this._trtcCloud||"function"!=typeof this._trtcCloud.startRemoteView)return;const{userId:t,view:s,streamType:n=0}=e||{};return this._trtcCloud.startRemoteView(t,s,n)}async stopRemoteView(e){if(!this._trtcCloud||"function"!=typeof this._trtcCloud.stopRemoteView)return;const{userId:t,streamType:s=0}=e||{};return this._trtcCloud.stopRemoteView(t,s)}_bindChatListenersOnce(){if(this._chatListenersBound||!this._chat||"function"!=typeof this._chat.on)return;const t=pe("SDK_READY"),s=pe("KICKED_OUT"),n=pe("USER_SIG_EXPIRED"),o=pe("ROOM_CUSTOM_DATA_RECEIVED");this._onChatReady=()=>{this._chatReadyFired=!0,this._emitOnceReady()},this._onChatKickedOut=e=>{this._emitter.emit(g.KICKED_OUT,e||{})},this._onChatUserSigExpired=()=>{this._emitter.emit(g.onUserSigExpired,{})},this._onChatRoomCustomDataReceived=t=>{const{Data:s={},Head:n={}}=JSON.parse(t.data);if("call_engine_srv.invite_user_notify"===n?.Command){const{CallInfo:t={}}=s;let n={intRoomId:0,strRoomId:""};if(1===t.RoomIdType)n.intRoomId=Number(t.RoomId);else{if(2!==t.RoomIdType)return;n.strRoomId=t.RoomId}this._callInfo=T({userIDList:s?.CalleeList_Account||[],callId:s?.CallInfo?.CallId||"",inviter:s?.Caller_Account||"",roomId:n.intRoomId||0,strRoomId:n.strRoomId||"",groupId:s?.CallInfo?.GroupId||"",type:s?.CallInfo?.CallMediaType,status:e.CallStatus.WAITING,role:e.CallRole.CALLEE}),this._emitter.emit(g.ON_CALL_RECEIVED,{callId:this._callInfo.callId,inviter:this._callInfo.inviter,inviteeList:this._callInfo.inviteeList,groupId:this._callInfo.groupId,mediaType:this._callInfo.mediaType,roomId:this._callInfo.roomId,userData:s?.UserData||"",callInfo:{...this._callInfo}})}},t&&this._chat.on(t,this._onChatReady),s&&this._chat.on(s,this._onChatKickedOut),n&&this._chat.on(n,this._onChatUserSigExpired),o&&this._chat.on(o,this._onChatRoomCustomDataReceived),this._chatListenersBound=!0}_unbindChatListeners(){if(!this._chatListenersBound||!this._chat||"function"!=typeof this._chat.off)return;const e=pe("SDK_READY"),t=pe("KICKED_OUT"),s=pe("USER_SIG_EXPIRED"),n=pe("ROOM_CUSTOM_DATA_RECEIVED");try{e&&this._onChatReady&&this._chat.off(e,this._onChatReady)}catch(e){}try{t&&this._onChatKickedOut&&this._chat.off(t,this._onChatKickedOut)}catch(e){}try{s&&this._onChatUserSigExpired&&this._chat.off(s,this._onChatUserSigExpired)}catch(e){}try{n&&this._onChatRoomCustomDataReceived&&this._chat.off(n,this._onChatRoomCustomDataReceived)}catch(e){}this._chatListenersBound=!1}_bindTRTCListenersOnce(){if(this._trtcListenersBound||!this._trtcCloud)return;const t=this._trtcCloud;if("function"!=typeof t.on)return;const s={},n=e=>(...t)=>{try{this._emitter.emit(e,...t)}catch(t){console.warn("[call-engine-wx] listener for",e,"threw:",t)}};for(const o of he){let i;if("onRemoteUserEnterRoom"===o){const t=n(o);i=(...s)=>{try{this._callInfo&&this._callInfo.callId&&this._callInfo.status===e.CallStatus.WAITING&&(this._callInfo.status=e.CallStatus.CALLING,this._callInfo.callStartTime||(this._callInfo.callStartTime=Date.now()),this._emitter.emit(g.ON_CALL_BEGIN,{callInfo:{...this._callInfo}}))}catch(e){console.warn("[call-engine-wx] ON_CALL_BEGIN gate threw:",e)}t(...s)}}else i=n(o);s[o]=i;try{t.on(o,i)}catch(e){}}this._trtcListenerHandlers=s,this._trtcListenersBound=!0}_unbindTRTCListeners(){if(!this._trtcListenersBound)return;const e=this._trtcCloud,t=this._trtcListenerHandlers||{};if(e&&"function"==typeof e.off)for(const s of Object.keys(t))try{e.off(s,t[s])}catch(e){}this._trtcListenerHandlers=null,this._trtcListenersBound=!1}_emitOnceReady(){this._readyEmitted||(this._readyEmitted=!0,this._emitter.emit(g.SDK_READY,{name:"sdk_ready"}),this._fetchPendingInvitation().catch(e=>{console.warn("[call-engine-wx] _fetchPendingInvitation: unexpected error",e)}))}async _fetchPendingInvitation(){if(!this._chat||!this._isLogined())return;if(this._callInfo&&this._callInfo.callId)return;const e=this._getLoginUserId();if(!e)return;let t;try{t=await q.getInvitation({chat:this._chat,userId:e})}catch(e){return void console.warn("[call-engine-wx] getInvitation request threw:",e)}if(t&&0===t.errCode&&t.data)try{const e={data:JSON.stringify({Data:t.data,Head:{Command:"call_engine_srv.invite_user_notify"}})};C(this._onChatRoomCustomDataReceived)&&this._onChatRoomCustomDataReceived(e)}catch(e){console.warn("[call-engine-wx] replay pending invitation failed:",e)}}_isLogined(){try{if(!this._chat)return!1;if("function"==typeof this._chat.getLoginUser)return!!this._chat.getLoginUser()}catch(e){}return!1}_getLoginUserId(){return this._userId?this._userId:C(this?._chat?.getLoginUser)&&this._chat.getLoginUser()||""}async _enterTRTCRoom(){try{q.stopHeartBeat()}catch(e){}if(this._callInfo.callType===e.CallMediaType.UNKNOWN)throw _e(-1,"call type is none");const{roomId:t}=this._callInfo;if(0===t.intRoomId&&""===t.strRoomId)throw _e(-1,"room id is empty");const s={sdkAppId:this._sdkAppId,userId:this._getLoginUserId(),userSig:this._userSig,role:20};t.intRoomId>0?s.roomId=t.intRoomId:s.strRoomId=t.strRoomId;const n=this._callInfo.mediaType===e.CallMediaType.VIDEO?0:2,o=this.getTRTCCloudInstance();await new Promise((e,t)=>{let i=!1,r=null;const a=()=>{r&&(clearTimeout(r),r=null);try{this._emitter.off("onEnterRoom",c)}catch(e){}},c=s=>{i||(i=!0,a(),"number"==typeof s&&s>0?e():t(_e("number"==typeof s?s:-1,`enterRoom failed: ${s}`)))};this._emitter.on("onEnterRoom",c),r=setTimeout(()=>{i||(i=!0,a(),t(_e(-1,"enterRoom timeout")))},1e4);try{const e=o.enterRoom(s,n);e&&"function"==typeof e.catch&&e.catch(e=>{i||(i=!0,a(),t(e))})}catch(e){if(i)return;i=!0,a(),t(e)}})}_safeLeaveTRTCRoom(){try{this._trtcCloud&&"function"==typeof this._trtcCloud.exitRoom&&this._trtcCloud.exitRoom()}catch(e){}}_clearCallInfo(){try{q.stopHeartBeat()}catch(e){}this._callInfo=T()}_getOrCreateTerminalId(){return this._terminalId||(this._terminalId=function(){const e=new Array(16),t="undefined"!=typeof crypto&&crypto||null;if(t&&"function"==typeof t.getRandomValues){const s=new Uint8Array(16);t.getRandomValues(s);for(let t=0;t<16;t++)e[t]=s[t]}else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());const s=e.map(e=>e.toString(16).padStart(2,"0")).join("").toUpperCase();return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20,32)}`}()),this._terminalId}}function _e(e,t){const s=new Error(t);return s.code=e,s}ge.instance=null,e.CallInvitationRespondedType=h,e.TUICallEngine=ge,e.TUICallEvent=g,e.TUIErrorCode=p,e.TencentCloudChat=le,e.default=ge,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@tencentcloud/trtc-component-wx"),require("@tencentcloud/lite-chat/basic")):"function"==typeof define&&define.amd?define(["exports","@tencentcloud/trtc-component-wx","@tencentcloud/lite-chat/basic"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CallsEngineWX={},e.TRTCComponentWX,e.TencentCloudChat)}(this,function(e,t,r){"use strict";class a{constructor(){this._handlers=new Map}on(e,t){if("function"!=typeof t)return this;let r=this._handlers.get(e);return r||(r=[],this._handlers.set(e,r)),r.push({fn:t,once:!1}),this}once(e,t){if("function"!=typeof t)return this;let r=this._handlers.get(e);return r||(r=[],this._handlers.set(e,r)),r.push({fn:t,once:!0}),this}off(e,t){if(!e)return this._handlers.clear(),this;const r=this._handlers.get(e);if(!r)return this;if(!t)return this._handlers.delete(e),this;const a=r.filter(e=>e.fn!==t);return 0===a.length?this._handlers.delete(e):this._handlers.set(e,a),this}emit(e,...t){const r=this._handlers.get(e);if(!r||0===r.length)return!1;const a=r.slice();for(const r of a){try{r.fn.apply(null,t)}catch(e){console.error("[call-engine-wx] listener threw:",e)}r.once&&this.off(e,r.fn)}return!0}removeAllListeners(e){return e?this._handlers.delete(e):this._handlers.clear(),this}listenerCount(e){const t=this._handlers.get(e);return t?t.length:0}}var o,i,s,n,l,c,d,h,u,I;e.CallStatus=void 0,(o=e.CallStatus||(e.CallStatus={}))[o.NONE=0]="NONE",o[o.WAITING=1]="WAITING",o[o.CALLING=2]="CALLING",e.CallRole=void 0,(i=e.CallRole||(e.CallRole={}))[i.NONE=0]="NONE",i[i.CALLER=1]="CALLER",i[i.CALLEE=2]="CALLEE",e.CallMediaType=void 0,(s=e.CallMediaType||(e.CallMediaType={}))[s.UNKNOWN=0]="UNKNOWN",s[s.AUDIO=1]="AUDIO",s[s.VIDEO=2]="VIDEO",e.CallScene=void 0,(n=e.CallScene||(e.CallScene={}))[n.NONE=0]="NONE",n[n.GROUP=1]="GROUP",n[n.MULTI=2]="MULTI",n[n.SINGLE=3]="SINGLE",e.IOSOfflinePushType=void 0,(l=e.IOSOfflinePushType||(e.IOSOfflinePushType={}))[l.APNs=0]="APNs",l[l.VoIP=1]="VoIP",e.CallInvitationResultCodeType=void 0,(c=e.CallInvitationResultCodeType||(e.CallInvitationResultCodeType={}))[c.SUCCESS=0]="SUCCESS",c[c.INVITED=1]="INVITED",c[c.LINE_BUSY=2]="LINE_BUSY",e.CallEndReason=void 0,(d=e.CallEndReason||(e.CallEndReason={}))[d.UNKNOWN=0]="UNKNOWN",d[d.HANGUP=1]="HANGUP",d[d.REJECT=2]="REJECT",d[d.NO_RESPONSE=3]="NO_RESPONSE",d[d.OFFLINE=4]="OFFLINE",d[d.LINE_BUSY=5]="LINE_BUSY",d[d.CANCELED=6]="CANCELED",d[d.OTHER_DEVICE_ACCEPTED=7]="OTHER_DEVICE_ACCEPTED",d[d.OTHER_DEVICE_REJECT=8]="OTHER_DEVICE_REJECT",d[d.END_BY_SERVER=9]="END_BY_SERVER",e.LOG_LEVEL=void 0,(h=e.LOG_LEVEL||(e.LOG_LEVEL={}))[h.DEBUG=0]="DEBUG",h[h.INFO=1]="INFO",h[h.WARN=2]="WARN",h[h.ERROR=3]="ERROR",h[h.NONE=4]="NONE",e.CameraPosition=void 0,(u=e.CameraPosition||(e.CameraPosition={}))[u.FRONT=1]="FRONT",u[u.BACK=0]="BACK",e.AudioPlayBackDevice=void 0,(I=e.AudioPlayBackDevice||(e.AudioPlayBackDevice={}))[I.SPEAKER=0]="SPEAKER",I[I.EAR=1]="EAR";const f=Object.freeze({None:0,AcceptedByInvitee:1,RejectedByInvitee:2,NoResponseUntilTimeout:3,Hangup:4,Join:5,Offline:6,InviteUser:7}),_=Object.freeze({ERR_FAILED:-1}),m=Object.freeze({ERROR:"onError",SDK_READY:"sdkReady",KICKED_OUT:"onKickedOffline",onUserSigExpired:"onUserSigExpired",ON_CALL_BEGIN:"onCallBegin",ON_CALL_END:"onCallEnd",ON_CALL_RECEIVED:"onCallReceived",ON_CALL_CANCELED:"onCallCanceled",ON_CALL_NOT_CONNECTED:"onCallNotConnected",INVITED:"onInvited",USER_ENTER:"onUserJoin",USER_LEAVE:"onUserLeave",VIEW_LAYOUT_CHANGED:"viewLayoutChanged"}),C="number",y="object",E="array",p="function",L=function(e){return typeof e===C},R=function(e){return typeof Array.isArray===p?Array.isArray(e):T(e)===E},g=function(e){return typeof e===p},T=function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()};let A=null;const v=function(e){const t=function(){if(A)return A;const e={osName:"Unknown",osVersion:"0.0.0",deviceName:"Unknown"};try{const t="undefined"!=typeof wx?wx:null,r="undefined"!=typeof uni?uni:null;if(t&&"function"==typeof t.getSystemInfoSync){const r=t.getSystemInfoSync()||{},[a="Unknown",o="0.0.0"]=String(r.system||"").split(" ");e.osName=a,e.osVersion=o,e.deviceName=r.model||r.brand||"Unknown"}else if(r&&"function"==typeof r.getSystemInfoSync){const t=r.getSystemInfoSync()||{},[a="Unknown",o="0.0.0"]=String(t.system||"").split(" ");e.osName=a,e.osVersion=o,e.deviceName=t.model||t.brand||"Unknown"}else if("undefined"!=typeof navigator&&navigator.userAgent){const t=navigator.userAgent;if(/Mac OS X/i.test(t)){e.osName="MacOS";const r=t.match(/Mac OS X ([\d_\.]+)/);e.osVersion=r?r[1].replace(/_/g,"."):"0.0.0",e.deviceName="Mac"}else if(/Windows/i.test(t)){e.osName="Windows";const r=t.match(/Windows NT ([\d\.]+)/);e.osVersion=r?r[1]:"0.0.0",e.deviceName="PC"}else if(/Android/i.test(t)){e.osName="Android";const r=t.match(/Android ([\d\.]+)/);e.osVersion=r?r[1]:"0.0.0",e.deviceName="Android"}else if(/iPhone|iPad|iPod/i.test(t)){e.osName="iOS";const r=t.match(/OS ([\d_]+)/);e.osVersion=r?r[1].replace(/_/g,"."):"0.0.0",e.deviceName=/iPad/i.test(t)?"iPad":"iPhone"}}}catch(e){}return A=e,e}();return{Command:e,DeviceName:t.deviceName,LongPollingKey:"",OSName:t.osName,OSVersion:t.osVersion,RoomId:"",SdkVersion:"1.0.0.0",Version:2}},w=function(t={}){let r=e.CallScene.NONE;const a=t.userIDList||[];return a.length>1&&(r=e.CallScene.MULTI),1===a.length&&(r=e.CallScene.SINGLE),{callId:t.callId||"",roomId:{strRoomId:t.strRoomID||t.strRoomId||"",intRoomId:t.roomID||t.roomId||0},inviter:t.inviter||"",inviteeList:a,groupId:t.chatGroupID||"",mediaType:t.type,status:t.status||e.CallStatus.NONE,role:t.role||e.CallRole.NONE,scene:r,callStartTime:0}},N=Object.freeze({IntRoomId:1,StrRoomId:2});function O(t,r){const a={Title:(t=t||{}).title||"",Sound:t.iosSound||"",BadgeMode:t.ignoreIosBadge?1:0,IsVoipPush:t.iosPushType||0,ContentAvailable:t.enableIosBackgroundNotification?1:0,InterruptionLevel:t.iosInterruptionLevel||"",Image:t.iosImage||""},o={Sound:t.androidSound||"",Title:t.title||"",OPPOChannelID:t.androidOppoChannelId||"",OPPOCategory:t.oppoCategory||"IM",OPPONotifyLevel:t.oppoNotifyLevel||0,GoogleChannelID:t.androidFcmChannelId||"",GoogleImage:t.fcmImage||"",XiaoMiChannelID:t.androidXiaomiChannelId||"",VIVOClassification:t.androidVivoClassification||0,VIVOCategory:t.vivoCategory||"IM",HuaWeiCategory:t.androidHuaweiCategory||"IM",HuaWeiImage:t.huaweiImage||"",HonorImportance:t.honorImportance||"NORMAL",HonorImage:t.honorImage||""},i={entity:{action:2},timPushFeatures:{fcmPushType:0,fcmNotificationType:1},voip_ext:{voip_type:"call",voip_media_type:r===e.CallMediaType.VIDEO?"video":"audio"}};return{Title:t.title||"",Description:t.description||"",Ext:JSON.stringify(i),AndroidInfo:o,ApnsInfo:a}}const D="sendTRTCCustomData",S="call_engine_srv.start_call",U="call_engine_srv.heart_beat",M="call_engine_srv.handle_call",P="call_engine_srv.hangup",V="call_engine_srv.cancel_invite",x="call_engine_srv.get_invitation",b=-1,F={errCode:0,errMsg:"",inviteId:"",callResultList:[]};let G=null,B="",k=0;function H(){G&&(clearInterval(G),G=null),B="",k=0}async function K(e,t){const r=e||{},a=r.chat;if(!a||!g(a.callExperimentalAPI))return{errCode:b,errMsg:"chat.callExperimentalAPI is not available"};if(!r.callId)return{errCode:b,errMsg:"callId is required"};if(!r.terminalId)return{errCode:b,errMsg:"terminalId is required"};let o=M;t===f.Hangup&&(o=P);const i=function(e,t,r,a){return{Body:{CallId:e||"",TerminalId:t||"",ActionType:r>>>0},Head:v(a)}}(r.callId,r.terminalId,t,o);try{const e={serviceCommand:o,data:JSON.stringify(i)},t=await a.callExperimentalAPI(D,e),r=t&&t.data||t||{},s=L(r.ErrorCode)?r.ErrorCode:L(r.errorCode)?r.errorCode:0;return 0!==s?{errCode:s,errMsg:r.ErrorInfo||r.errorInfo||""}:{errCode:0,errMsg:""}}catch(e){return{errCode:e&&(e.code||e.errorCode)||b,errMsg:e&&(e.message||e.errorInfo)||"send failed"}}}const W={CMD_START_CALL:S,CMD_HEART_BEAT:U,CMD_HANDLE_CALL:M,CMD_HANGUP_CALL:P,CMD_CANCEL_CALL:V,CMD_GET_INVITATION:x,HEARTBEAT_INTERVAL_MS:2e3,HEARTBEAT_FAIL_RETRY_DEFAULT:5,HEARTBEAT_FAIL_INTERVAL_MS:2e3,startCall:async function(t){const r=t||{},a=r.chat;if(!a||!g(a.callExperimentalAPI))return{...F,errCode:b,errMsg:"chat.callExperimentalAPI is not available"};if(!r.inviter)return{...F,errCode:b,errMsg:"inviter is required"};if(!R(r.userIdList)||0===r.userIdList.length)return{...F,errCode:b,errMsg:"userIdList cannot be empty"};if(r.mediaType!==e.CallMediaType.AUDIO&&r.mediaType!==e.CallMediaType.VIDEO)return{...F,errCode:b,errMsg:"invalid mediaType"};const o={roomId:r.roomId||{},timeout:r.timeout,userData:r.userData,isEphemeralCall:!!r.isEphemeralCall,offlinePushInfo:r.offlinePushInfo},i=function(e,t,r,a,o){const i=a||{},s=i.roomId||{},n={CallId:"",CallMediaType:r>>>0};"number"==typeof s.intRoomId&&s.intRoomId>0?(n.RoomId=String(s.intRoomId),n.RoomIdType=N.IntRoomId):(!s.intRoomId||0===s.intRoomId)&&"string"==typeof s.strRoomId&&s.strRoomId.length>0&&(n.RoomId=s.strRoomId,n.RoomIdType=N.StrRoomId),n.ExcludeFromHistoryMessage=!1,n.GroupId=o||"",n.IsEphemeralCall=!!i.isEphemeralCall;const l="number"==typeof i.timeout?i.timeout:30;return{Body:{Caller_Account:e,CalleeList_Account:(t||[]).slice(),CallInfo:n,Timeout:1e3*l,UserData:i.userData||"",OfflinePushInfo:O(i.offlinePushInfo,r)},Head:v("call_engine_srv.start_call")}}(r.inviter,r.userIdList,r.mediaType,o,r.groupId||"");let s;try{const e={serviceCommand:S,data:JSON.stringify(i)};s=await a.callExperimentalAPI(D,e)}catch(e){const t=e&&(e.code||e.errorCode)||b,r=e&&(e.message||e.errorInfo)||"send failed";return{...F,errCode:t,errMsg:r}}const n=s&&s.data||s||{};return 0!==n.ErrorCode?{...F,errCode:n.ErrorCode,errMsg:n.ErrorInfo}:{errCode:n?.ErrorCode||0,errMsg:n?.errMsg||"",inviteId:n?.Response?.CallId||"",callResultList:n?.Response?.CallResult||[]}},startHeartBeat:function(e){const t=e||{},{chat:r,callId:a,userId:o}=t;if(!r||!g(r.callExperimentalAPI))return void console.warn("[SSOChannel] startHeartBeat: chat.callExperimentalAPI unavailable");if(!a||!o)return void console.warn("[SSOChannel] startHeartBeat: callId and userId are required");H();const i=L(t.intervalMs)&&t.intervalMs>0?t.intervalMs:2e3,s=L(t.retryCount)&&t.retryCount>0?t.retryCount:5;B=a,G=setInterval(async()=>{if(!B||B!==a)return;const e=await async function(e,t,r){const a={Body:{User_Account:r,CallId:t},Head:v(U)};try{const t={serviceCommand:U,data:JSON.stringify(a)},r=await e.callExperimentalAPI(D,t),o=r&&r.data||r||{},i=L(o.ErrorCode)?o.ErrorCode:L(o.errorCode)?o.errorCode:0;return 0!==i?{errCode:i,errMsg:o.ErrorInfo||o.errorInfo||""}:{errCode:0,errMsg:""}}catch(e){return{errCode:e&&(e.code||e.errorCode)||b,errMsg:e&&(e.message||e.errorInfo)||"send failed"}}}(r,a,o);if(B&&B===a)if(0!==e.errCode){if(k+=1,console.warn("[SSOChannel] heartbeat failed",k,e.errCode,e.errMsg),k>=s){const e=B;if(H(),"function"==typeof t.onTimeout)try{t.onTimeout(e)}catch(e){}}}else k=0},i)},stopHeartBeat:H,accept:async function(e){return K(e,f.AcceptedByInvitee)},reject:async function(e){return K(e,f.RejectedByInvitee)},hangup:async function(e){return K(e,f.Hangup)},cancel:async function(e){const t=e||{},r=t.chat;if(!r||!g(r.callExperimentalAPI))return{errCode:b,errMsg:"chat.callExperimentalAPI is not available"};if(!t.callId)return{errCode:b,errMsg:"callId is required"};if(!t.inviter)return{errCode:b,errMsg:"inviter is required"};if(!R(t.calleeList)||0===t.calleeList.length)return{errCode:b,errMsg:"calleeList cannot be empty"};const a=(o=t.inviter,i=t.callId,s=t.calleeList,n=V,{Body:{CallId:i||"",Operator_Account:o||"",CalleeList_Account:Array.isArray(s)?s.filter(Boolean):[]},Head:v(n)});var o,i,s,n;try{const e={serviceCommand:V,data:JSON.stringify(a)},t=await r.callExperimentalAPI(D,e),o=t&&t.data||t||{},i=L(o.ErrorCode)?o.ErrorCode:L(o.ErrorCode)?o.errorCode:0;return 0!==i?{errCode:i,errMsg:o.ErrorInfo||o.errorInfo||""}:{errCode:0,errMsg:""}}catch(e){return{errCode:e&&(e.code||e.errorCode)||b,errMsg:e&&(e.message||e.errorInfo)||"send failed"}}},getInvitation:async function(e){const t=e||{},r=t.chat;if(!r||!g(r.callExperimentalAPI))return{errCode:b,errMsg:"chat.callExperimentalAPI is not available",data:null};if(!t.userId)return{errCode:b,errMsg:"userId is required",data:null};const a={Body:{User_Account:t.userId||""},Head:v(x)};var o;try{const e={serviceCommand:x,data:JSON.stringify(a)},t=await r.callExperimentalAPI(D,e),i=t&&t.data||t||{},s=L(i.ErrorCode)?i.ErrorCode:L(i.ErrorCode)?i.errorCode:0;if(0!==s)return{errCode:s,errMsg:i.ErrorInfo||i.errorInfo||"",data:null};const n=i?.Response;return n&&(null!==(o=n)&&typeof o===y)&&0!==Object.keys(n).length?{errCode:0,errMsg:"",data:n}:{errCode:0,errMsg:"",data:null}}catch(e){return{errCode:e&&(e.code||e.errorCode)||b,errMsg:e&&(e.message||e.errorInfo)||"send failed",data:null}}}};var j,Y;e.LayoutTemplate=void 0,(j=e.LayoutTemplate||(e.LayoutTemplate={}))[j.FLOAT=0]="FLOAT",j[j.GRID=1]="GRID",function(e){e[e.NONE=0]="NONE",e[e.WAITING=1]="WAITING",e[e.CALLING=2]="CALLING"}(Y||(Y={}));const J=720,q=1280,$={x:480,y:80,w:200,h:300};class X{constructor(){this.currentTemplate=e.LayoutTemplate.FLOAT,this.largeViewUserId="",this.isViewReversed=!1,this.currentLayout=Q(),this.previousLayout=Q()}setLayoutTemplate(e){this.currentTemplate=e,this.largeViewUserId="",this.isViewReversed=!1}setLargeViewUser(e){this.largeViewUserId===e?this.largeViewUserId="":this.largeViewUserId=e}toggleViewReversed(){this.isViewReversed=!this.isViewReversed}getCurrentTemplate(){return this.currentTemplate}getCurrentLayout(){return this.currentLayout}recalculate(t){switch(this.previousLayout=this.currentLayout,this.currentTemplate){case e.LayoutTemplate.FLOAT:this.currentLayout=this.calculateFloatLayout(t);break;case e.LayoutTemplate.GRID:this.currentLayout=this.calculateGridLayout(t)}return this.isLayoutChanged()}toJson(){return JSON.stringify(this.toJsonObject())}toJsonObject(){const t=this.currentLayout,r={template:z(t.template)};return t.template===e.LayoutTemplate.FLOAT?(r.canvas={w:t.canvas.w,h:t.canvas.h},r.primaryUser={userId:t.primaryUser.userId,isLocal:t.primaryUser.isLocal},t.secondaryUser?r.secondaryUser={userId:t.secondaryUser.userId,isLocal:t.secondaryUser.isLocal,frame:{...t.secondaryUser.frame}}:r.secondaryUser=null,r.showRemoteInfo=t.showRemoteInfo):(r.canvas={w:t.canvas.w,h:t.canvas.h},r.participants=t.participants.map(e=>({userId:e.userId,frame:{...e.frame},isLocal:e.isLocal,showName:e.showName}))),r}isLayoutChanged(){const t=this.previousLayout,r=this.currentLayout;if(t.template!==r.template)return!0;if(r.template===e.LayoutTemplate.FLOAT&&t.template===e.LayoutTemplate.FLOAT){if(t.primaryUser.userId!==r.primaryUser.userId)return!0;return(t.secondaryUser?t.secondaryUser.userId:"")!==(r.secondaryUser?r.secondaryUser.userId:"")||t.showRemoteInfo!==r.showRemoteInfo}if(r.template===e.LayoutTemplate.GRID&&t.template===e.LayoutTemplate.GRID){if(t.participants.length!==r.participants.length)return!0;for(let e=0;e<r.participants.length;e++){const a=t.participants[e],o=r.participants[e];if(a.userId!==o.userId)return!0;if(a.frame.x!==o.frame.x)return!0;if(a.frame.y!==o.frame.y)return!0;if(a.frame.w!==o.frame.w)return!0;if(a.frame.h!==o.frame.h)return!0;if(a.showName!==o.showName)return!0}return!1}return!0}calculateFloatLayout(t){const r=t.selfId;let a="";for(const e of t.allParticipants)if(e.id!==r){a=e.id;break}const o=t.selfStatus===Y.CALLING,i=t.mediaType===e.CallMediaType.AUDIO;let s,n,l,c;return o||i?!o&&i||i?(s=a,n=!1,l=null,c=!0):(this.isViewReversed?(s=r,n=!0,l={userId:a,isLocal:!1,frame:{...$}}):(s=a,n=!1,l={userId:r,isLocal:!0,frame:{...$}}),c=!1):(s=r,n=!0,l=null,c=!0),{template:e.LayoutTemplate.FLOAT,canvas:{w:J,h:q},primaryUser:{userId:s,isLocal:n},secondaryUser:l,showRemoteInfo:c}}calculateGridLayout(t){const r=new Map;for(const e of t.allParticipants)r.set(e.id,e.status);const a=[];if(t.inviter){const e=r.get(t.inviter);void 0!==e&&e!==Y.NONE&&a.push(t.inviter)}for(const e of t.inviteeList){const t=r.get(e);void 0!==t&&t!==Y.NONE&&a.push(e)}const o=this.calculateGridPositions(a.length,a,t.selfId);return{template:e.LayoutTemplate.GRID,canvas:{w:J,h:q},participants:o}}calculateGridPositions(e,t,r){const a=[];if(e<=0)return a;const o=240,i=360;let s=-1;if(this.largeViewUserId)for(let r=0;r<e;r++)if(t[r]===this.largeViewUserId){s=r;break}if(s>=0&&e<=4){const i=[s];for(let t=0;t<e;t++)t!==s&&i.push(t);const n=o,l=e-1,c=[{x:0,y:0,w:J,h:J}],d=J;for(let e=0;e<l;e++)c.push({x:e*n,y:d,w:n,h:n});for(let e=0;e<i.length&&e<c.length;e++){const o=t[i[e]];a.push({userId:o,frame:c[e],isLocal:o===r,showName:0===e})}return a}if(s>=0&&e>4){const i=480,n=480,l=[s];for(let t=0;t<e;t++)t!==s&&l.push(t);{const e=t[l[0]];a.push({userId:e,frame:{x:0,y:0,w:i,h:n},isLocal:e===r,showName:!0})}let c=1;if(c<l.length){const e=t[l[c]];a.push({userId:e,frame:{x:i,y:0,w:o,h:o},isLocal:e===r,showName:!1}),c++}if(c<l.length){const e=t[l[c]];a.push({userId:e,frame:{x:i,y:o,w:o,h:o},isLocal:e===r,showName:!1}),c++}let d=n;for(;c<l.length;){for(let e=0;e<3&&c<l.length;e++){const i=t[l[c]];a.push({userId:i,frame:{x:e*o,y:d,w:o,h:o},isLocal:i===r,showName:!1}),c++}d+=o}return a}if(1===e)a.push({userId:t[0],frame:{x:0,y:0,w:J,h:q},isLocal:t[0]===r,showName:!1});else if(2===e)a.push({userId:t[0],frame:{x:0,y:0,w:i,h:i},isLocal:t[0]===r,showName:!1}),a.push({userId:t[1],frame:{x:i,y:0,w:i,h:i},isLocal:t[1]===r,showName:!1});else if(3===e)a.push({userId:t[0],frame:{x:0,y:0,w:i,h:i},isLocal:t[0]===r,showName:!1}),a.push({userId:t[1],frame:{x:i,y:0,w:i,h:i},isLocal:t[1]===r,showName:!1}),a.push({userId:t[2],frame:{x:180,y:i,w:i,h:i},isLocal:t[2]===r,showName:!1});else if(4===e)a.push({userId:t[0],frame:{x:0,y:0,w:i,h:i},isLocal:t[0]===r,showName:!1}),a.push({userId:t[1],frame:{x:i,y:0,w:i,h:i},isLocal:t[1]===r,showName:!1}),a.push({userId:t[2],frame:{x:0,y:i,w:i,h:i},isLocal:t[2]===r,showName:!1}),a.push({userId:t[3],frame:{x:i,y:i,w:i,h:i},isLocal:t[3]===r,showName:!1});else{let i=0;for(let s=0;s<e;s+=3){const n=Math.min(3,e-s);for(let e=0;e<n;e++){const n=s+e;a.push({userId:t[n],frame:{x:e*o,y:i,w:o,h:o},isLocal:t[n]===r,showName:!1})}i+=o}}return a}}function z(t){switch(t){case e.LayoutTemplate.FLOAT:return"float";case e.LayoutTemplate.GRID:return"grid";default:return"float"}}function Q(){return{template:e.LayoutTemplate.FLOAT,canvas:{w:J,h:q},primaryUser:{userId:"",isLocal:!1},secondaryUser:null,showRemoteInfo:!1}}const Z=new a,ee=Object.freeze(["onEnterRoom","onExitRoom","onSwitchRole","onError","onWarnning","onRemoteUserEnterRoom","onRemoteUserLeaveRoom","onUserVideoAvailable","onUserSubStreamAvailable","onUserAudioAvailable","onUserVoiceVolume","onNetworkQuality","onFirstVideoFrame","onSendFirstLocalVideoFrame","onSendFirstLocalAudioFrame","onMicDidReady"]);function te(e){const t=r&&r.EVENT||{};switch(e){case"SDK_READY":return t.SDK_READY||"sdkStateReady";case"KICKED_OUT":return t.KICKED_OUT||"kickedOut";case"USER_SIG_EXPIRED":return t.USER_SIG_EXPIRED||"userSigExpired";case"ROOM_CUSTOM_DATA_RECEIVED":return t.ROOM_CUSTOM_DATA_RECEIVED;default:return null}}class re{constructor(e){const t=e||{};this._emitter=new a,this._sdkAppId=t.SDKAppID||t.sdkAppID||0,this._userId="",this._userSig="",this._isExternalChat=!1,this._chatListenersBound=!1,this._trtcCloud=null,this._trtcListenersBound=!1,this._trtcListenerHandlers=null,this._callInfo=w(),this._callsInFlight=!1,this._terminalId="",this._viewLayout=new X;const r=t.chat||t.tim;r&&(this._isExternalChat=!0,this._chat=r)}static createInstance(e){return re.instance||(re.instance=new re(e)),re.instance}static once(e,t){"ready"===e?"function"==typeof t&&Promise.resolve().then(()=>{try{t()}catch(e){console.error("[call-engine-wx] ready callback threw:",e)}}):Z.once(e,t)}async login(e){const t=e||{},a=t.userID,o=t.userSig,i=t.sdkAppID||t.SDKAppID||this._sdkAppId;if(!a||!o)throw ae(_.ERR_FAILED,"login: userID and userSig are required");!this._sdkAppId&&i&&(this._sdkAppId=i),this._userId=a,this._userSig=o,this._bindChatListenersOnce();try{if(this._chat=r.create({SDKAppID:this._sdkAppId,devMode:!0}),this._isLogined())return void this._emitOnceReady();let e;try{e=await this._chat.login({userID:a,userSig:o});try{this.getTRTCCloudInstance()}catch(e){}}catch(e){const t=e&&e.code,r=e&&e.message||"";if(2024===t||2025===t)return console.warn("[call-engine-wx] login: tolerated lite-chat code",t,r),void this._emitOnceReady();if(this._chatReadyFired&&(/timeout/i.test(r)||"NETWORK_TIMEOUT"===t))return console.warn("[call-engine-wx] login: chat.login() rejected with",r||t,"AFTER SDK_READY — treating as success"),void this._emitOnceReady();throw e}if(e&&e.data&&e.data.repeatLogin)return void this._emitOnceReady();this._emitOnceReady()}catch(e){const t=e&&e.code||_.ERR_FAILED,r=e&&e.message||"login failed";throw this._emitter.emit(m.ERROR,{code:t,message:r}),ae(t,r)}}async logout(){this._clearCallInfo();try{this._chat&&"function"==typeof this._chat.logout&&await this._chat.logout()}finally{this._userId="",this._userSig=""}}async destroyInstance(){re.instance=null;try{await this.logout()}catch(e){}this._unbindChatListeners(),this._unbindTRTCListeners(),this._emitter.removeAllListeners(),this._trtcCloud=null}on(e,t){this._emitter.on(e,t)}off(e,t){this._emitter.off(e,t)}once(e,t){this._emitter.once(e,t)}getTim(){return this._chat}getTRTCCloudInstance(){if(this._trtcCloud)return this._trtcCloud;if(!t||"function"!=typeof t.getTRTCShareInstance)throw ae(_.ERR_FAILED,"[call-engine-wx] @tencentcloud/trtc-component-wx is not installed or does not expose getTRTCShareInstance().");return this._trtcCloud=t.getTRTCShareInstance(),this._bindTRTCListenersOnce(),this._trtcCloud}setLogLevel(e){try{this._chat&&"function"==typeof this._chat.setLogLevel&&this._chat.setLogLevel(e)}catch(e){}}async calls(t){if(console.warn("---\x3e calls 入参 ",JSON.stringify(t)),!this._isLogined()&&!this._chatReadyFired)throw ae(_.ERR_FAILED,"calls: not logged in. Call login() first and wait for SDK_READY.");if(this._callsInFlight)throw ae(_.ERR_FAILED,"calls: a previous calls() is still in progress");if(this._callInfo.status!==e.CallStatus.NONE)throw ae(_.ERR_FAILED,"calls: there is an active call already; hang up before starting a new one");if(!R(t?.userIDList)||0===t?.userIDList?.length)throw ae(_.ERR_FAILED,"calls: userIDList cannot be empty");if(t?.type!==e.CallMediaType.AUDIO&&t?.type!==e.CallMediaType.VIDEO)throw ae(_.ERR_FAILED,"calls: invalid mediaType");const r=this._getLoginUserId();if(!r)throw ae(_.ERR_FAILED,"calls: cannot resolve login user id");var a;this._callInfo=w({...t,strRoomId:(a=t?.strRoomID,a||`roomId_${Math.floor(1e6*Math.random())}`),status:e.CallStatus.WAITING,role:e.CallRole.CALLER,inviter:r}),this._callsInFlight=!0;let o=!1;try{try{await this._enterTRTCRoom(),o=!0}catch(e){this._safeLeaveTRTCRoom();const t=e&&e.code||_.ERR_FAILED,r=e&&e.message||"enter TRTC room failed";throw this._emitter.emit(m.ERROR,{code:t,message:r}),ae(t,r)}const t=await W.startCall({chat:this._chat,...this._callInfo,userIdList:this._callInfo.inviteeList});if(0!==t.errCode)throw this._safeLeaveTRTCRoom(),o=!1,this._emitter.emit(m.ERROR,{code:t.errCode,message:t.errMsg}),ae(t.errCode,t.errMsg||"start_call failed");this._callInfo.callId=t.inviteId,this._callInfo.callStartTime=Date.now();let r=0;for(const a of t.callResultList)switch(a.resultCode){case e.CallInvitationResultCodeType.INVITED:this._emitter.emit(m.USER_ENTER,a.userId);break;case e.CallInvitationResultCodeType.SUCCESS:this._emitter.emit("onUserInviting",a.userId);break;case e.CallInvitationResultCodeType.LINE_BUSY:this._emitter.emit("onUserLineBusy",a.userId),r++}if(r>=this._callInfo.inviteeList.length){const r=t.callResultList[t.callResultList.length-1];return this._safeLeaveTRTCRoom(),o=!1,this._emitter.emit(m.ON_CALL_NOT_CONNECTED,{callInfo:{...this._callInfo},userId:r?r.userId:"",reason:e.CallEndReason.LINE_BUSY}),this._clearCallInfo(),{inviteId:t.inviteId,roomId:this._callInfo,callResultList:t.callResultList}}return W.startHeartBeat({chat:this._chat,callId:this._callInfo.callId,userId:this._callInfo.inviter,onTimeout:t=>{this._callInfo.callId===t&&(this._emitter.emit(m.ON_CALL_NOT_CONNECTED,{callInfo:{...this._callInfo},userId:this._callInfo.inviter,reason:e.CallEndReason.LINE_BUSY}),this._safeLeaveTRTCRoom(),this._clearCallInfo())}}),{inviteId:t.inviteId,roomId:this._callInfo,callResultList:t.callResultList}}catch(e){throw o&&this._safeLeaveTRTCRoom(),this._clearCallInfo(),e}finally{this._callsInFlight=!1}}async accept(){if(!this._isLogined()&&!this._chatReadyFired)throw ae(_.ERR_FAILED,"accept: not logged in. Call login() first and wait for SDK_READY.");if(this._callInfo.role!==e.CallRole.CALLEE)throw ae(_.ERR_FAILED,"accept: current role is not CALLEE");if(this._callInfo.status!==e.CallStatus.WAITING)throw ae(_.ERR_FAILED,`accept: invalid call status ${this._callInfo.status}; expected WAITING`);const t=this._callInfo.callId;if(!t)throw ae(_.ERR_FAILED,"accept: no active invitation (callId is empty)");let r=!1;try{await this._enterTRTCRoom(),r=!0;const a=this._getOrCreateTerminalId(),o=await W.accept({chat:this._chat,callId:t,terminalId:a});if(0!==o.errCode)throw ae(o.errCode,o.errMsg||"handle_call(accept) failed");return this._callInfo.status=e.CallStatus.CALLING,this._callInfo.callStartTime=Date.now(),this._emitter.emit(m.ON_CALL_BEGIN,{callInfo:{...this._callInfo}}),W.startHeartBeat({chat:this._chat,callId:this._callInfo.callId,userId:this._getLoginUserId(),onTimeout:t=>{this._callInfo.callId===t&&(this._emitter.emit(m.ON_CALL_NOT_CONNECTED,{callInfo:{...this._callInfo},userId:this._getLoginUserId(),reason:e.CallEndReason.LINE_BUSY}),this._safeLeaveTRTCRoom(),this._clearCallInfo())}}),{callId:t,roomId:this._callInfo.roomId}}catch(e){r&&this._safeLeaveTRTCRoom(),this._clearCallInfo();const t=e&&e.code||_.ERR_FAILED,a=e&&e.message||"accept failed";throw this._emitter.emit(m.ERROR,{code:t,message:a}),ae(t,a)}}async reject(){if(!this._isLogined()&&!this._chatReadyFired)throw ae(_.ERR_FAILED,"reject: not logged in. Call login() first and wait for SDK_READY.");if(this._callInfo.role!==e.CallRole.CALLEE)throw ae(_.ERR_FAILED,"reject: current role is not CALLEE");if(this._callInfo.status!==e.CallStatus.WAITING)throw ae(_.ERR_FAILED,`reject: invalid call status ${this._callInfo.status}; expected WAITING`);const t=this._callInfo.callId;if(!t)throw ae(_.ERR_FAILED,"reject: no active invitation (callId is empty)");const r={...this._callInfo};try{const a=this._getOrCreateTerminalId(),o=await W.reject({chat:this._chat,callId:t,terminalId:a});return 0!==o.errCode&&console.warn("[call-engine-wx] reject: backend reported error",o.errCode,o.errMsg),this._emitter.emit(m.ON_CALL_END,{callInfo:r,reason:e.CallEndReason.REJECT,userId:this._getLoginUserId()}),{callId:t}}finally{this._clearCallInfo()}}async hangup(){if(!this._isLogined()&&!this._chatReadyFired)throw ae(_.ERR_FAILED,"hangup: not logged in. Call login() first and wait for SDK_READY.");if(this._callInfo.status!==e.CallStatus.CALLING&&this._callInfo.status!==e.CallStatus.WAITING)throw ae(_.ERR_FAILED,`hangup: invalid call status ${this._callInfo.status}; expected CALLING or WAITING`);const t=this._callInfo.callId;if(!t)throw ae(_.ERR_FAILED,"hangup: no active call (callId is empty)");const r=this._callInfo.role===e.CallRole.CALLER&&this._callInfo.status===e.CallStatus.WAITING,a={...this._callInfo};try{if(r){const e=this._callInfo.inviter||this._getLoginUserId(),r=Array.isArray(this._callInfo.inviteeList)?this._callInfo.inviteeList.slice():[];if(r.length>0){const a=await W.cancel({chat:this._chat,inviter:e,callId:t,calleeList:r});0!==a.errCode&&console.warn("[call-engine-wx] hangup(cancel): backend reported error",a.errCode,a.errMsg)}}else{const e=this._getOrCreateTerminalId(),r=await W.hangup({chat:this._chat,callId:t,terminalId:e});0!==r.errCode&&console.warn("[call-engine-wx] hangup: backend reported error",r.errCode,r.errMsg)}return this._safeLeaveTRTCRoom(),this._emitter.emit(m.ON_CALL_END,{callInfo:a,reason:r?e.CallEndReason.CANCELED:e.CallEndReason.HANGUP,userId:this._getLoginUserId()}),{callId:t}}finally{this._clearCallInfo()}}setLayoutTemplate(e){this._viewLayout.setLayoutTemplate(e),this._recalcAndEmitLayout()}setLargeViewUser(e){this._viewLayout.setLargeViewUser(e),this._recalcAndEmitLayout()}toggleViewReversed(){this._viewLayout.toggleViewReversed(),this._recalcAndEmitLayout()}_buildLayoutState(){const t=this._getLoginUserId()||"",r=this._callInfo||{},a=r.inviter||"",o=Array.isArray(r.inviteeList)?r.inviteeList:[],i="number"==typeof r.status?r.status:Y.NONE,s=new Set,n=[],l=(e,t)=>{e&&!s.has(e)&&(s.add(e),n.push({id:e,status:t}))};l(t,i),a&&l(a,i);for(const e of o)l(e,i);return{selfId:t,selfStatus:i,mediaType:"number"==typeof r.mediaType?r.mediaType:e.CallMediaType.VIDEO,allParticipants:n,inviter:a,inviteeList:o}}_recalcAndEmitLayout(){try{this._viewLayout.recalculate(this._buildLayoutState())&&this._emitter.emit(m.VIEW_LAYOUT_CHANGED,this._viewLayout.toJsonObject())}catch(e){console.warn("[call-engine-wx] _recalcAndEmitLayout failed:",e&&e.message)}}async openCamera(e,t){let r;if(r=void 0===t?-1:t?1:0,g(this?._trtcCloud?.startLocalPreview))return this._trtcCloud.startLocalPreview(e,r)}async closeCamera(){if(g(this?._trtcCloud?.stopLocalPreview))return this._trtcCloud.stopLocalPreview()}async switchCamera(e){g(this?._trtcCloud?.switchCamera)&&await this._trtcCloud.switchCamera(!!e)}async openMicrophone(){g(this?._trtcCloud?.startLocalAudio)&&await this._trtcCloud.startLocalAudio()}async closeMicrophone(){g(this?._trtcCloud?.stopLocalAudio)&&await this._trtcCloud.stopLocalAudio()}async selectAudioPlaybackDevice(t){if(!g(this?._trtcCloud?.setAudioRoute))return;const r=t===e.AudioPlayBackDevice.EAR||1===t?e.AudioPlayBackDevice.EAR:e.AudioPlayBackDevice.SPEAKER;await this._trtcCloud.setAudioRoute(r)}async startRemoteView(e){if(!this._trtcCloud||"function"!=typeof this._trtcCloud.startRemoteView)return;const{userId:t,view:r,streamType:a=0}=e||{};return this._trtcCloud.startRemoteView(t,r,a)}async stopRemoteView(e){if(!this._trtcCloud||"function"!=typeof this._trtcCloud.stopRemoteView)return;const{userId:t,streamType:r=0}=e||{};return this._trtcCloud.stopRemoteView(t,r)}_bindChatListenersOnce(){if(this._chatListenersBound||!this._chat||"function"!=typeof this._chat.on)return;const t=te("SDK_READY"),r=te("KICKED_OUT"),a=te("USER_SIG_EXPIRED"),o=te("ROOM_CUSTOM_DATA_RECEIVED");this._onChatReady=()=>{this._chatReadyFired=!0,this._emitOnceReady()},this._onChatKickedOut=e=>{this._emitter.emit(m.KICKED_OUT,e||{})},this._onChatUserSigExpired=()=>{this._emitter.emit(m.onUserSigExpired,{})},this._onChatRoomCustomDataReceived=t=>{const{Data:r={},Head:a={}}=JSON.parse(t.data);if("call_engine_srv.invite_user_notify"===a?.Command){const{CallInfo:t={}}=r;let a={intRoomId:0,strRoomId:""};if(1===t.RoomIdType)a.intRoomId=Number(t.RoomId);else{if(2!==t.RoomIdType)return;a.strRoomId=t.RoomId}this._callInfo=w({userIDList:r?.CalleeList_Account||[],callId:r?.CallInfo?.CallId||"",inviter:r?.Caller_Account||"",roomId:a.intRoomId||0,strRoomId:a.strRoomId||"",groupId:r?.CallInfo?.GroupId||"",type:r?.CallInfo?.CallMediaType,status:e.CallStatus.WAITING,role:e.CallRole.CALLEE}),this._emitter.emit(m.ON_CALL_RECEIVED,{callId:this._callInfo.callId,inviter:this._callInfo.inviter,inviteeList:this._callInfo.inviteeList,groupId:this._callInfo.groupId,mediaType:this._callInfo.mediaType,roomId:this._callInfo.roomId,userData:r?.UserData||"",callInfo:{...this._callInfo}})}},t&&this._chat.on(t,this._onChatReady),r&&this._chat.on(r,this._onChatKickedOut),a&&this._chat.on(a,this._onChatUserSigExpired),o&&this._chat.on(o,this._onChatRoomCustomDataReceived),this._chatListenersBound=!0}_unbindChatListeners(){if(!this._chatListenersBound||!this._chat||"function"!=typeof this._chat.off)return;const e=te("SDK_READY"),t=te("KICKED_OUT"),r=te("USER_SIG_EXPIRED"),a=te("ROOM_CUSTOM_DATA_RECEIVED");try{e&&this._onChatReady&&this._chat.off(e,this._onChatReady)}catch(e){}try{t&&this._onChatKickedOut&&this._chat.off(t,this._onChatKickedOut)}catch(e){}try{r&&this._onChatUserSigExpired&&this._chat.off(r,this._onChatUserSigExpired)}catch(e){}try{a&&this._onChatRoomCustomDataReceived&&this._chat.off(a,this._onChatRoomCustomDataReceived)}catch(e){}this._chatListenersBound=!1}_bindTRTCListenersOnce(){if(this._trtcListenersBound||!this._trtcCloud)return;const t=this._trtcCloud;if("function"!=typeof t.on)return;const r={},a=e=>(...t)=>{try{this._emitter.emit(e,...t)}catch(t){console.warn("[call-engine-wx] listener for",e,"threw:",t)}};for(const o of ee){let i;if("onRemoteUserEnterRoom"===o){const t=a(o);i=(...r)=>{try{this._callInfo&&this._callInfo.callId&&this._callInfo.status===e.CallStatus.WAITING&&(this._callInfo.status=e.CallStatus.CALLING,this._callInfo.callStartTime||(this._callInfo.callStartTime=Date.now()),this._emitter.emit(m.ON_CALL_BEGIN,{callInfo:{...this._callInfo}}))}catch(e){console.warn("[call-engine-wx] ON_CALL_BEGIN gate threw:",e)}t(...r)}}else i=a(o);r[o]=i;try{t.on(o,i)}catch(e){}}this._trtcListenerHandlers=r,this._trtcListenersBound=!0}_unbindTRTCListeners(){if(!this._trtcListenersBound)return;const e=this._trtcCloud,t=this._trtcListenerHandlers||{};if(e&&"function"==typeof e.off)for(const r of Object.keys(t))try{e.off(r,t[r])}catch(e){}this._trtcListenerHandlers=null,this._trtcListenersBound=!1}_emitOnceReady(){this._readyEmitted||(this._readyEmitted=!0,this._emitter.emit(m.SDK_READY,{name:"sdk_ready"}),this._fetchPendingInvitation().catch(e=>{console.warn("[call-engine-wx] _fetchPendingInvitation: unexpected error",e)}))}async _fetchPendingInvitation(){if(!this._chat||!this._isLogined())return;if(this._callInfo&&this._callInfo.callId)return;const e=this._getLoginUserId();if(!e)return;let t;try{t=await W.getInvitation({chat:this._chat,userId:e})}catch(e){return void console.warn("[call-engine-wx] getInvitation request threw:",e)}if(t&&0===t.errCode&&t.data)try{const e={data:JSON.stringify({Data:t.data,Head:{Command:"call_engine_srv.invite_user_notify"}})};g(this._onChatRoomCustomDataReceived)&&this._onChatRoomCustomDataReceived(e)}catch(e){console.warn("[call-engine-wx] replay pending invitation failed:",e)}}_isLogined(){try{if(!this._chat)return!1;if("function"==typeof this._chat.getLoginUser)return!!this._chat.getLoginUser()}catch(e){}return!1}_getLoginUserId(){return this._userId?this._userId:g(this?._chat?.getLoginUser)&&this._chat.getLoginUser()||""}async _enterTRTCRoom(){try{W.stopHeartBeat()}catch(e){}if(this._callInfo.callType===e.CallMediaType.UNKNOWN)throw ae(-1,"call type is none");const{roomId:t}=this._callInfo;if(0===t.intRoomId&&""===t.strRoomId)throw ae(-1,"room id is empty");const r={sdkAppId:this._sdkAppId,userId:this._getLoginUserId(),userSig:this._userSig,role:20};t.intRoomId>0?r.roomId=t.intRoomId:r.strRoomId=t.strRoomId;const a=this._callInfo.mediaType===e.CallMediaType.VIDEO?0:2,o=this.getTRTCCloudInstance();await new Promise((e,t)=>{let i=!1,s=null;const n=()=>{s&&(clearTimeout(s),s=null);try{this._emitter.off("onEnterRoom",l)}catch(e){}},l=r=>{i||(i=!0,n(),"number"==typeof r&&r>0?e():t(ae("number"==typeof r?r:-1,`enterRoom failed: ${r}`)))};this._emitter.on("onEnterRoom",l),s=setTimeout(()=>{i||(i=!0,n(),t(ae(-1,"enterRoom timeout")))},1e4);try{const e=o.enterRoom(r,a);e&&"function"==typeof e.catch&&e.catch(e=>{i||(i=!0,n(),t(e))})}catch(e){if(i)return;i=!0,n(),t(e)}})}_safeLeaveTRTCRoom(){try{this._trtcCloud&&"function"==typeof this._trtcCloud.exitRoom&&this._trtcCloud.exitRoom()}catch(e){}}_clearCallInfo(){try{W.stopHeartBeat()}catch(e){}this._callInfo=w()}_getOrCreateTerminalId(){return this._terminalId||(this._terminalId=function(){const e=new Array(16),t="undefined"!=typeof crypto&&crypto||null;if(t&&"function"==typeof t.getRandomValues){const r=new Uint8Array(16);t.getRandomValues(r);for(let t=0;t<16;t++)e[t]=r[t]}else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());const r=e.map(e=>e.toString(16).padStart(2,"0")).join("").toUpperCase();return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}()),this._terminalId}}function ae(e,t){const r=new Error(t);return r.code=e,r}re.instance=null,e.TencentCloudChat=r,e.CallInvitationRespondedType=f,e.TUICallEngine=re,e.TUICallEvent=m,e.TUIErrorCode=_,e.default=re,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
3
3
|
//# sourceMappingURL=index.umd.min.js.map
|