@tencentcloud/lite-chat 4.1.0 → 4.1.2

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/standard.es.js CHANGED
@@ -1 +1 @@
1
- let e=e=>void 0===e,t=e=>"string"==typeof e,s=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[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=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},a=e=>{if("object"!=typeof e||null===e)return!1;e=Object.getPrototypeOf(e);if(null===e)return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return e===t};function c(e=99999999){return Math.round(Math.random()*e)}let u=(r,n,o,a)=>{if(!i(r)||!i(n))return 0;let l=0;var c,d=Object.keys(n);for(let t=0,s=d.length;t<s;t++)if(c=d[t],!(e(n[c])||o&&o.includes(c)))if(i(r[c])&&i(n[c]))l+=u(r[c],n[c],o,a);else{if(a&&a.includes(n[c]))continue;r[c]!==n[c]&&(r[c]=n[c],l+=1)}return l};function l(s){let r,n,i=s,o="";for(let e=0,t=(i=s.length%8!=0?"0".repeat(8-s.length%8)+s:i)["length"];e<t;e+=8)r=parseInt(i.slice(e,e+4),2),n=parseInt(i.slice(e+4,e+8),2),o+=base16Map.get(r)+base16Map.get(n);return o}let 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 g,S;!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"}(g=g||{});let p="LiteChat",_={[g.DEBUG]:console.debug,[g.INFO]:console.info,[g.WARN]:console.warn,[g.ERROR]:console.error},m={[g.INFO]:4,[g.WARN]:5,[g.ERROR]:6},v=1e3,f=2,I=5e3,E=50;!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 C=Object.freeze({__proto__:null,CONSOLE_METHOD:_,CloudConfigReportLevelMap:m,get ConvModifyPushType(){return S},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:E,DEFAULT_GLOBAL_THROTTLE_TIME:I,DEFAULT_SINGLE_MAX_TOTAL_COUNT:f,DEFAULT_SINGLE_THROTTLE_TIME:v,ENUM_PLATFORM:d,IS_TOPIC_MESSAGE:2,get LogLevel(){return g},NOT_NEED_CRC_SERVCMD:h,SDK_NAME:p});let M="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),y="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||M,O=y&&"function"==typeof wx.createGamePortal,A="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),R=T&&"function"==typeof tt.onShow,D="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),b="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,L="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,P=y&&"object"==typeof wx.miniapp,G="undefined"!=typeof uni,w=y||A||T||D||b||L||N,U="undefined"==typeof window&&!w&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,k="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),F="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),$="undefined"!=typeof uni?!w:"undefined"!=typeof window&&!w&&!k,q=A?qq:T?tt:D?swan:b?my:y?wx:L?uni:N?jd:{},x=$&&window&&window.navigator&&window.navigator.userAgent||"",V=/(micromessenger|webbrowser)/i.test(x),B=function(){let e="WEB";return V?e="WEB":A?e="QQ_MP":T?e="TT_MP":D?e="BAIDU_MP":b?e="ALI_MP":y?e=P?"DONUT_NATIVE_APP":"WX_MP":L?e="UNI_NATIVE_APP":U?e="NS_NATIVE_APP":k&&(e="RN_NATIVE_APP"),d[e]}(),j=/iPad/i.test(x),K=/iPhone/i.test(x)&&!j,H=/iPod/i.test(x),W=K||j||H,Y=function(){var e=x.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),z=/Android/i.test(x),J=function(){var e,t,s=x.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);return s?(e=s[1]&&parseFloat(s[1]),t=s[2]&&parseFloat(s[2]),e&&t?parseFloat(s[1]+"."+s[2]):e||null):null}(),Q=/Firefox/i.test(x),X=/Edge/i.test(x),Z=!X&&/Chrome/i.test(x),ee=/MSIE/.test(x)||-1<x.indexOf("Trident")&&-1<x.indexOf("rv:11.0"),te=function(){var e=/MSIE\s(\d+)\.\d/.exec(x);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(x)&&/rv:11.0/.test(x)?11:t}(),se=/Safari/i.test(x)&&!Z&&!z&&!X,ne=/Windows/i.test(x),oe=/MAC OS X/i.test(x),ie=$&&"undefined"!=typeof Worker&&!ee,re=z||W,ae=$&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ce=function(){var e;return"undefined"!=typeof window&&void 0!==window.navigator&&(e=window.navigator["standalone"],!(!W||e||se))}();function ue(){let e="unknown";if(oe&&(e="mac"),ne&&(e="windows"),W&&(e="ios"),z&&(e="android"),w)try{var t=q.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}function le(e,t){var s={};for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(s[n[r]]=e[n[r]]);return s}function de(e,o,a,l){return new(a=a||Promise)(function(s,t){function r(e){try{i(l.next(e))}catch(e){t(e)}}function n(e){try{i(l.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}i((l=l.apply(e,o||[])).next())})}let he=2800,ge=2801,pe=3e3,_e="application/x-www-form-urlencoded;charset=UTF-8";function me(e){return de(this,arguments,void 0,function*({method:n,url:i,data:o,timeout:a=pe}){return new Promise(w?(t,e)=>{q.request({url:i,data:o,method:n,timeout:a,header:{"content-type":_e},success:e=>t(e.data),fail:()=>e(new Error(`{"message":"Network error","code":${he}}`))})}:(t,e)=>{let s=new XMLHttpRequest,r=setTimeout(()=>{s.abort(),e(new Error(`{"message":"Request timeout","code":${ge}}`))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(r),200===s.status||304===s.status)try{t(s.responseText?JSON.parse(s.responseText):null)}catch(e){t(s.responseText)}else e(new Error(`{"message":"Network error","code":${he}}`))},s.open(n,i,!0),s.setRequestHeader("Content-type",_e),s.send(o||null)})})}function ve(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(var 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 fe(r){if(null===r||"object"!=typeof r)return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp)return new RegExp(r.source,r.flags);if(r instanceof Map){let s=new Map;return r.forEach((e,t)=>{s.set(fe(t),fe(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(fe(e))}),t}if(Array.isArray(r))return r.map(e=>fe(e));let e=Object.getPrototypeOf(r),s=Object.create(e);return[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)].forEach(e=>{var t=Object.getOwnPropertyDescriptor(r,e);t&&(t.get||t.set?Object.defineProperty(s,e,t):s[e]=fe(r[e]))}),s}function Ie(e,s,t){let r=new WeakSet;try{return JSON.stringify(e,(e,t)=>{if(void 0===(t=s?s(e,t):t))return"undefined";if(null===t)return null;if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if("function"==typeof t)return`[Function: ${t.name||"anonymous"}]`;if("symbol"==typeof t)return t.toString();if("bigint"==typeof t)return t.toString()+"n";if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t instanceof Date?t.toISOString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof Set?{dataType:"Set",value:Array.from(t.values())}:t},t)}catch(e){return console.error("Failed to stringify:",e),""}}function Ee(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var Se,Te,Ce=Object.freeze({__proto__:null,ANDROID_VERSION:J,IE_VERSION:te,IN_ALIPAY_MINI_APP:b,IN_BAIDU_MINI_APP:D,IN_BROWSER:$,IN_DONUT_NATIVE_APP:P,IN_JD_MINI_APP:N,IN_MINI_APP:w,IN_NS_NATIVE_APP:U,IN_QQ_MINI_APP:A,IN_RN_APP:k,IN_TT_MINI_APP:T,IN_TT_MINI_GAME:R,IN_UNI_APP:G,IN_UNI_NATIVE_APP:L,IN_WX_MINI_APP:y,IN_WX_MINI_APP_DESK:M,IN_WX_MINI_GAME:O,IN_WX_MINI_PLUGIN:F,IOS_VERSION:Y,IS_ANDROID:z,IS_CHROME:Z,IS_EDGE:X,IS_FIREFOX:Q,IS_IE:ee,IS_IOS:W,IS_IPAD:j,IS_IPHONE:K,IS_IPOD:H,IS_MAC:oe,IS_SAFARI:se,IS_WECHAT:V,IS_WIN:ne,IS_WORKER_AVAILABLE:ie,MINI_APP_NAMESPACE:q,USER_AGENT:x,base16EncodeBinaryString:l,deepCopyWithMethods:fe,deepMerge:u,generatePromise:Ee,getPlatformType:ue,getType:s,httpRequest:me,isArray:n,isArrayOrObject:i,isEmpty:ve,isFlutterWeb:ae,isH5:re,isIOSWebView:ce,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:o,isPlainObject:a,isString:t,isUndefined:e,isUniIOSApp:function(){return L&&"ios"===uni.getDeviceInfo().platform.toLocaleLowerCase()},isValidRequestKey:r,platform:B,randomInt:c,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t},safeStringify:Ie});class Me{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,r){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!r||e.context===r;return!(t&&e)}))}emit(s,...r){var e=this.listeners[s];e&&e.forEach(e=>{var{fn:e,context:t}=e;try{e.apply(t,r)}catch(e){console.warn(`Error in event handler for ${s} error: `+Ie(e))}})}once(t,s,r){let n=(...e)=>{s.apply(r,e),this.off(t,n)};this.on(t,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"}(Se=Se||{});let ye=[16,17];function Oe(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{2===e.GroupInfo.MillionGroupFlag?s.push(Se.TOPIC_TIPS_NOTIFICATION):ye.includes(null==(e=null==e?void 0:e.MsgBody)?void 0:e.OpType)?s.push(Se.GROUP_MESSAGE_PINNED):s.push(Se.GROUP_TIPS_NOTIFICATION)}),s}let Ae=[{conditions:[{type:"event",value:100}],subType:Se.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Se.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Se.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Se.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Se.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Se.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Se.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Se.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Se.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Se.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.C2cNotifyMsgArray)&&t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(Se.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(Se.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(Se.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(Se.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Oe},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(Se.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(Se.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(Se.TOPIC_MESSAGE_READ_SYNC):s.push(Se.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(Se.TOPIC_SYSTEM_NOTIFICATION):s.push(Se.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Oe},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{var e=e["GroupAtTips"]["TopicId"];e?s.push(Se.TOPIC_AT_TIPS):s.push(Se.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{switch(e.PushType){case S.CONV_MARK_UPDATED:s.push(Se.CONVERSATION_MARK_UPDATED);break;case S.CONV_GROUP_ADDED:s.push(Se.CONVERSATION_GROUP_ADD);break;case S.CONV_GROUP_DELETED:s.push(Se.CONVERSATION_GROUP_DELETED);break;case S.CONV_GROUP_UPDATED:s.push(Se.CONVERSATION_GROUP_UPDATED);break;default:s.push(Se.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Se.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Se.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Se.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Se.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Se.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Se.ALL_MESSAGE_READ}];function Re(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],n=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=Ae.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(!e)return null;let s=[];"function"==typeof e.subTypeParser?s=e.subTypeParser(t):e.subType&&(s=e.subType),Array.isArray(s)?s.forEach(e=>{n.push({type:Te.SERVER_PUSH_MESSAGE+":"+e,data:t})}):n.push({type:Te.SERVER_PUSH_MESSAGE+":"+s,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"}(Te=Te||{});let De={[Te.SERVER_PUSH_MESSAGE]:Re,[Te.SERVER_PUSH_MESSAGE_MULTIPLE]:Re,[Te.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},be=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new Me,this._innerEventEmitter=new Me,this.InnerEventSubType=Se}subscribeInnerEvent(s,r,n,i){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=n;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,i)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,n)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(De).includes(t)){let e=null==(t=De[t])?void 0:t.call(De,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,r,n,i){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=n;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,i)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,n)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};class Ne{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t;try{null!=(t=this._socket)&&t.send(e)}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:n}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,this._onSendFail=n)}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 Le{connectSocket(e){return this._socket=q.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:n}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=n}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}let Pe="CONNECT",Ge="SEND",we="DISCONNECT",Ue="OPEN",ke="MESSAGE",Fe="CLOSE",$e="ERROR",qe="SEND_FAIL";class xe{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){var 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:Pe,url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:Ge,data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:r,onClose:n,onError:i,onSendFail:o}=e;if(this._worker){let s={[Ue]:t,[ke]:r,[Fe]:n,[$e]:i,[qe]:o};this._onSendFail=o,this._worker.onmessage=e=>{var t=((null==e?void 0:e.data)||{})["type"];"function"==typeof s[t]&&null!=(t=s[t])&&t.call(s,null==e?void 0:e.data)}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:we}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Ve,Be=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return w?b?my.getStorageSync({key:e}).data:q.getStorageSync(e):this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){var 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){w?b?my.setStorageSync({key:e,data:JSON.stringify(t)}):q.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}};!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(Ve=Ve||{});class je{constructor(e){this._url="",this._readyState=Ve.DISCONNECTED,this._url=e,this._id=c(),this._emitter=new Me,y||L||R?this._socket=new Le:this._canUseWebWorker()?this._socket=new xe:this._socket=new Ne,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Ve.CONNECTED,Ve.CONNECTING].includes(this._readyState)||(this._readyState=Ve.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Ve.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Ve.CONNECTED,Ve.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===Ve.CONNECTED}disconnect(){this._readyState=Ve.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Ve.CONNECTING&&(this._readyState=Ve.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Ve.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Ve.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Ve.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(){var t=Be.get("cloudConfig")||{};return(e(t.isWorkerEnabled)||"1"===t.isWorkerEnabled)&&ie}}let Ke="CHINA",He="OVERSEA",We="SINGAPORE",Ye="KOREA",ze="GERMANY",Je="IND",Qe="JPN",Xe="USA",Ze="INDONESIA",et={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"}},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"}}},st={[We]:[[2e7,3e7],[172e7,173e7]],[Ye]:[[3e7,4e7],[173e7,174e7]],[ze]:[[4e7,5e7],[174e7,175e7]],[Je]:[[5e7,6e7],[175e7,176e7]],[Qe]:[[6e7,7e7],[176e7,177e7]],[Xe]:[[7e7,8e7],[177e7,178e7]],[Ze]:[[8e7,9e7],[178e7,179e7]]};function nt(t){var e;if(null!=(e=Be.get("instance"))&&e.oversea)return He;for(let e of Object.keys(st))for(var[s,r]of st[e])if(t>=s&&t<r)return e;return Ke}var ot,it="4.1.0";!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"}(ot=ot||{});let rt=ot.INITIAL;function at(){var e=Math.random();return 0===e?at():e}function ct(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:n}=Be.get("instance"),i=at(),o=ue(),a=function(){var e=ue();let t=-1;return"ios"===e?t=Y||-1:"android"===e&&(t=J||-1),t}(),r=(s={sdkappid:r,instanceid:n,random:i,platform:B,host:o,version:a,sdkversion:it},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}function ut(e){var{sdkAppId:t,testEnv:s}=Be.get("instance"),t=nt(t);if(s)return ct(et.TEST[t].DEFAULT,{isBinary:e});let r=et.PRODUCTION[t],n=$&&r.ANYCAST,i=$,o=!!r.BACKUP_CN;return ct({[ot.INITIAL]:()=>(rt=ot.DEFAULT,r.DEFAULT),[ot.DEFAULT]:()=>(rt=ot.IPV6,r.IPV6),[ot.IPV6]:()=>(rt=ot.BACKUP,r.BACKUP),[ot.BACKUP]:()=>{return i?(rt=ot.BACKUP_WEB_ONLY,e=r.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):o?(rt=ot.BACKUP_CN,r.BACKUP_CN):n?(rt=ot.ANYCAST,r.ANYCAST):r.DEFAULT;var e,t},[ot.BACKUP_WEB_ONLY]:()=>o?(rt=ot.BACKUP_CN,r.BACKUP_CN):n?(rt=ot.ANYCAST,r.ANYCAST):r.DEFAULT,[ot.BACKUP_CN]:()=>(rt=n?ot.ANYCAST:ot.DEFAULT,r[rt]),[ot.ANYCAST]:()=>(rt=ot.DEFAULT,r.ANYCAST="",r.DEFAULT)}[rt](),{isBinary:e})}var lt=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){var s=Date.now();this._timeOffsetWithServer=t+(s-e)-s}};let dt=16;var ht=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){var t=e["id"];this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){var{id:e,callback:t,context:s,isOnce:r=!1,intervalMs:n=dt}=e,i=Math.max(n,dt);return{id:e,nextExecuteTime:Date.now()+i,intervalMs:n,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.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);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var 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 gt(t){var s=[];for(let e=0;e<t.length;e+=1){var r,n=t.charCodeAt(e);55296<=n&&n<=56319?(r=t.charCodeAt(++e)-56320+(n-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):n<=127?s.push(n):n<=2047?s.push(192|n>>6,128|63&n):s.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(s)}function pt(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=pt(e[t]));return s}function _t(e,t){if(h.includes(e))return 0;var s=gt(JSON.stringify(t));let r=4294967295;var n=s["length"];for(let e=0;e<n;e++){r^=s[e];for(let e=0;e<8;e++)1&~r?r>>>=1:r=r>>>1^3988292384}return(4294967295^r)>>>0}function mt(e){var t,{servcmd:e,data:s}=e,r=(r=e,n=Be.get("login")||{},t=Be.get("instance")||{},{servcmd:r,ver:"v4",platform:B,websdkappid:537048168,websdkversion:"1.7.3",a2:n.a2Key||void 0,tinyid:n.tinyID||void 0,status_instid:n.statusInstanceId||0,sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:n.a2Key?void 0:n.userId,usersig:n.a2Key?void 0:n.userSig,sdkability:75689843,sdkability_ext:l(""),cappid:t.applicationID||0,tjgID:"",seq:It(),cs:0}),n=pt(s);return r.cs=_t(e,n),{head:r,body:n}}function vt(e){var t,{servcmd:e,data:s}=e,r=(r=e,n=Be.get("login")||{},t=Be.get("instance")||{},{servcmd:r,ver:"v4",platform:B,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:n.statusInstanceId||0,sdkability:75689843,sdkability_ext:l(""),cappid:t.applicationID||0,seq:It(),cs:0}),n=pt(s);return r.cs=_t(e,n),{head:r,body:n}}let ft=c();function It(){return ft=ft<2415919103?ft+1:c()}function Et(){var e=Be.get("login")||{},t=Be.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"4.1.0",tiny_id:Number(e.tinyID),user_id:e.userId,platform:B,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var St,Ot,Ct=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,n=Be.get("login")||{},t=Be.get("instance")||{},{servcmd:r,ver:"v4",platform:B,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:n.userId,usersig:n.userSig,status_instid:n.statusInstanceId||0,sdkability:75689843,sdkability_ext:l(""),cappid:t.applicationID||0,seq:It(),cs:0}),n=pt(s);return r.cs=_t(e,n),{head:r,body:n}},generateProtocolData:mt,generateSSOLogProtocolData:vt,generateSequence:It,getCommonHead:Et,taskScheduler:ht,timeManager:lt});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(St=St||{});let Mt={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 yt{constructor(e){this.level=St.info,this._canSendLog=!0,this._logCreatedAt=lt.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();var{method:e,eventType:t=0,message:s="",costTime:r=0,error:n,moreMessage:i=""}=e||{};this.eventType=t,this.method=e,this.message=s,this.costTime=r,this.moreMessage=i,n&&this.setError(n)}setMoreMessage(e){this.moreMessage=this.moreMessage+" "+e}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=lt.getTimeOffsetWithServer()}end(){this._canSendLog&&(this._canSendLog=!1,this.timestamp=lt.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()))}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=Be.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=St.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(Mt).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{Mt[e]&&(t[Mt[e]]=this[e])}),t}_getUiPlatform(){var e,t=null==(e=Be.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null==(e=Be.get("instance"))?void 0:e.sdkEdition}}!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(Ot=Ot||{});var At=Ot;let Tt=20,Rt=6e4,Dt=[4,5,6],bt=[],Nt=[],Lt="report-logger";var Pt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Tt,this._maxThreshold=100,this._waitingTime=Rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=g.DEBUG,this._throttleConfig={global:{throttleTime:I,maxCount:E},single:{throttleTime:v,maxCount:f}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,be.subscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ht.addTask({id:Lt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=Tt,evt_rpt_waiting:t=Rt,evt_rpt_level:s=Dt,evt_rpt_sdkappid_bl:r=bt,evt_rpt_tinyid_wl:n=Nt,evt_rpt_global_throttle_time:i=I,evt_rpt_global_throttle_count:o=E,evt_rpt_single_throttle_time:a=v,evt_rpt_single_throttle_count:l=f}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=n,this._throttleConfig={global:{throttleTime:i,maxCount:o},single:{throttleTime:a,maxCount:l}}}createSSOLogData(e){var t=new yt(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){[g.DEBUG,g.ERROR,g.INFO,g.NONE,g.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(g.DEBUG,e,t,s)}info(e,t="",s){this._log(g.INFO,e,t,s)}warn(e,t="",s){this._log(g.WARN,e,t,s)}error(e,t="",s){this._log(g.ERROR,e,t,s)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&0<this._logQueue.length&&this.uploadSSOLogData()}uploadSSOLogData(){return de(this,void 0,void 0,function*(){var e,t;0!==this._logQueue.length&&(t=this._logQueue.slice(),t=this._filterLogs(t),this._logQueue=[],0===t.length||ve((t={Header:Et(),Event:t}).Header.user_id)||(e=(t=vt({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void es.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(y){var s=null==(t=null==(e=wx.getAccountInfoSync)?void 0:e.call(wx))?void 0:t.miniProgram;if(s){let{appId:e,envVersion:t}=s;Be.set("instance",{appId:e,envVersion:t})}}else $&&Be.set("instance",{href:window.location.href})}_filterLogs(e){var t=(Be.get("login")||{})["tinyID"],s=(Be.get("instance")||{})["sdkAppId"];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(){var 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){var 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!==g.NONE}_shouldReport(e){return this._reportLevel.includes(m[e])}_formatLog(e,t,s){var r=new Date,r=`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:`+r.getMilliseconds(),e=`<${g[e]}>`;return ee||w?[p+` [${r}] ${e} [${t}] `+s]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",p,"",`[${r}] ${e} [${t}] `+s]}_log(e,t,s,r){if(this._shouldLog(e)){var n=this._formatLog(e,t,s);if(_[e].apply(console,n),this._shouldReport(e)){let e=this._getThrottleKey(t,s,r);this._checkThrottle(e)||this.createSSOLogData(Object.assign(Object.assign({message:s},r),{method:t})).end()}}}_getThrottleKey(e,t,s){var e=""+e+t+Ie(Object.assign(Object.assign({},s),{costTime:""})),r=gt(JSON.stringify(e));let n=4294967295;var i=r["length"];for(let e=0;e<i;e++){n^=r[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return""+((4294967295^n)>>>0)}reset(){console.log("SSO_LOG_MODULE.reset"),ht.removeTask(Lt),be.unSubscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Tt,this._maxThreshold=100,this._waitingTime=Rt,this._logQueue=[],this._logLevel=g.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};let Gt=15e3,wt="Channel",Ut="channel_schedule_task",kt="channel_reconnect_task",Ft="connected",$t="connecting",qt="disconnected",xt=1e3,Vt="network_status_change",Bt="activity_status_change",jt="send_fail",Kt="reconnect_failed",Ht="socket_error",Wt="socket_close";function Yt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zt(e){return(zt="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})(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 Qt,os,Xt={exports:{}},Zt=(Qt||(Xt.exports=function s(r,n,i){function o(t,e){if(!n[t]){if(!r[t]){if(!e&&Jt)return Jt(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=n[t]={exports:{}};r[t][0].call(e.exports,function(e){return o(r[t][1][e]||e)},e,e.exports,s,r,n,i)}return n[t].exports}for(var a=Jt,e=0;e<i.length;e++)o(i[e]);return o}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,n=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var n=r.shift();if(n){if("object"!=zt(n))throw new TypeError(n+"must be non-object");for(var i in n)t=n,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=n[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,n){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),n);else for(var i=0;i<r;i++)e[n+i]=t[s+i]},flattenChunks:function(e){for(var t,s,r,n,i=t=0,o=e.length;i<o;i++)t+=e[i].length;for(n=new Uint8Array(t),i=s=0,o=e.length;i<o;i++)r=e[i],n.set(r,s),s+=r.length;return n}}),i={arraySet:function(e,t,s,r,n){for(var i=0;i<r;i++)e[n+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,n)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(r)},{}],2:[function(e,t,s){var l=e("./common"),n=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var u=new l.Buf8(256),r=0;r<256;r++)u[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&n))return String.fromCharCode.apply(null,l.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}u[254]=u[254]=1,s.string2buf=function(e){for(var t,s,r,n,i=e.length,o=0,a=0;a<i;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<i&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new l.Buf8(o),a=n=0;n<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<i&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[n++]=s:(s<2048?t[n++]=192|s>>>6:(s<65536?t[n++]=224|s>>>12:(t[n++]=240|s>>>18,t[n++]=128|s>>>12&63),t[n++]=128|s>>>6&63),t[n++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new l.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,n,i=t||e.length,o=new Array(2*i),a=s=0;a<i;)if((r=e[a++])<128)o[s++]=r;else if(4<(n=u[r]))o[s++]=65533,a+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&a<i;)r=r<<6|63&e[a++],n--;1<n?o[s++]=65533:r<65536?o[s++]=r:(r-=65536,o[s++]=55296|r>>10&1023,o[s++]=56320|1023&r)}return c(o,s)},s.utf8border=function(e,t){for(var s=(t=(t=t||e.length)>e.length?e.length:t)-1;0<=s&&128==(192&e[s]);)s--;return!(s<0||0===s)&&s+u[e[s]]>t?s:t}},{"./common":Qt=1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var n=65535&e,i=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;i=i+(n=n+t[r++]|0)|0,--o;);n%=65521,i%=65521}return n|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 a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var n=a,i=r+s;e^=-1;for(var o=r;o<i;o++)e=e>>>8^n[255&(e^t[o])];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,r,n,i,o,a,l=e.state,u=e.next_in,c=e.input,d=u+(e.avail_in-5),h=e.next_out,g=e.output,p=h-(t-e.avail_out),_=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,I=l.wnext,E=l.window,S=l.hold,C=l.bits,M=l.lencode,y=l.distcode,A=(1<<l.lenbits)-1,O=(1<<l.distbits)-1;e:do{for(C<15&&(S+=c[u++]<<C,C+=8,S+=c[u++]<<C,C+=8),s=M[S&A];;){if(S>>>=r=s>>>24,C-=r,0==(r=s>>>16&255))g[h++]=65535&s;else{if(!(16&r)){if(!(64&r)){s=M[(65535&s)+(S&(1<<r)-1)];continue}if(32&r){l.mode=12;break e}e.msg="invalid literal/length code",l.mode=30;break e}for(n=65535&s,(r&=15)&&(C<r&&(S+=c[u++]<<C,C+=8),n+=S&(1<<r)-1,S>>>=r,C-=r),C<15&&(S+=c[u++]<<C,C+=8,S+=c[u++]<<C,C+=8),s=y[S&O];;){if(S>>>=r=s>>>24,C-=r,!(16&(r=s>>>16&255))){if(!(64&r)){s=y[(65535&s)+(S&(1<<r)-1)];continue}e.msg="invalid distance code",l.mode=30;break e}if(i=65535&s,C<(r&=15)&&(S+=c[u++]<<C,(C+=8)<r)&&(S+=c[u++]<<C,C+=8),m<(i+=S&(1<<r)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(S>>>=r,C-=r,(r=h-p)<i){if(f<(r=i-r)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=E,(o=0)===I){if(o+=v-r,r<n){for(n-=r;g[h++]=E[o++],--r;);o=h-i,a=g}}else if(I<r){if(o+=v+I-r,(r-=I)<n){for(n-=r;g[h++]=E[o++],--r;);if(o=0,I<n){for(n-=r=I;g[h++]=E[o++],--r;);o=h-i,a=g}}}else if(o+=I-r,r<n){for(n-=r;g[h++]=E[o++],--r;);o=h-i,a=g}for(;2<n;)g[h++]=a[o++],g[h++]=a[o++],g[h++]=a[o++],n-=3;n&&(g[h++]=a[o++],1<n)&&(g[h++]=a[o++])}else{for(o=h-i;g[h++]=g[o++],g[h++]=g[o++],g[h++]=g[o++],2<(n-=3););n&&(g[h++]=g[o++],1<n)&&(g[h++]=g[o++])}break}}break}}while(u<d&&h<_);u-=n=C>>3,S&=(1<<(C-=n<<3))-1,e.next_in=u,e.next_out=h,e.avail_in=u<d?d-u+5:5-(u-d),e.avail_out=h<_?_-h+257:257-(h-_),l.hold=S,l.bits=C}},{}],8:[function(e,t,s){var N=e("../utils/common"),L=e("./adler32"),P=e("./crc32"),G=e("./inffast"),w=e("./inftrees"),U=0,k=-2,F=1,r=852,n=592;function x(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function i(){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 o(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=F,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(r),t.distcode=t.distdyn=new N.Buf32(n),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):k}function l(e,t){var s,r;return!e||!e.state||(r=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t))?k:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=s,r.wbits=t,a(e))}function u(e,t){var s;return e?(s=new i,(e.state=s).window=null,(s=l(e,t))!==U&&(e.state=null),s):k}var q,V,B=!0;function j(e,t,s,r){var n,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(n=e.wsize-e.wnext)&&(n=r),N.arraySet(e.window,t,s-r,n,e.wnext),(r-=n)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=n,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=n))),0}s.inflateReset=a,s.inflateReset2=l,s.inflateResetKeep=o,s.inflateInit=function(e){return u(e,15)},s.inflateInit2=u,s.inflate=function(e,t){var s,r,n,i,o,a,l,u,c,d,h,g,p,_,m,v,f,I,E,S,C,M,y,A,O=0,T=new N.Buf8(4),R=[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 k;12===(s=e.state).mode&&(s.mode=13),o=e.next_out,n=e.output,l=e.avail_out,i=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,d=a,h=l,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(2&s.wrap&&35615===u)T[s.check=0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0),c=u=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&u)<<8)+(u>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&u))e.msg="unknown compression method",s.mode=30;else{if(c-=4,C=8+(15&(u>>>=4)),0===s.wbits)s.wbits=C;else if(C>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<C,e.adler=s.check=1,s.mode=512&u?10:12,c=u=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(s.flags=u,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=u>>8&1),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.head&&(s.head.time=u),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,T[2]=u>>>16&255,T[3]=u>>>24&255,s.check=P(s.check,T,4,0)),c=u=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.head&&(s.head.xflags=255&u,s.head.os=u>>8),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.length=u,s.head&&(s.head.extra_len=u),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&((g=a<(g=s.length)?a:g)&&(s.head&&(C=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),N.arraySet(s.head.extra,r,i,g,C)),512&s.flags&&(s.check=P(s.check,r,g,i)),a-=g,i+=g,s.length-=g),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(g=0;C=r[i+g++],s.head&&C&&s.length<65536&&(s.head.name+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=P(s.check,r,g,i)),a-=g,i+=g,C)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===a)break e;for(g=0;C=r[i+g++],s.head&&C&&s.length<65536&&(s.head.comment+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=P(s.check,r,g,i)),a-=g,i+=g,C)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(u!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=u=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===a)break e;a--,u+=r[i++]<<c,c+=8}e.adler=s.check=x(u),c=u=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=o,e.avail_out=l,e.next_in=i,e.avail_in=a,s.hold=u,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)u>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:D=b=void 0;var D,b=s;if(B){for(q=new N.Buf32(512),V=new N.Buf32(32),D=0;D<144;)b.lens[D++]=8;for(;D<256;)b.lens[D++]=9;for(;D<280;)b.lens[D++]=7;for(;D<288;)b.lens[D++]=8;for(w(1,b.lens,0,288,q,0,b.work,{bits:9}),D=0;D<32;)b.lens[D++]=5;w(2,b.lens,0,32,V,0,b.work,{bits:5}),B=!1}if(b.lencode=q,b.lenbits=9,b.distcode=V,b.distbits=5,s.mode=20,6!==t)break;u>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}u>>>=2,c-=2}break;case 14:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if((65535&u)!=(u>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&u,c=u=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(g=s.length){if(0===(g=l<(g=a<g?a:g)?l:g))break e;N.arraySet(n,r,i,g,o),a-=g,i+=g,l-=g,o+=g,s.length-=g}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(s.nlen=257+(31&u),u>>>=5,c-=5,s.ndist=1+(31&u),u>>>=5,c-=5,s.ncode=4+(15&u),u>>>=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===a)break e;a--,u+=r[i++]<<c,c+=8}s.lens[R[s.have++]]=7&u,u>>>=3,c-=3}for(;s.have<19;)s.lens[R[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,y={bits:s.lenbits},M=w(0,s.lens,0,19,s.lencode,0,s.work,y),s.lenbits=y.bits,M){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(;v=(O=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&O,!((m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(f<16)u>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(A=m+2;c<A;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(u>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}C=s.lens[s.have-1],g=3+(3&u),u>>>=2,c-=2}else if(17===f){for(A=m+3;c<A;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}C=0,g=3+(7&(u>>>=m)),u>>>=3,c=c-m-3}else{for(A=m+7;c<A;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}C=0,g=11+(127&(u>>>=m)),u>>>=7,c=c-m-7}if(s.have+g>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;g--;)s.lens[s.have++]=C}}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,y={bits:s.lenbits},M=w(1,s.lens,0,s.nlen,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,y={bits:s.distbits},M=w(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,y),s.distbits=y.bits,M){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<=a&&258<=l){e.next_out=o,e.avail_out=l,e.next_in=i,e.avail_in=a,s.hold=u,s.bits=c,G(e,h),o=e.next_out,n=e.output,l=e.avail_out,i=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(O=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&O,!((m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(v&&!(240&v)){for(I=m,E=v,S=f;v=(O=s.lencode[S+((u&(1<<I+E)-1)>>I)])>>>16&255,f=65535&O,!(I+(m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,s.length=f,0===v){s.mode=26;break}if(32&v){s.back=-1,s.mode=12;break}if(64&v){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&v,s.mode=22;case 22:if(s.extra){for(A=s.extra;c<A;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.length+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(O=s.distcode[u&(1<<s.distbits)-1])>>>16&255,f=65535&O,!((m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(!(240&v)){for(I=m,E=v,S=f;v=(O=s.distcode[S+((u&(1<<I+E)-1)>>I)])>>>16&255,f=65535&O,!(I+(m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,64&v){e.msg="invalid distance code",s.mode=30;break}s.offset=f,s.extra=15&v,s.mode=24;case 24:if(s.extra){for(A=s.extra;c<A;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.offset+=u&(1<<s.extra)-1,u>>>=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===l)break e;if(s.offset>(g=h-l)){if((g=s.offset-g)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}p=g>s.wnext?(g-=s.wnext,s.wsize-g):s.wnext-g,g>s.length&&(g=s.length),_=s.window}else _=n,p=o-s.offset,g=s.length;for(l-=g=l<g?l:g,s.length-=g;n[o++]=_[p++],--g;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;n[o++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[i++]<<c,c+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?P:L)(s.check,n,h,o-h)),h=l,(s.flags?u:x(u))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=u=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(u!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}c=u=0}s.mode=29;case 29:M=1;break e;case 30:M=-3;break e;case 31:return-4;default:return k}return e.next_out=o,e.avail_out=l,e.next_in=i,e.avail_in=a,s.hold=u,s.bits=c,(s.wsize||h!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&j(e,e.output,e.next_out,h-e.avail_out)?(s.mode=31,-4):(d-=e.avail_in,h-=e.avail_out,e.total_in+=d,e.total_out+=h,s.total+=h,s.wrap&&h&&(e.adler=s.check=(s.flags?P:L)(s.check,n,h,e.next_out-h)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),M=(0==d&&0===h||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&L(1,t,r,0)!==s.check?-3:j(e,t,r,r)?(s.mode=31,-4):(s.havedict=1,U)},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var G=e("../utils/common"),w=[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],U=[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],k=[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],F=[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,r,n,i,o,a){for(var l,u,c,d,h,g,p,_,m,v=a.bits,f=0,I=0,E=0,S=0,C=0,M=0,y=0,A=0,O=0,T=0,R=null,D=0,b=new G.Buf16(16),N=new G.Buf16(16),L=null,P=0,f=0;f<=15;f++)b[f]=0;for(I=0;I<r;I++)b[t[s+I]]++;for(C=v,S=15;1<=S&&0===b[S];S--);if(S<C&&(C=S),0===S)n[i++]=20971520,n[i++]=20971520,a.bits=1;else{for(E=1;E<S&&0===b[E];E++);for(C<E&&(C=E),f=A=1;f<=15;f++)if((A=(A<<1)-b[f])<0)return-1;if(0<A&&(0===e||1!==S))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+b[f];for(I=0;I<r;I++)0!==t[s+I]&&(o[N[t[s+I]]++]=I);if(g=0===e?(R=L=o,19):1===e?(R=w,D-=257,L=U,P-=257,256):(R=k,L=F,-1),f=E,h=i,y=I=T=0,c=-1,d=(O=1<<(M=C))-1,1===e&&852<O||2===e&&592<O)return 1;for(;;){for(m=o[I]<g?(_=0,o[I]):o[I]>g?(_=L[P+o[I]],R[D+o[I]]):(_=96,0),l=1<<(p=f-y),E=u=1<<M;n[h+(T>>y)+(u-=l)]=p<<24|_<<16|m,0!==u;);for(l=1<<f-1;T&l;)l>>=1;if(0!==l?T=(T&l-1)+l:T=0,I++,0==--b[f]){if(f===S)break;f=t[s+o[I]]}if(C<f&&(T&d)!==c){for(h+=E,A=1<<(M=f-(y=0===y?C:y));M+y<S&&!((A-=b[M+y])<=0);)M++,A<<=1;if(O+=1<<M,1===e&&852<O||2===e&&592<O)return 1;n[c=T&d]=C<<24|M<<16|h-i}}0!==T&&(n[h+T]=f-y<<24|64<<16),a.bits=C}return 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 d=e("./zlib/inflate"),h=e("./utils/common"),g=e("./utils/strings"),p=e("./zlib/constants"),r=e("./zlib/messages"),n=e("./zlib/zstream"),i=e("./zlib/gzheader"),_=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options,e=(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 n,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==p.Z_OK)throw new Error(r[e]);if(this.header=new i,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=g.string2buf(t.dictionary):"[object ArrayBuffer]"===_.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==p.Z_OK)throw new Error(r[e])}function a(e,t){t=new o(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}o.prototype.push=function(e,t){var s,r,n,i,o,a=this.strm,l=this.options.chunkSize,u=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?p.Z_FINISH:p.Z_NO_FLUSH,"string"==typeof e?a.input=g.binstring2buf(e):"[object ArrayBuffer]"===_.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new h.Buf8(l),a.next_out=0,a.avail_out=l),(s=(s=d.inflate(a,p.Z_NO_FLUSH))===p.Z_NEED_DICT&&u?d.inflateSetDictionary(this.strm,u):s)===p.Z_BUF_ERROR&&!0===c&&(s=p.Z_OK,c=!1),s!==p.Z_STREAM_END&&s!==p.Z_OK)return this.onEnd(s),!(this.ended=!0)}while(!a.next_out||0!==a.avail_out&&s!==p.Z_STREAM_END&&(0!==a.avail_in||r!==p.Z_FINISH&&r!==p.Z_SYNC_FLUSH)||("string"===this.options.to?(n=g.utf8border(a.output,a.next_out),i=a.next_out-n,o=g.buf2string(a.output,n),a.next_out=i,a.avail_out=l-i,i&&h.arraySet(a.output,a.output,n,i,0),this.onData(o)):this.onData(h.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(c=!0),(0<a.avail_in||0===a.avail_out)&&s!==p.Z_STREAM_END);return(r=s===p.Z_STREAM_END?p.Z_FINISH:r)===p.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===p.Z_OK):r!==p.Z_SYNC_FLUSH||(this.onEnd(p.Z_OK),!(a.avail_out=0))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===p.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=o,s.inflate=a,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,a(e,t)},s.ungzip=a},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")),Xt.exports),es=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=xt,this._currentConnectState=Ft,this._beforeSendInterceptors=[]}init(){ht.addTask({id:Ut,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:r}=Be.get("instance"),n=nt(t);let i="";return s?i=et.TEST[n].DEFAULT:r?(i=et.PRODUCTION[n].DEFAULT,rt=ot.DEFAULT):i=et.PRODUCTION[n].INITIAL.replace("*",""+t),ct(i,{isBinary:e})}(this._isBinarySupported),be.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),be.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:n=Gt,canResend:i=!0}=t||{};if(ve(e))return Pt.warn("sendPacket",wt+".sendPacket: packet is empty "),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===qt&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:jt});var o=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=Ee();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:n,canResend:i})}t=this._isBinarySupported?gt(o).buffer:o;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new je(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),t=wt+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t})}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=wt+".disconnect socketID:"+e;this._ssoLog({method:"disconnect",message:e}),this._removeEventListeners(),null!=(e=this._socketAdapter)&&e.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(wt+".dispose"),ht.removeTask(Ut),ht.removeTask(kt),be.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),be.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=xt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(var t of this._beforeSendInterceptors){var{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){var e=this._currentConnectState===$t&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return de(this,void 0,void 0,function*(){var e=`${wt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=ut(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Kt}),console.warn(wt+".reconnect failed: ",e)}}})}_addEventListeners(){var e;null!=(e=this._socketAdapter)&&e.on("connect",this._onConnect,this),null!=(e=this._socketAdapter)&&e.on("message",this._onMessage,this),null!=(e=this._socketAdapter)&&e.on("close",this._onClose,this),null!=(e=this._socketAdapter)&&e.on("error",this._onError,this),null!=(e=this._socketAdapter)&&e.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e;null!=(e=this._socketAdapter)&&e.off("connect",this._onConnect,this),null!=(e=this._socketAdapter)&&e.off("message",this._onMessage,this),null!=(e=this._socketAdapter)&&e.off("close",this._onClose,this),null!=(e=this._socketAdapter)&&e.off("error",this._onError,this),null!=(e=this._socketAdapter)&&e.off("sendFail",this._onSendFail,this)}_onClose(e){var{socketId:e,event:t}=e||{},s=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,s=`${wt}.onClose closeSocketID: ${e} currentSocketID: ${this._connectionId} connectionDuration: ${s} code: ${null==t?void 0:t.code} reason: `+(null==t?void 0:t.reason);this._ssoLog({method:"onClose",message:s}),e===this._connectionId&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Wt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=`${wt}.onError sourceSocketID: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+JSON.stringify(t);this._ssoLog({method:"onError",message:t}),e===this._connectionId&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Ht}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=`${wt}.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(t){let s,e;this._updateHeartbeatTime();try{s=this._isBinarySupported?(this._isCompressedData(t.data)?e=>{var t=new Uint8Array(e).slice(4);let s;try{s=Zt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var n=new Uint8Array(e);let i="",o=0;for(var a=n["length"];o<a;){let t=n[o],s=0,r=0;if(t<=127?(s=0,r=255&t):t<=223?(s=1,r=31&t):t<=239?(s=2,r=15&t):t<=244&&(s=3,r=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=n[o+e+1],r=r<<6|63&t;else r=65533,s=a-o;i+=String.fromCodePoint(r),o+=s+1}return i})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return void this._ssoLog({method:"jsonParseError",message:e})}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:n}=(null==e?void 0:e.body)||{},i=(null==(i=null==e?void 0:e.body)?void 0:i.ErrorCode)||r,r=(null==(r=null==e?void 0:e.body)?void 0:r.ErrorInfo)||n,n=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(n);this._pendingRequests.delete(n),i&&0!==i?(be.emitInnerEvent("error",{errorCode:i,errorInfo:r}),s({errorCode:i,errorInfo:r})):t(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),be.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;Pt.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:n,reject:i,timeout:o}=e;if(r){this._pendingRequests.set(t,{resolve:n,reject:i,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:r});let e=this._isBinarySupported?gt(s).buffer:s;null!=(n=this._socketAdapter)&&n.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=wt+`.onConnect cost:${s} ms. socketID:${e} res:`+JSON.stringify(t);if(this._ssoLog({method:"onConnect",message:s}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){let e=wt+".reconnect success";this._ssoLog({method:"reconnectSuccess",message:e}),be.emitInnerEvent(At.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ft,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=mt({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return de(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var e;return(null==(e=this._socketAdapter)?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return de(this,void 0,void 0,function*(){var e,t=mt({servcmd:"heartbeat.alive",data:{}});try{let e=""+t.head.seq+t.head.servcmd;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){var s=null==(e=Be.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=wt+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return de(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=L?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=wt+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),e);t&&"none"!==e?this._handleConnectStateChange({state:Ft,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Vt}):this._handleConnectStateChange({state:qt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Vt})}isPrivateNetWork(){var e=Be.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:r}=e,r=`${wt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+r;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:r}),s&&(Pt.info("_handleConnectStateChange",` from ${this._currentConnectState} to `+e),be.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===qt)&&be.emitInnerEvent(At.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),ht.addTask({id:kt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}_handleActivityStatusChange(e){var t=null==(t=null==(t=this._socketAdapter)?void 0:t._ws)?void 0:t.readyState,e=`${wt}.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),3===t&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Bt})}_resetReconnectDelay(){Pt.debug(wt+"._resetReconnectDelay"),ht.removeTask(kt);var e=null==(e=Be.get("activityMonitor"))?void 0:e.isActive;this._intendedDelay=e?xt:1e3}_scheduleReconnectWithBackoff(){var e=null==(e=Be.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(xt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=wt+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;Pt.debug(e),this.reconnect(),ht.updateTaskInterval(kt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Pt.info(e,t)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){de(this,void 0,void 0,function*(){var e=t.split("/")[2];if(e.startsWith("ws")){e=`https://${e}/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield me({method:"GET",url:e,data:{}})}catch(e){Pt.warn("diagnoseBySSO","diagnoseBySSO failed. error:"+e.message)}}})}(this._url),function(t){de(this,void 0,void 0,function*(){var e=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield me({method:"GET",url:e,data:{}})}catch(e){Pt.warn("diagnoseByCDN', 'diagnoseByCDN failed. error:"+e.message)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(var[e,t]of this._pendingRequests.entries()){var{reject:t,timestamp:s,timeout:r}=t;Date.now()-s>=r&&(this._pendingRequests.delete(e),3e4<=Date.now()-this._lastDiagnoseAt&&this._diagnose(),t({errorCode:ge,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=Be.get("instance"))&&e.devMode||(e=ue(),b)||y&&"windows"===e||L)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let ts={init:function(e){Be.set("instance",e),es.init()},destroy:function(){es.dispose(),Be.clear(),ht.dispose()},notificationCenter:be,channel:es,store:Be,ssoLog:Pt,utils:Ce,common:Ct,constants:C},ss=e=>"function"==typeof e;function ns(t,s,r){let n=r||[];var e,i;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!n.includes(e)),i=Object.keys(s).filter(e=>!n.includes(e)),e.length===i.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?ns(t[e],s[e],r):t[e]===s[e]))}!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"}(os=os||{});var is,rs=os;!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"}(is=is||{});var as,hs,ps,cs=is,us=(!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"}(as=as||{}),as);let ls=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),ds={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"},gs=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(hs=hs||{}),{modify:cs.MESSAGE_MODIFIED,delete:cs.MESSAGE_DELETED,revoke:cs.MESSAGE_REVOKED}),_s=(!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(ps=ps||{}),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ds),{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:hs,Direction:ps})),ms={[gs.modify]:cs.TOPIC_MESSAGE_MODIFIED,[gs.delete]:cs.TOPIC_MESSAGE_DELETED,[gs.revoke]:cs.TOPIC_MESSAGE_REVOKED},vs={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"},fs=Object.assign({},vs),Is={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Es=Object.assign(Object.assign(Object.assign(Object.assign({},Is),{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"}),Ss=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"}),Cs={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},Ms={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ys={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},Os=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Cs),{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:Ms,GROUP_TIPS_OPERATION_TYPE:ys}),As=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ls),_s),fs),Es),Ss),Os),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),Ts={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},Rs={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},Ds={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"},bs={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"},Ns={[Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:bs.USER_STATUS_UPDATE},{stepId:bs.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CONVERSATION_RECOVER},{stepId:bs.HISTORY_MESSAGE_RECOVER,dependency:bs.CONVERSATION_RECOVER},{stepId:bs.BLACKLIST_RECOVER},{stepId:bs.FRIEND_RECOVER},{stepId:bs.GROUP_REVOKED_NOTICE_RECOVER,dependency:bs.HISTORY_MESSAGE_RECOVER},{stepId:bs.GROUP_TIPS_RECOVER,dependency:bs.HISTORY_MESSAGE_RECOVER},{stepId:bs.TOPIC_REQUEST_INFO_RESET},{stepId:bs.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_RECOVER]},{stepId:bs.EMIT_C2C_MESSAGE_EVENT,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[Ds.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:bs.COMMERCIAL_CONFIG_UPDATE},{stepId:bs.CLOUD_CONFIG_SYNC},{stepId:bs.USER_PROFILE_SYNC},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.FRIEND_AND_BLACKLIST_SYNC},{stepId:bs.GROUP_LIST_SYNC},{stepId:bs.CONVERSATION_LIST_SYNC},{stepId:bs.SIGNALING_MESSAGE_RECOVER,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC]},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_LIST_SYNC]},{stepId:bs.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[bs.GROUP_LIST_SYNC,bs.CONVERSATION_LIST_SYNC]},{stepId:bs.CONVERSATION_GROUP_LIST_SYNC},{stepId:bs.CONVERSATION_GROUP_UPDATE,dependency:[bs.CONVERSATION_LIST_SYNC,bs.CONVERSATION_GROUP_LIST_SYNC]},{stepId:bs.QUALITY_REPORT}],[Ds.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:bs.HANDLE_C2C_NEW_MESSAGE},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_C2C_NEW_MESSAGE},{stepId:bs.EMIT_C2C_MESSAGE_EVENT,dependency:[bs.HANDLE_C2C_NEW_MESSAGE,bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC]}],[Ds.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.UPDATE_GROUP_NEXT_SEQUENCE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.EMIT_GROUP_MESSAGE_EVENT,dependency:[bs.HANDLE_GROUP_NEW_MESSAGE,bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Ds.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:bs.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_TIPS_NOTIFICATION}]},Ls={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Ps={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},Gs=["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","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var Us,ks,Fs,ws=Object.freeze({__proto__:null,ERROR_CODE:Ts,InnerEvent:cs,NEED_LOG_API:Gs,OuterConstant:As,OuterEvent:rs,QUALITY_METRICS:Ls,SDK_EDITION:Rs,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Ps,SignalingEvent:us,WORKFLOW_DEFINITIONS:Ns,WORKFLOW_NAME:Ds,WORKFLOW_STEP:bs});!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Us=Us||{}),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(ks=ks||{}),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(Fs=Fs||{});let $s={[ks.multipleAccount]:"multipleAccount",[ks.multipleDevice]:"multipleDevice",[ks.restApi]:"REST_API_Kick",[Fs.multipleAccount]:"multipleAccount",[Fs.multipleDevice]:"multipleDevice",[Fs.restApi]:"REST_API_Kick",[Fs.usersigExpired]:"userSigExpired"},qs="login_online_presence_task",{ERROR:xs,DESTROY:Vs,FORCE_OFFLINE:Bs}=cs,{KICKED_OUT_MULT_ACCOUNT:js,KICKED_OUT_MULT_DEVICE:Ks,KICKED_OUT_REST_API:Hs,ACCOUNT_A2KEY_EXPIRED:Ws,MSG_A2KEY_EXPIRED:Ys}=Ts;class zs{init(){var e=ts["notificationCenter"];e.subscribeInnerEvent(Bs,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(xs,Ys,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Ws,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,js,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Ks,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Hs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Vs,this._dispose,this)}_handleForceOfflineFromServerPush(e){var{EventArray:e=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(e).forEach(e=>{var{KickType:e,NewInstInfo:t}=e["KickoutMsgNotify"];this._processKickedOutReasonInfo({kickedOutReasonCode:e,newInstanceInfo:t})})}_extractKickedOutMessages(e){return e.reduce((e,t)=>[...e,...t.C2cNotifyMsgArray||[]],[]).filter(e=>{return this._isKickedOut(null==(e=null==e?void 0:e.KickoutMsgNotify)?void 0:e.KickType)})}_handleForceOfflineFromResponse(e){e=e.errorCode;this._processKickedOutReasonInfo({kickedOutReasonCode:e})}_processKickedOutReasonInfo(r){return de(this,void 0,void 0,function*(){var e=r["kickedOutReasonCode"],{ssoLog:t,utils:{safeStringify:s}}=ts;try{this._logKickedOutEvent(r),yield ts.login.loginAction.logout(Us.KICKED_OUT)}catch(e){t.debug("_processKickedOutReasonInfo"," fail "+s(e))}finally{ts.notificationCenter.emitOuterEvent(rs.KICKED_OUT,{data:{type:$s[e]},name:rs.KICKED_OUT}),[ks.restApi,Ws,Ys].includes(e)&&ts.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,e=`type:${$s[e]} newInstanceInfo: `+JSON.stringify(t);ts.ssoLog.warn("kickedOut",e)}_isKickedOut(e){return[ks.multipleAccount,ks.multipleDevice,ks.restApi].includes(e)}_dispose(){var e=ts["notificationCenter"];e.unSubscribeInnerEvent(Bs,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(xs,Ws,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Ys,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,js,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Ks,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Hs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Vs,this._dispose,this)}}function Js(r){return de(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=ts.common.generateProtocolData({servcmd:e,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:r}}),s=""+t.head.seq+e,d=yield ts.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:n,PurchaseBits:i,A2Key:o,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:u,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:n,purchaseBits:i,a2Key:o,authKey:a,errorCode:l,errorInfo:u,actionStatus:c}}})}function Qs(t){var s;try{var r=Be.getStorage("errorMessage");if(!t||!r)return"";var n=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:i=!1,code:o,replacement1:a="",replacement2:l=""}=t;if(!o)return"";var u=i?o+"_en":o+"_cn";let e=n[n[u]?u:o]||"";return e=e&&(a&&(e=e.replace("$replacement1",a)),l)?e.replace("$replacement2",l):e}catch(t){return console.warn("Error parsing stored error messages:",t),""}}class Xs extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:n="",moreMessage:i=""}=e;let o=r;s&&!r&&(o=Qs(e));r=(s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`)+" "+i;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=n}}function Zs(e,t){if(e&&!0!==(null==(e=ts.store.get("login"))?void 0:e.isLoggedIn))throw new Xs({code:Ts.USER_NOT_LOGGED_IN,functionName:t})}function en(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)tn.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)tn.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function tn({required:e,rules:r,value:t,allowEmpty:n,name:i,key:o,customValidator:a}){if(void 0===t){if(e)throw new Xs({functionName:i,message:`[${i}] Missing required params: "${o}"`})}else{let s="";if(!r.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<r.length;t++){let e=r[t];e=e.replace(e[0],e[0].toUpperCase()),s+=e+"/"}let e=`[${o}] must be type of ${s=s.substring(0,s.length-1)}, received type: ${Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}.`;throw new Xs({functionName:i,message:e})}if(!1===n){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new Xs({functionName:i,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new Xs({functionName:i,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new Xs({functionName:i,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let sn=[],nn={},on={};function rn(e,t){var s;Zs(nn[e],e),en(on[e],t,e),s=e,sn.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function an(e,t){sn.push({interceptor:e,context:t})}function cn(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(on,e),t&&"object"==typeof t&&Object.assign(nn,t)}function un(e){return ts.store.get("commercialConfig").get(e)}class ln{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{var s=Date.now();t?(this._stepStartTimes.set(e+"-"+t,s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var{ssoLog:n,utils:{safeStringify:i}}=ts,o=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?o-t:0;this._stepStartTimes.delete(s+"-"+e),n.error("_executeWorkflowStep",`[Workflow ${s}] Step ${e} failed at ${new Date(o).toISOString()} (${t}ms) `+i(r),{error:r})}else{let e=this._workflowStartTimes.get(s),t=e?o-e:0;this._workflowStartTimes.delete(s),n.error("_executeWorkflowStep",`[Workflow ${s}] failed at ${new Date(o).toISOString()} (${t}ms) `+i(r),{error:r})}}}}static getInstance(){return ln._instance||(ln._instance=new ln),ln._instance}static setInstance(e){ln._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){var n;this._handlers.has(e)?Ns[e].find(e=>e.stepId===t)?(n=this._handlers.get(e)).has(t)||n.set(t,r?s.bind(r):s):ts.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`):ts.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return de(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){ts.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=Ns[o],i={cancelled:!1};this._activeWorkflows.set(o,{cancelToken:i});try{let t=new Map,n=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:o,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:i});yield new Promise((t,s)=>{let r=()=>{i.cancelled?t():this._getExecutableSteps({pendingSteps:n.pendingSteps,completedSteps:n.completedSteps,stepMap:n.stepMap,workflowName:o}).filter(e=>!n.runningSteps.has(e)).forEach(e=>{n.completedSteps.has(e)||n.runningSteps.has(e)||this._executeWorkflowStep(e,n,{onComplete:()=>{0===n.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:n.pendingSteps,completedSteps:n.completedSteps,stepMap:n.stepMap,workflowName:o}).filter(e=>!n.runningSteps.has(e)).length&&0===n.runningSteps.size&&(ts.ssoLog.debug("executeWorkflow",`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),ts.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Completed execution at `+(new Date).toISOString())}catch(e){ts.ssoLog.error("executeWorkflow",`[Workflow ${o}] Failed execution at `+(new Date).toISOString(),{error:e})}finally{this._activeWorkflows.delete(o)}}})}_executeWorkflowStep(l,u,c){return de(this,void 0,void 0,function*(){let{workflowName:i,runningSteps:e,stepMap:r,stepResults:n,data:o}=u;e.add(l),this._logWorkflowExecution(i,l,"start");try{let e=r.get(l),s=null;null!=e&&e.dependency&&(t(e.dependency)?s=n[e.dependency]:Array.isArray(e.dependency)&&(s={},e.dependency.forEach(e=>{s[e]=n[e]})));var a=this._handlers.get(i).get(l);if(a){let e=yield Promise.resolve(a({data:o,result:s}));n[l]=e,this._logWorkflowExecution(i,l,"success")}u.completedSteps.add(l)}catch(e){let t=`[Workflow].${i}.`+l,{errorCode:s,errorInfo:r=t+" failed"}=e||{},n=new Xs({functionName:t,code:s,message:r});ts.ssoLog.error(t,r,{error:n}),this._logWorkflowExecution(i,l,"error",e),c.onError(e)}finally{e.delete(l),u.pendingSteps.delete(l),c.onStepComplete(),c.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ns).forEach(e=>{this._handlers.has(e)||this._handlers.set(e,new Map)})}_cancelWorkFlow(e){var t=this._activeWorkflows.get(e);t&&(t=t["cancelToken"],t.cancelled=!0,this._activeWorkflows.delete(e))}_cancelAllWorkflows(){Object.keys(Ns).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return!!Ns[e]&&!!this._handlers.get(e)}_getExecutableSteps(e){let{pendingSteps:s,completedSteps:r,stepMap:i,workflowName:o}=e;return Array.from(s).filter(e=>{var{dependency:s,skipIfDependencyMissing:e=!0}=i.get(e)||{};if(!s)return!0;if(t(s))return this._isStepRegistered({workflowName:o,stepId:s})?r.has(s):!e;if(n(s)){if(0<s.filter(e=>!this._isStepRegistered({workflowName:o,stepId:e})).length&&e)return!1;for(let e of s)if(!r.has(e))return!1;return!0}return!1})}_isStepRegistered(e){var{workflowName:e,stepId:t}=e;return null==(e=this._handlers.get(e))?void 0:e.has(t)}_logWorkflowExecution(e,t,s,r){this._logHandlers[s](e,t)}}let dn=new Map,hn=({type:e,groupID:t})=>e===As.GRP_COMMUNITY||(""+t).startsWith(Ms.COMMUNITY)&&!(""+t).includes(Ms.TOPIC),gn=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(Ms.COMMUNITY)&&(""+e).includes(Ms.TOPIC)},pn="openim",_n="million_group_open_http_svc";function mn(s){return de(this,void 0,void 0,function*(){var{servcmd:e,data:t}=vn(e=s.data)||fn(e)?function(e){let{servcmd:t,data:s}=e;var r,n,i;return fn(s)?({servcmd:e,data:r}=e,{GroupId:n=""}=r,[n]=(i=n).split(Ms.TOPIC),{servcmd:In(e),data:Object.assign(Object.assign({},r),{GroupId:n,TopicId:i})}):{servcmd:t=vn(s)?In(t):t,data:s}}(s):s,t=ts.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return ts.channel.sendPacket(t,{requestId:e})})}function vn(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return hn({type:e,groupID:t})}function fn(e){var{GroupId:e=""}=e;return gn(e)}function In(e){return e.includes(pn)?e:(e=e.split(".")[1],_n+"."+e)}function En(){var e;return null==(e=ts.store.get("login"))?void 0:e.userId}let Sn=e=>n(e)||o(e),Cn=(r,n,i,o)=>{if(!Sn(r)||!Sn(n))return 0;let a=0;var l,u=Object.keys(n);for(let t=0,s=u.length;t<s;t++)if(l=u[t],!(e(n[l])||i&&i.includes(l)))if(Sn(r[l])&&Sn(n[l]))a+=Cn(r[l],n[l],i,o);else{if(o&&o.includes(n[l]))continue;r[l]!==n[l]&&(r[l]=n[l],a+=1)}return a},Mn=(t,s)=>{if(e(s))return"";switch(t){case As.MSG_TEXT:return s.text||"";case As.MSG_IMAGE:return"[Image]";case As.MSG_LOCATION:return"[Location]";case As.MSG_AUDIO:return"[Voice]";case As.MSG_VIDEO:return"[Video]";case As.MSG_FILE:return"[File]";case As.MSG_CUSTOM:return"[Custom Messages]";case As.MSG_GRP_TIP:return"[Group Notification]";case As.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case As.MSG_FACE:return"[Animated Sticker]";case As.MSG_MERGER:return"[Chat Record]";default:return""}},yn=[{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}],On="im_sdk_config_mgr.fetch_config",An="im_sdk_config_mgr.push_configv2",Tn="cloud-config",Rn=2996,Dn=new class{init(e){this.core=e}};function bn(s){return de(this,void 0,void 0,function*(){var e=(Dn.core.store.get("instance")||{})["sdkAppId"],e=Dn.core.helper.generateProtocolData({servcmd:On,data:{uint32_sdkappid:e,uint64_version:s}}),t=""+e.head.seq+On;return Dn.core.channel.sendPacket(e,{requestId:t})})}var Nn=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){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n},channel:i}=this._core=e;e.subscribeInnerEvent(An,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(yn),i.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return de(this,void 0,void 0,function*(){var e,t={code:0,data:""};return s&&(t.data=(null==(e=this._core.store.get("cloudConfig"))?void 0:e[s])||""),t})}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:n}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:n+=1}),t<n)throw new this._core.helper.ChatError({code:Rn,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_handlePushedConfig(s){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.info("_handlePushedConfig",t(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return de(this,void 0,void 0,function*(){var e,{ssoLog:t,utils:{safeStringify:s}}=this._core;try{this._canFetch()&&(e=yield bn(this._version),t.info("_fetchCloudConfigIfLogin",s(e)),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:Tn,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){t.error("_fetchCloudConfigIfLogin",s(e))}})}_fetchCloudConfigIfReady(){return de(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._canFetch())try{var e=yield bn(this._version);t.info("_fetchCloudConfigIfReady",s(e)),yield this._updateCloudConfig(e)}catch(e){t.error("_fetchCloudConfigIfReady",s(e))}})}_updateCloudConfig(t){return de(this,void 0,void 0,function*(){var e=this._parseCloudConfig(t);e&&(this._core.store.set("cloudConfig",e),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:e}}))})}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:n}=e;let i=null;if(0===t){if(this._version!==n)try{i=JSON.parse(s),this._version=n}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return i}_parseCmdFreqLimit(){return de(this,void 0,void 0,function*(){var e,t=null==(e=yield this.getServerConfig("cmd_frequency_limit"))?void 0:e.data,s=this._core.utils["isEmpty"];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(Tn),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(yn),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(An,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(){var 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}}let Pn={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()},Gn="CommercialConfig",wn="commercial-config";var xn,Vn,Un=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){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n,InnerEvent:i}}=this._core=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(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return de(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let n,i=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(n=(t<32?new Ln(0,2**t):new Ln(2**(t-32),0)).toString(),!this._featureMap.get(n))){i=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${Gn}.isFeatureEnabled decimalNumber:${e} key:${n} ret:`+i),{code:0,data:{enabled:i}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return de(this,void 0,void 0,function*(){let s,{ssoLog:e,helper:r,utils:{safeStringify:t}}=this._core;try{this._isFetching=!0;let e=r.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null==(s=this._core.store.get("instance"))?void 0:s.sdkAppId}}),t=yield this._core.channel.sendPacket(e);null!=t&&t.body&&(this._parseCommercialConfig(t.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(s){e.error("_fetchAndParseCommercialConfig",t(s))}finally{this._isFetching=!1}})}_syncCommercialConfig(t){return de(this,void 0,void 0,function*(){var e=((null==t?void 0:t.data)||{})["purchaseBits"];e&&(this._parsePurchaseBits(e),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:wn,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var e=null==(e=this._core.store.get("login"))?void 0:e.isLoggedIn,t=Date.now()>=this._expirationTime;return e&&!this._isFetching&&t}_handlePushedConfig(e){null!=e&&e.body&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return de(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,n,i=this._core["ssoLog"];"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:n}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*n):void 0===t?(i.warn("_parseCommercialConfig",Gn+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(i.warn("_parseCommercialConfig",Gn+`._parseCommercialConfig errorCode:${t} errorMessage:`+s),this._expirationTime=Date.now()+12e4))}_isValidPurchaseBits(e){return e&&"string"==typeof e&&1<=e.length&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(s){var{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new Ln(0,2**t):new Ln(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(Pn,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(Pn,r);e&&this._methodKeyMap.set(e,!1)}}else e.warn("_parsePurchaseBits",Gn+".parsePurchaseBits invalid purchases:"+t(s))}_getKeyByValue(e,t){e=Object.entries(e).find(([,e])=>e===t);return e?e[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(wn),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},kn=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;var{notificationCenter:e,InnerEvent:t,channel:s}=this._core;e.subscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(this._serverOverloadInfoMap.has(e)){var{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){var{OverLoadServCmd:e,DelaySecs:t}=e;this._serverOverloadInfoMap.set(e,{overloadStartTimestamp:Date.now(),delaySeconds:t})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();var{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)}},Fn=new class{constructor(){this.name="ConfigCenter"}install(e){Dn.init(e),Nn.install(e),Un.install(e),kn.install(e)}},$n=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return de(this,void 0,void 0,function*(){if(this._core=e,this._canFetch()){let e=yield this._fetchErrorMessage();var t;e&&(t=this._parseResponse(e),this._saveErrorMessage(t))}})}_canFetch(){var 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 de(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){return!e||(e=e["errorMessageSavedTime"],e&&6048e5<=(new Date).getTime()-e)}_parseResponse(e){if("string"==typeof e){var s=e.split(";\n"),r={},n=new RegExp(/'/g);for(let t=0;t<s.length;t++){var i=s[t].indexOf(":"),o=s[t].slice(0,i);let e=s[t].slice(i+1);o.startsWith("//")||""!==e&&(e=e.replace(n,""),r[o]=e)}return r}}};function qn(n,l){return de(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=n,r="openim.getmsg",o=l.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+r;try{let e=yield l.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:n,revokedMessageList:i}=function(e,E){let r=[],n=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:n,MsgClientTime:i,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,To_Account:d,TinyId:h,MsgCheckResult:g,CloudCustomData:p,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:i,messageFlagBits:m,random:o,sequence:a,time:l,messageControlInfo:u,isSupportExtension:c,to:d,tinyID:h,checkResult:g,cloudCustomData:p,messageVersion:v,eventArray:f,elements:E.message.messageHelper.parseServerPushMessageElement(n)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))n.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=E.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:n}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:n,revokedMessageList:i,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}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"}(xn=xn||{}),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Vn=Vn||{});var Bn=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){var t=(this._core=e)["constants"];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.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(t){return de(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=xn.START_SYNC;for(var u=[],c=[],d=[],h=[];this._canContinueSync({cookie:this._cookie,syncFlag:l});){let e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:l,syncTriggerEvent:a?Vn.NEW_MESSAGE_RECEIVED:Vn.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:n,groupTipList:i}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",l=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:n,overflowUnreadCountList:r,conversationUpdateFieldList:u}),Array.isArray(i)&&c.push(...i),o){let e=this._handleNewMessageList(t)["messages"];h.push(...e)}}return o?{conversationUpdateFieldList:u,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c,messages:h}:{conversationUpdateFieldList:u,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c}})}_syncUnreadDBMessageAfterLogin(){return de(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return de(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:r}=e,{OuterConstant:{CONV_C2C:n,CONV_SYSTEM:i}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==i){let e=r.find(({conversationID:e})=>e===""+n+t);e?e.unreadCount=s:r.push({conversationID:""+n+t,unreadCount:s,type:n})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===i||r.find(({conversationID:e})=>e===""+n+t)||r.push({conversationID:""+n+t,type:n,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return de(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let n=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:i,avatar:o,conversationID:a=""}=r;if(s!==t){let s=n.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;i&&o?i===e&&o===t||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=n.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!0})}}_handleNewMessageList(e){let t=(this._core.message||{})["messageDataHandler"],l=new Map,s=[];return e.forEach(a=>{this._updateMessageProfile(a);let e=1===a.isModified;if(t.isMessageSentByCurrentInstance(a)?a.isModified=e:e=!1,a.isOnlineMessage())a._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(a)||s.push(a);else if(!t.isInMessageList(a)){if(t.storeConversationMessage(a)){let{conversationID:e,conversationType:t,conversationSubType:s,flow:r,_isExcludedFromUnreadCount:n,_isExcludedFromLastMessage:i}=a,o=i?"":a;l.has(e)?(l.get(e).lastMessage=o,"in"!==r||n||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:n||"in"!==r?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:l}}_fetchUnreadDBMessage(c){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;try{e.debug("_fetchUnreadDBMessage","unread-message-synchronizer._fetchUnreadDBMessage options:"+t(c));var s,r,n,i,o,a,l,u=yield qn(c,this._core);return u?({syncFlag:s,unreadMessageList:r,revokedMessageList:n,cookie:i,unreadCountList:o,overflowUnreadCountList:a,groupTipList:l}=u,this._parseAndSaveUnreadMessageList(r),{syncFlag:s,cookie:i,unreadMessageList:r,revokedMessageList:n,unreadCountList:o,overflowUnreadCountList:a,groupTipList:l}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===xn.START_SYNC||t===xn.SYNCING&&!(null!=(t=this._core)&&t.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach(e=>{var t=e["ID"];this._unreadDBMessageMap.set(t,e)})}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},jn=new class{init(e){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!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t="visible"===document.visibilityState;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:t}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:t})}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},Kn=new class{init(e){this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var{MINI_APP_NAMESPACE:e,IN_TT_MINI_GAME:t,IN_WX_MINI_GAME:s}=(null==(e=this._core)?void 0:e.utils)||{};t||s?(null!=(t=null==e?void 0:e.onShow)&&t.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null!=(s=null==e?void 0:e.onHide)&&s.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!1}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):(null!=(t=null==e?void 0:e.onAppShow)&&t.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null!=(s=null==e?void 0:e.onAppHide)&&s.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!1}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},Hn=new class{init(e){var{IN_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Kn:jn).init(e)}};let Wn="none",Yn="online";var zn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return de(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,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Yn})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Wn})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Jn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return de(this,void 0,void 0,function*(){try{var{MINI_APP_NAMESPACE:e}=this._core["utils"];this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),e.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}})}_deactivateNetworkMonitoring(){var e;null!==this._mpNetworkStatusCallback&&({MINI_APP_NAMESPACE:e}=this._core["utils"],e.offNetworkStatusChange&&e.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Qn=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?Jn:zn).init(e)}},Xn=new class{constructor(){this.name="SystemStateMonitor"}install(e){Hn.init(e),Qn.init(e)}};let Zn=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.*"]),eo="tui_room_svr.*";var to=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Zn}install(e){var{notificationCenter:e,InnerEvent:t,helper:s}=this._core=e;e.subscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return de(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=eo}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(i,o){return de(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=eo,data:r}=i||{};let n={};try{n="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:n}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}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{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=Zn}_dispose(){var{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)}};let so=1,no=2,oo=3,io=4,ro=5,ao="TIMCustomElem",co="C2C",uo="GROUP",lo="invite",ho="accept",go="cancel",po="reject",_o="modifyInvitation",mo="signaling",vo=8010,fo="signaling-timeout";function Io(e){return e.filter(e=>{var t,s;return e.type===ao&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function Eo(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function So(e,t){return e.toString(16).padStart(t,"0")}function Co(e){if(e<0||53<e)throw new Error("Number of digits must be between 0 and 53");return e<=30?Math.floor(Math.random()*(1<<e)):(e=e-30,Math.floor(Math.random()*(1<<e))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var Mo=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){(this._core=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){var t=mo+".isInvitationValid",{inviteID:e,groupID:s,inviter:r}=e,r=r===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var n=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(t+` inviteID:${e} inviteeList:${n} groupID:`+s),s){if(r)return 0<n.length;let e=this._core.common.getCurrentUserID();return n.includes(e)}return!0}updateSignaling(e){let s=mo+".updateSignaling",{inviteID:r,inviter:t,inviteeList:n,groupID:i}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+i),i&&this.hasSignaling(r)){let e=n[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},yo=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:n}=e,s=s||(t?r[0]:n);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:n}=e,s=(null==(s=null==(s=Mo.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,n)}}_createMessageControlInfo(e,t){t=t===ro&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){var t=mo+"._createInviteSignalingData",{userID:s,timeout:r=0,groupID:n="",inviteeList:i=[]}=e,o=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:so,inviter:o,inviteeList:n?i:[s],timeout:r});return console.log(t+" signalingData:",e),e}_createAcceptSignalingData(e){var t=mo+"._createAcceptSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:n}=Mo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:oo,groupID:n,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createCancelSignalingData(e){var t=mo+"._createCancelSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviteeList:s,groupID:n}=Mo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:no,groupID:n,inviter:r,inviteeList:s});return console.log(t+" signalingData:",e),e}_createRejectSignalingData(e){var t=mo+"._createRejectSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:n}=Mo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:io,groupID:n,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createTimeoutSignalingData(e){var t=mo+"._createTimeoutSignalingData",{isInviter:s=!1,inviteID:r}=e,{inviteeList:r,inviter:n}=Mo.getSignaling(r),i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ro,inviter:n,inviteeList:s?r:[i]});return console.log(t+" signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?uo:co,priority:"High",payload:{data:JSON.stringify(e)}};return null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t)}_generateInviteID(){return[So(Co(32),8),So(Co(16),4),So(16384|Co(12),4),So(32768|Co(14),4),So(Co(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Oo=new class{constructor(){this._isProcessingSignaling=!1}init(e){(this._core=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(t){return de(this,void 0,void 0,function*(){var s;try{this._validateBeforeInvite(t);var{signaling:r,signalingData:n,signalingExtensionOptions:e}=yo.createInviteSignaling(t),i=yield this._sendSignaling(r,e);if(0!==(null==i?void 0:i.code))return i;{let{inviteID:e,timeout:t}=n;return Mo.saveSignaling(e,Object.assign(Object.assign({},n),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:fo+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}}catch(e){throw e}})}accept(i){return de(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,yo.createAcceptSignaling(i)),n=yield this._sendSignaling(t,r);return 0===(null==n?void 0:n.code)?(Mo.updateSignaling(s),Object.assign(Object.assign({},n),{inviteID:e})):n}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(n){return de(this,void 0,void 0,function*(){try{var e=n["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,yo.createCancelSignaling(n)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(Mo.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(n){return de(this,void 0,void 0,function*(){try{var e=n["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,yo.createRejectSignaling(n)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(Mo.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return de(this,void 0,void 0,function*(){var r,n,{inviteID:i,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(i);let e=Mo.getSignaling(i),t=e["signaling"],s=le(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var l=yield null==(n=null==(r=this._core)?void 0:r.message.messageAction)?void 0:n.modifyMessage(t);return Mo.hasSignaling(i)&&Mo.saveSignaling(i,Object.assign(Object.assign({},s),{signaling:t})),l}catch(e){if(a){let e=Mo.getSignaling(i)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0!==Io([e]).length)return e={businessID:(e=Eo(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||so,timeout:e.timeout||0},t.debug(mo+" getSignalingInfo "+s(e)),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&Mo.setSignalingListenStatus(!0),null!=(r=this._core)&&r.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&Mo.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=Mo.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();t.has(e)&&(t=t.get(e).inviter===s,this._sendTimeoutNotice({inviteID:e,isInviter:t}))}_sendSignaling(t,s){return de(this,void 0,void 0,function*(){var e;return null==(e=null==(e=null==(e=this._core)?void 0:e.message)?void 0:e.messageSender)?void 0:e.sendMessage(t,s)})}_sendTimeoutNotice(s){return de(this,void 0,void 0,function*(){var n;this._core.ssoLog.debug("_sendTimeoutNotice",mo+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:i,inviteID:o}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=yo.createTimeoutSignaling(s),t=yield this._sendSignaling(a,e);if(0===(null==t?void 0:t.code)){let{data:e,groupID:t,inviteeList:s,inviter:r}=l;null!=(n=this._core)&&n.notificationCenter.emitOuterEvent(null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),i?Mo.removeSignaling(o):Mo.updateSignaling(l)}})}_validateInviteId(e,t){if(!Mo.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:vo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var t=lo,e=e["userID"],s=this._core.common.getCurrentUserID();if(e===s)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${s}, inviteeId:`+e})}_validateBeforeAccept(t){var s=ho;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=Mo.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t=go,s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=Mo.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s=po;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=Mo.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){var t=_o;this._validateInviteId(t,e)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Ao=new class{constructor(){this._actionProcessor=new Map([[so,this._onNewInvitationReceived.bind(this)],[io,this._onInviteeRejected.bind(this)],[oo,this._onInviteeAccepted.bind(this)],[no,this._onInvitationCancelled.bind(this)],[ro,this._onInvitationTimeout.bind(this)]])}init(e){(this._core=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=>{var t,s=Eo(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){Mo.getSignalingListenStatus()&&0!==(e=Io(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){Mo.getSignalingListenStatus()&&0<(e=Io(e.data)).length&&e.forEach(e=>{var t=Eo(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){var r=mo+"._onNewInvitationReceived",{inviteID:n,inviteeList:i,groupID:o}=t,a=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",r+` signalingData:${JSON.stringify(t)}}`),!o||i.includes(a)){let e=t["timeout"];var r=Date.now()/1e3-s.time,o=(0<e&&0<r&&e>r&&(e-=r),Mo.getSignaling(n));o!==t&&(o||Mo.saveSignaling(n,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(a=this._core)&&a.helper.taskScheduler.addOnceTask({id:fo+"-"+n,intervalMs:1e3*e,callback:Oo.handleInvitationExpiryTimer.bind(Oo,n)})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:i})}))}}_onInviteeRejected(e){var t=mo+"._onInviteeRejected",{inviteID:s,inviter:r,groupID:n,inviteeList:i}=e,o=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInviteeRejected",t+` inviteID:${s} hasInviteID:${o} inviter:${r} groupID:`+n),o&&(Mo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInviteeAccepted(e){var t=mo+"._onInviteeAccepted",{inviteID:s,inviter:r,groupID:n,inviteeList:i}=e,o=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInviteeAccepted",t+` inviteID:${s} hasInviteID:${o} inviter:${r} groupID:`+n),o&&(Mo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInvitationCancelled(e){var t=mo+"._onInvitationCancelled",{inviteID:s,inviter:r,groupID:n}=e,i=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInvitationCancelled",t+` inviteID:${s} hasInviteID:${i} inviter:${r} groupID:`+n),i&&(Mo.removeSignaling(s),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t=mo+"._onInvitationTimeout",{inviteID:s,inviteeList:r}=e,n=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInvitationTimeout",t+` inviteID:${s} hasInviteID:${n} data:`+e.data),n&&(Mo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s=mo+"._onInvitationModified",{inviteID:r,data:n}=e,i=Mo.hasSignaling(r);this._core.ssoLog.debug("_onInvitationModified",s+` inviteID:${r} data:`+n),i&&(Mo.saveSignaling(r,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:r,data:n}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},To=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:n}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&Mo.getSignalingListenStatus()){e=Io([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();Ao.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=Eo(e);s&&(t=s["actionType"],t===so?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:n=0}=e,i=this._core.common.getCurrentUserID();r.includes(i)&&(r=Date.now()/1e3-t.time,0<n&&n<r&&0!==n||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let Ro={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}}},Do={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Lo,Po,Xo,bo=new class{constructor(){this.name="Signaling"}install(e){Oo.init(e),Ao.init(e),yo.init(e),Mo.init(e),To.init(e),e.helper.registerValidateConfig({auth:Do,params:Ro})}};let No=new class{init(e){this.core=e}},Go=(!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(Lo=Lo||{}),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(Po=Po||{}),"MSG_REACTION"),wo="MSG_EXT",Uo=0,ko=1,Fo={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",xo="16k_yue",Vo="16k_ja",Bo="16k_zh-PY",jo={[Fo.ZH_CN]:$o,[Fo.EN_US]:qo,[Fo.YUE_HK]:xo,[Fo.JA_JP]:Vo,[Fo.ZH_PY]:Bo},Ko=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Ho={READ:0,UNREAD:1},Wo=1,Yo=2,zo=3,Jo=1,Qo=2,Zo=(!function(e){e.IN="in",e.OUT="out"}(Xo=Xo||{}),16),ei=17,ti=2116,si=2500,ni="C2C",oi="GROUP",ii=20;function ri(d){return de(this,void 0,void 0,function*(){var t,{appStore:s,utils:{isEmpty:r},common:{getCurrentUserID:n},notificationCenter:e,OuterEvent:i}=No.core,{messageList:o,conversationID:a}=d,l=s.conversationStore.getConversationMap();let u=null==(t=l.get(a))?void 0:t.peerReadTime;if(!u){let e=a.replace(ni,""),t=yield function(t){return de(this,void 0,void 0,function*(){var e={To_Account:t};return No.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];u=null==e?void 0:e[0],l.has(a)&&(l.get(a).peerReadTime=u)}}if(l.has(a)){let e=null==(t=l.get(a))?void 0:t.lastMessage;r(e)||e.fromAccount===n()&&e.lastTime<=u&&!e.isPeerRead&&(e.isPeerRead=!0,s.conversationStore.updateConversation(a,{lastMessage:e}))}let c=[];o.forEach(e=>{e.time<=u&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),e.emitOuterEvent(i.MESSAGE_READ_BY_PEER,{name:i.MESSAGE_READ_BY_PEER,data:c})})}function ai(a){return de(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:n}}=No.core,i=r.conversationStore.getConversationMap();if(i.has(a)){let s=null==(e=i.get(a))?void 0:e.userProfile;if(s&&a.startsWith(n.CONV_C2C)){let{avatar:e,nick:t}=s;No.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!1})}}var o=((yield t.userProfile.getMyProfile())||{})["data"];if(o){let{avatar:e,nick:t}=o;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!0})}})}function ci(e){let t,s=No.core["message"],{conversationID:r,messageID:n}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===n))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===n)}function ui(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:n,nick:i,ID:o,clientSequence:a,clientTime:l,messageRandom:u,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:n,From_AccountNick:i,Id:o,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:l,MsgRandom:u,Random:u,MsgSeq:c,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function li(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:n,MsgClientTime:i,ClientSeq:o,To_Account:a,MsgTimeStamp:l,TinyId:u,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:i,time:l,tinyID:u,random:c,sequence:d,to:a,groupID:n,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return No.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var di=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:n}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,n,this._handleReactionSync,this)}addMessageReaction(d,h){return de(this,void 0,void 0,function*(){let{OuterConstant:e,helper:s}=this._core;this._validateMessageReactionBusinessCapability();var{conversationID:r,ID:n,conversationType:t,from:i,to:o,clientSequence:a,random:l,time:u,sequence:c}=d,r=`conversationID:${r} messageID:${n} reactionID:`+h;try{return this._recordMessageReactedByMe(n,h),t===e.CONV_C2C?yield function(o,a){return de(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:n,reactionID:i}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+n,Reaction:i,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:i,to:o,clientSequence:a,random:l,time:u,reactionID:h},this._core):t===e.CONV_GROUP&&(yield function(r,n){return de(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=n.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:o,reactionID:h,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){this._removeMyReactionRecord(n,h);let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"addMessageReaction",code:t,moreMessage:r})}})}removeMessageReaction(d,h){return de(this,void 0,void 0,function*(){var{OuterConstant:e,helper:s}=this._core,{conversationID:r,ID:t,conversationType:n,from:i,to:o,clientSequence:a,random:l,time:u,sequence:c}=(this._validateMessageReactionBusinessCapability(),d),r=`conversationID:${r} messageID:${t} reactionID:`+h;try{return this._removeMyReactionRecord(t,h),n===e.CONV_C2C?yield function(o,a){return de(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:n,reactionID:i}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+n,Reaction:i,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:i,to:o,clientSequence:a,random:l,time:u,reactionID:h},this._core):n===e.CONV_GROUP&&(yield function(r,n){return de(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=n.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},n)})}({to:o,reactionID:h,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:r})}})}getAllUserListOfMessageReaction(l){return de(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=l,s=100<l.count?100:l.count,n=e["conversationID"],{helper:i,constants:o}=this._core;try{var a;if(a=n.startsWith(o.OuterConstant.CONV_C2C)?yield function(l){return de(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=l,{from:e,to:n,clientSequence:i,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:n,MsgKey:i+`_${o}_`+a};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(i){return de(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=i,{sequence:e,to:n}=e,s={Reaction:s,NextSeq:t,GroupId:n,Count:r,MsgSeq:e};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s})){let{Reaction_Account:e,NextSeq:t}=a,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,userList:s}}}}catch(e){let t=(e||{})["errorCode"];throw new i.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(g){return de(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),g),r=t[0];let n=null,i=new Map,{from:o,to:a,conversationType:l}=r,u=this._generateMessageKeyList(t,i),{Results:c=[]}=(l===e.OuterConstant.CONV_C2C?n=yield function(n){return de(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=n,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:o,to:a,messageKeyList:u,maxUserCountPerReaction:s}):l===e.OuterConstant.CONV_GROUP&&(n=yield function(r){return de(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,e={GroupId:e,MsgSeqList:t,Count:s};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:u,maxUserCountPerReaction:s})),n||{}),d=this._extractUserIDsFromReactionResults(c),h=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:i}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:h}),reactedByMyself:1===r}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){let t=[];return null!=e&&e.forEach(e=>{var{ReactionList:e=[]}=e;e.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(s){return de(this,void 0,void 0,function*(){var e;try{var t=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:s});return t?t.data:[]}catch(e){return[]}})}_getUserProfileMap(e){return de(this,void 0,void 0,function*(){let r=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;r.set(s,{nick:e,avatar:t,userID:s})}),r})}_recordMessageReactedByMe(e,t){e=e+"-"+t;this._reactionsMap.has(e)?this._reactionsMap.get(e).reactedByMe=!0:this._reactionsMap.set(e,{reactedByMe:!0})}_removeMyReactionRecord(e,t){e=e+"-"+t;this._reactionsMap.has(e)&&(this._reactionsMap.get(e).reactedByMe=!1)}_recordMessageReactionInfo(e){var{messageID:e,reactionID:t,reactionInfo:s}=e,e=e+"-"+t,t=this._reactionsMap.get(e)||{};this._reactionsMap.set(e,Object.assign(Object.assign({},t),s))}_validateMessageReactionBusinessCapability(){var{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(Go))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){let t=e["MsgReactionNotifyList"],{notificationCenter:d,constants:h}=this._core;t.forEach(c=>de(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:n,MsgRandom:i}=Object.assign(Object.assign({},e),t),o=r+`-${n}-`+i,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),u=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:l}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(o+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:o,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(h.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:h.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:o,reactionList:u}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:n,OperateType:i}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+o,o=r+"-"+n;if(1===i?this._recordMessageReactedByMe(r,n):this._removeMyReactionRecord(r,n),null!=(e=this._reactionsMap.get(o))&&e.reactionID){let e=this._reactionsMap.get(o);e.reactedByMyself=1===i,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,n){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return n.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return n.set(t,e),t})),r}},hi=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:n}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),n.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),n.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return de(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new r.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(r){return de(this,void 0,void 0,function*(){var{common:e,constants:t}=No.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:n,clientTime:i}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:n,MsgClientTime:i}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return de(this,void 0,void 0,function*(){var{common:e,constants:t}=No.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:t})})}(s),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(n){return de(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=n[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(n);if(0<(null==s?void 0:s.length)){let e=yield function(s){return de(this,void 0,void 0,function*(){var{common:e,constants:t}=No.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:t})})}(s),t=(e||{})["GroupMsgReceiptList"];this._updateGroupMessagesReadReceiptInfo({messageList:n,readReceiptList:t})}}return{code:0,data:{messageList:n}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(i){return de(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:o=Ho.READ,cursor:s=""}=i,{conversationID:n,sequence:a,ID:l}=t,u=n.replace(e.OuterConstant.CONV_GROUP,""),c=100<=i.count?100:i.count;try{let i=yield function(i){return de(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:n}=i,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:n};return No.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:u,sequence:a,filter:o,cursor:s,count:c});if(i){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=i,n={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return o===Ho.READ?n.readUserIDList=r.map(e=>e.Read_Account):o===Ho.UNREAD&&(n.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:n}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let n=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:i,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(i)){let r=""+t.OuterConstant.CONV_C2C+a;null!=i&&i.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=ci({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,n.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(n)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:i}}=e,o=""+s.OuterConstant.CONV_GROUP+i;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:n}=e,e=e+`-${t}-`+s,t=ci({conversationID:o,messageID:e}),s={groupID:i,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof n&&(t.readReceiptInfo.unreadCount=n,s.unreadCount=n),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function gi(o,a,l){return de(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=No.core["common"],{from:t,to:s,clientSequence:r,random:n,time:i}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${n}_`+i,OperateType:l,ExtensionList:a}})})}function pi(r,n,i){return de(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=No.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:i,ExtensionList:n}})})}var _i=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:n}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(c,d){return de(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:s,conversationID:r,sequence:n,time:i,conversationType:o}=c,a=d;20<d.length&&(a=d.slice(0,20),t.warn("setMessageExtensions","the length of extensions cannot exceed 20"));var l=this._generateServerExtensions(c,a),u=`convID:${r} messageID:${s} sequence:${n} time:${i} count:`+a.length;try{let r;if(o===e.CONV_C2C?r=yield gi(c,l,Wo):o===e.CONV_GROUP&&(r=yield pi(c,l,Wo)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(c,r);return{code:0,data:{extensions:e},successLog:{message:u+` successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:u})}})}getMessageExtensions(o){return de(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:n}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),i=`convID:${e} messageID:${r} sequence:${t} time:`+n;try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),{code:0,data:{extensions:t},successLog:{message:i}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:i})}})}deleteMessageExtensions(d,h){return de(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t}}=this._core,{conversationType:s,conversationID:r,sequence:n,ID:i,time:o}=d,a=zo,l=[];e(h)||(a=Yo,null==h)||h.forEach(e=>{l.push({key:e,value:"",seq:0})});var u=`convID:${r} messageID:${i} sequence:${n} time:${o} operateType:`+a,c=this._generateServerExtensions(d,l);try{let r;if(s===t.CONV_C2C?r=yield gi(d,c,a):s===t.CONV_GROUP&&(r=yield pi(d,c,a)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return{code:0,data:{extensions:e},successLog:{message:u+`successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:u})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],n=t.ExtensionList||[],i=[],o=0,a=0,l=[];return n.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;i.push({code:e,key:t,value:s}),0===e?o++:a++,l.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<l.length&&this._updateLocalExtensions(e.ID,l),{resultList:i,successCount:o,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);let r=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=r&&r.set(e,{value:s,seq:t})})}_fetchMessageExtensions(l,s){return de(this,void 0,void 0,function*(){let{constants:{OuterConstant:e},utils:{isEmpty:o}}=this._core;try{let i;var{conversationType:t,ID:a}=l;if(t===e.CONV_C2C?i=yield function(e,t){var s=No.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:n,random:i,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:n+`_${i}_`+o,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(i=yield function(e,t){var s=No.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(l,s)),i){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=i,r=(i.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let n=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||n.push({key:t,value:e})})}return n}}catch(e){throw e}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(wo))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:r,TinyId:n,MsgLastSeq:i,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},n=n+`-${o}-`+a;this._extensionsLatestSequenceMap.set(n,i),r===Wo?this._handleMessageExtensionsUpdated({messageID:n,updateMessageExtensionsInfo:e}):r===Yo?this._handleMessageExtensionsDeleted({messageID:n,deleteMessageExtensionsInfo:t}):r===zo&&this._handleMessageExtensionsCleared({messageID:n,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:n=[]}=e,i=[];n.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(i.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:i}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:n=[]}=e,i=[];n.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(i.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:i}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:n,clearMessageExtensionsInfo:i=[]}=e,o=[];i.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(n)&&(this._messageExtensionsMap.get(n)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&o.push(t)}),this._clearLocationExtensions(n,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:n,keyList:o}})}};let mi={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=No.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},vi={setMessageExtensions:[mi,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[mi],deleteMessageExtensions:[mi]},fi=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,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var t="string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(t=null==e?void 0:e.text)?void 0:t.length))||"payload.text is invalid.";return!0!==t?t:!(null!=e&&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=>{var{isString:t,isNumber:s}=No.core["utils"];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||10<e)||"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}}}),vi),{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}]}),Ii=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});class Ei{constructor(e){this._core=e}deleteMessage(s){return de(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:t};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:e})})}revokeMessage(i){return de(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:n}=i;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:n,MsgTimeStamp:r}}})})}}class Si{constructor(e){this._core=e}deleteMessage(s){return de(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={GroupId:e,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:t};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:e})})}revokeMessage(s){return de(this,void 0,void 0,function*(){var{to:e,sequence:t}=s;return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:{GroupId:e,MsgSeqList:[{MsgSeq:t}]}})})}}class Ci{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:n,revokeReason:i,revoker:o}=e;let a={};var l=this._core.message["messageDataHandler"];return(a=l.revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}))||(a={conversationID:e,sequence:t},r&&n&&s&&(a.ID=r+`-${n}-`+s)),a.revoker=o,a.revokeReason=i,a.revokerInfo={userID:o,nick:"",avatar:""},a}updateRevokerInfo(t){return de(this,void 0,void 0,function*(){var e=t.map(e=>e.revoker);try{let s=yield this._fetchUserInfos(e);s&&t.forEach(e=>{var t=e["revoker"];s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(t){return de(this,void 0,void 0,function*(){var e=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t});return null!=e&&e.data?null==(e=e.data)?void 0:e.reduce((e,{userID:t,nick:s,avatar:r})=>(e[t]={nick:s||"",avatar:r||""},e),{}):null})}}var Mi=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Si(e),this._c2cMessageAction=new Ei(e),this._messageHelper=new Ci(e);e=e.helper;e.registerApi({apiName:"deleteMessage",context:this}),e.registerApi({apiName:"revokeMessage",context:this}),e.registerApi({apiName:"resendMessage",context:this}),e.registerApi({apiName:"findMessage",context:this})}deleteMessage(t){return de(this,void 0,void 0,function*(){let l=[],u=[],{conversationID:c,conversationType:d}=t[0],e=c.replace(d,"");if("@TIM#SYSTEM"===d)throw new this._core.helper.ChatError({code:ti});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:n,sequence:i,random:o,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!n){let e="C2C"===s?i+`_${o}_`+a:String(i);l.push(e)}u.push(e)}}),0===l.length)return this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}};30<l.length&&(l=l.slice(0,30),u=u.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:l}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:l}),this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(u){return de(this,void 0,void 0,function*(){var s;let{conversationType:e,isRevoked:t,ID:r,type:n,from:i,to:o}=u;var a,l=`type:${n} from:${i} to:${o} ID:`+r;if("@TIM#SYSTEM"===e)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(t)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:l});try{if(a="C2C"===e?yield this._c2cMessageAction.revokeMessage(u):yield this._groupMessageAction.revokeMessage(u)){let e=a["RecallRetList"],t=(null==(s=null==e?void 0:e[0])?void 0:s.RetCode)||0;if(0!==t)throw new this._core.helper.ChatError({code:t,moreMessage:l});return u.isRevoked=!0,yield this._handleRevokeMessageSuccess(u),{code:0,data:{message:u},successLog:{message:l}}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:l})}})}resendMessage(t,s){return de(this,void 0,void 0,function*(){var e;return t.isResend=!0,t.status="unSend",null==(e=null==(e=this._core)?void 0:e.apiMap)?void 0:e.sendMessage(t,s)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(n){if(0!==n.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;n.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:n=""}=n[0];e(n)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,n):t.emitInnerEvent(r.MESSAGE_DELETED,n)}}_handleRevokeMessageSuccess(n){return de(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:r}=n;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([n])})}};class yi{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new yi({index:e,data:t})}constructor(e){this.type=Lo.MSG_FACE;var{index:e,data:t}=e;this.content={index:e,data:t}}validateBeforeSend(){var e;return"number"==typeof(null==(e=this.content)?void 0:e.index)&&"string"==typeof(null==(e=this.content)?void 0:e.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{index:e,data:t}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Index:e,Data:t}}}}class Oi{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new Oi({description:e,longitude:t,latitude:s})}constructor(e){this.type=Lo.MSG_LOCATION;var{description:e,longitude:t,latitude:s}=e;this.content={description:e,longitude:t,latitude:s}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{description:e,longitude:t,latitude:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Desc:e,Longitude:t,Latitude:s}}}}var Ai=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(Lo.MSG_FACE,yi),e.message.messageFactory.registerElementClass(Lo.MSG_LOCATION,Oi),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){var t,s;return e?({index:t,data:s}=(null==e?void 0:e.payload)||{},t=new yi({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],n=this._core.apiMap.createTextMessage(e),i=this._core["OuterConstant"];if(!n)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==i.MSG_AT_ALL?(t.push({GroupAtAllFlag:Uo,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:ko}),s.push(i.MSG_AT_ALL))}),n._groupAtInfoList=t,n.atUserList=s}return n}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:n,payload:i,needReadReceipt:o,receiverList:a,cloudCustomData:l="",isSupportExtension:u=!1}=e;if(!Array.isArray(i._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(i.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:n,payload:i,needReadReceipt:o,isSupportExtension:u,cloudCustomData:l,receiverList:a});return t.setRelayFlag(!0),t.setElement(i._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new Oi({description:t,longitude:s,latitude:r}),s=this._core.common.getCurrentUserID(),(r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),r):null}};let Ti=class{init(e){this._messageHelper=new Ci(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return de(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return de(this,void 0,void 0,function*(){let a=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:l}}=this._core;s.forEach(e=>{var{MsgRand:t,MsgSeq:s,To_Account:r,From_Account:n,RevokerInfo:{Revoker_Account:i,Revoke_Reason:o}}=e,r=l()===n?"C2C"+r:"C2C"+n,e=(null==(n=null==e?void 0:e.RevokerInfo)?void 0:n.Reason)||o,n=this._messageHelper.generateRevokeMessage({conversationID:r,sequence:s,random:t,revoker:i,revokeReason:e});a.push(n)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return de(this,void 0,void 0,function*(){var e=t.result["revokedMessageList"];yield this._parseAndEmitC2CRevokedMessages(e)})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},Ri=class{init(e){this._messageHelper=new Ci(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){e=e.GroupTips;null!=e&&e.forEach(e=>{var t;Array.isArray(null==(t=null==e?void 0:e.MsgBody)?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(i){return de(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:u}=i,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:n}}=this._core,h=!1;u&&(h=n({groupID:u.GroupId})||!r(u.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:n,TopicId:i,RevokerInfo:{Revoker_Account:o=(null==l?void 0:l.Revoker_Account)||"",Reason:a=(null==l?void 0:l.Reason)||""}}=e,i=this._messageHelper.generateRevokeMessage({conversationID:i?"GROUP"+i:"GROUP"+s,sequence:t,random:e,tinyID:n,clientTime:r,revoker:o,revokeReason:a});(h?(i.revokerInfo.nick=u.From_AccountNick,i.revokerInfo.avatar=u.From_AccountHeadurl,c):d).push(i)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),c.push(...d)),0!==c.length&&t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:c})}catch(e){console.debug(e)}})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var Di=new class{constructor(){this._c2cMessageReceiver=new Ti,this._groupMessageReceiver=new Ri}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class bi{constructor(e){var t=(this._core=e)["constants"];this._messageHelper=new Ci(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return de(this,void 0,void 0,function*(){var e;try{var t=yield function(i){return de(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=No.core,n=e.groupStore.getGroupMap(),t={NotifyReqList:i.map(e=>{var t=n.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*No.core.common.timeManager.getServerTimeMs()}})||[]};return r.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:t})})}(s);if(t){let s=[];null!=(e=null==t?void 0:t.NotifyRspList)&&e.forEach(e=>{var{GroupId:e,NotifyMsgList:t}=e,e=this._parseServerRevokeMessageList({groupID:e,serverRevokeMessageList:t});s.push(...e)}),0!==s.length&&(yield this._emitMessageRevokedEvent(s))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){let{serverRevokeMessageList:t,groupID:o}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:n=""}}=e,i="GROUP"+o,i=this._messageHelper.generateRevokeMessage({conversationID:i,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:n});a.push(i)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return de(this,void 0,void 0,function*(){var{notificationCenter:e,OuterEvent:t}=this._core;yield this._messageHelper.updateRevokerInfo(s),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:s})})}}class Ni{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new Ci(e)}getRoamingMessagesByAnchor(p){return de(this,void 0,void 0,function*(){var n;try{var{conversationID:i,count:e,messageID:r,time:o,direction:a}=p;let t=o,s="";if(!o){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(i)){let e=this._historyMessageListFetchAnchors.get(i);t=e.lastMessageTime,s=e.messageKey}}var l=i.replace(ni,""),u=yield function(i){return de(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:n}=i,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:n};return No.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:l,direction:a});if(u){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=u;this._historyMessageListFetchAnchors.set(i,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],h=this._parseMessage(d);c.push(h)}var g=this._core.message.messageHelper.filterValidMessages(c);return{messageList:g,nextReqMessageIDFromServer:null==(n=g[0])?void 0:n.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){var t=ni,e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}}var Li=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new bi(e),this._c2cMessageHistory=new Ni(e),this._messageHelper=new Ci(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 de(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e,r=ii;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var n=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:n,targetCount:r})){let e=null;if(t.startsWith(oi)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:r,direction:Po.FORWARD}):t.startsWith(ni)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:r,direction:Po.FORWARD})),e){var{nextReqMessageIDFromServer:i,hasNoMoreHistoryMessage:o,messageList:a}=e,l=this._core.message.messageDataHandler.prependLocalMessageList({messageList:a,conversationID:t}),u=t,{appStore:c,message:d,OuterConstant:h}=No.core,c=c.conversationStore.getConversation(u),g=d.messageDataHandler.getLocalMessageList(u);if(c&&0!==g.length&&u!==h.CONV_SYSTEM){var p=[];for(let e=0;e<g.length;e++)"in"!==g[e].flow?"out"!==g[e].flow||g[e].isRead||g[e].setIsRead(!0):p.push(g[e]);let t=0;if(c.type===h.CONV_C2C){let e=p.slice(-c.unreadCount).filter(e=>e.isRevoked).length;t=p.length-c.unreadCount-e}else t=p.length-c.unreadCount;for(let e=0;e<t&&!p[e].isRead;e++)p[e].setIsRead(!0)}yield ai(t),t.startsWith(ni)&&(yield ri({messageList:a,conversationID:t}));var _=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,l.length+n),m=_.filter(e=>e.isRevoked),v=(yield this._messageHelper.updateRevokerInfo(m),o&&this._fetchedCompleteConversations.add(t),{nextReqMessageID:o?"":String(i),messageList:_,isCompleted:o}),f=_.map(e=>e.sequence);return{code:0,data:v,successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${n} sequenceList: `+JSON.stringify(f)}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:r}),successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${n}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(r){return de(this,void 0,void 0,function*(){var i,o;let{conversationID:e,sequence:a,time:t,direction:l=Po.FORWARD}=r,u=this._core.helper["isEmpty"];if(![Po.BACKWARD,Po.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=ii}=r,c=(s=s>ii?ii:s,null);if(e.startsWith(oi)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:n}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),l===Po.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==Po.BACKWARD)return{code:0,data:c};{if(u(r)&&u(n))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(i=null==r?void 0:r[r.length-1])?void 0:i.sequence)||0,t=(null==(o=null==n?void 0:n[n.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:r.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(ni)&&(c=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:e,count:s+1,time:t,direction:l}))){let{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=c;return s||(l===Po.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(d){return de(this,void 0,void 0,function*(){let t,{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:n,CONV_GROUP:i},message:o,apiMap:a}=this._core,l=e.conversationStore.getConversation(d);if(!l)throw new s({code:si});var u={fromAccount:r()},c=l["type"];c===n?(u.type=Jo,u.toAccount=d.replace(n,"")):c===i&&(u.type=Qo,u.toGroupID=d.replace(i,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:d});let e=yield function(n){return de(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=n,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return No.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(u);return e&&(o.messageDataHandler.deleteConversationMessageList(d),this._clearedConversations.add(d),this._fetchedCompleteConversations.delete(d),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(d),this._updateConversationLastMessage(d)),{code:0,data:{conversationID:d},successLog:{message:"convID:"+d}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:e,moreMessage:"convID:"+d})}})}_updateConversationLastMessage(e){var t=this._core["appStore"];t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e),r=s["length"];if(!t)return r;let n=-1;return null!=e&&e.startsWith(ni)?n=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(oi)&&(n=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===n?0:n}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return de(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),n=r.length;let i=n,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=n;return s?(l=r.findIndex(e=>t.startsWith(ni)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,i=l):a=e<n?n-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=r.slice(a,l),o.isCompleted=i<=e,t.startsWith(ni)&&(yield ai(t),yield ri({messageList:o.messageList,conversationID:t})),o})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){var 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}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}},Pi=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(n){return de(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=n,r=yield function(i,o){return de(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=i,{store:r,common:n}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=r.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=r.get("instance"))?void 0:e.sdkAppId},s=yield n.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},Gi=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return de(this,void 0,void 0,function*(){let{message:e,language:t=Fo.ZH_PY}=s,r=(e.payload||{})["url"];var n=this._core.common.getCurrentUserID(),n=(e.from===n&&"out"===e.flow&&(r=e.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(i=Ko.exec(r))?void 0:i[1])||"mp3"),i=jo[t]||Bo;try{let s=yield function(e){var{store:t,common:s}=No.core,{url:e,format:r,serverLanguageType:n}=e,n={BytesUrl:e,BytesEngServiceType:n,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:n})}({url:r,format:n,serverLanguageType:i});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!Ko.test(e))throw new this._core.common.ChatError({code:2119})}};class wi{constructor(e){var{constants:t,common:s,utils:r}=No.core,{CONV_C2C:t,CONV_GROUP:n}=t.OuterConstant,{ID:e,tinyID:i,from:o,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:l,sequence:u,cloudCustomData:c="",nick:d="",avatar:h="",clientSequence:g,conversationType:p,groupID:_,_elements:m,time:v}=e,i=(this.ID=e||i+`-${s}-`+l,this.messageRandom=l,this.from=o,this.messageSender=o,this.time=v,this.messageSequence=u,this.clientSequence=g||u,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=h,this.nick=d,r.deepCopyWithMethods(m));i.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=i,e?p.startsWith(t)?this.receiverUserID=a:p.startsWith(n)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ui{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:n,JsonMsgKey:i}=e||{},e=e.map(e=>li(e));return new Ui({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:n,downloadKey:i})}constructor(e){this.type=No.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:n,pbDownloadKey:i="",downloadKey:o="",version:a=0,layersOverLimit:l=!1}=e,u=[];t.forEach(e=>{e&&(e=new wi(e),u.push(e))}),this.content={messageList:u,title:s,abstractList:r,compatibleText:n,version:a,downloadKey:o,pbDownloadKey:i,layersOverLimit:l}}validateBeforeSend(){var e=No.core.helper["isEmpty"];return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{abstractList:e,compatibleText:t,downloadKey:s,layersOverLimit:r,pbDownloadKey:n,title:i,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:n,Title:i,Version:o,MsgList:ui(a)}}}}var ki=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Ui),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===r.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){var t,s=this._core["common"];return e?(t=new Ui(e.payload),s=s.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setRelayFlag(!0),e.setElement(t),e):null}sendMessage(a,l){return de(this,void 0,void 0,function*(){var e,t,s;try{var i=function(t){let e="utf-8";No.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,n;if(n=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<n;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<n;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,n=null;if(11264<i){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return de(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:ui(e)};return No.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];n=new Ui(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(n)}catch(e){console.error(e)}}var{message:o}=(yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,l))["data"];return n&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(o){return de(this,void 0,void 0,function*(){let r=this._core["ssoLog"],e=o.payload,{downloadKey:n,pbDownload:t,type:s}=e,i=le(e,["downloadKey","pbDownload","type","messageList"]);try{let e=yield function(e){return de(this,void 0,void 0,function*(){return No.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(n),t=(e||{})["MsgList"],s=null==t?void 0:t.map(e=>{e=li(e);return new wi(e)});return"function"==typeof o.isOnlineMessage?o.setElement({type:o.type,content:Object.assign({messageList:s},i)}):(o.payload.messageList=s,o.payload.downloadKey="",o.payload.pbDownloadKey=""),r.info("downloadMergerMessage"," success downloadKey:"+n),o}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:n})}})}},Fi=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return de(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:r}}=this._core,{GroupId:n,To_Account:i}=a,o=(a.From_Account=a.From_Account||s(),null);if(n){o=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:n}));let e=t.userStore.getUserProfile(s());o.level=(null==e?void 0:e.level)||0,r(i)&&0<i.length&&(o._receiverList=i)}else i&&(o=this._generateC2CMessage(a));return e.messageSender.sendMessage(o,a)})}_generateC2CMessage(e){var{message:t,OuterConstant:{CONV_C2C:s}}=this._core,e=t.messageHelper.parseServerPushMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Xo.OUT})),s=e["elements"];return t.setElement(s),t}_generateGroupMessage(e){var{message:t,OuterConstant:{CONV_GROUP:s}}=this._core,e=t.messageHelper.parseServerGroupMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Xo.OUT})),s=e["elements"];return t.setElement(s),t}},$i=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_PINNED:r}}=this._core=e;t.subscribeInnerEvent(s,r,this._handleGroupMessagePinned,this),e.registerApi({apiName:"pinGroupMessage",context:this}),e.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(o){return de(this,void 0,void 0,function*(){let{ssoLog:e,common:{isTopic:t},OuterConstant:{},helper:{ChatError:r}}=this._core;var{groupID:s,message:n,isPinned:i}=o,n=n["sequence"];try{return yield function(o){return de(this,void 0,void 0,function*(){var{buildAndSendPacket:e,getCurrentUserID:t}=No.core["common"],{groupID:s,sequence:r,isPinned:n}=o,t=t(),i=n?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",s={GroupId:s,MsgSeq:r};return n?s.Pinner_Account=t:s.UnPinner_Account=t,e({servcmd:i,data:s})})}({groupID:s,sequence:n,isPinned:i}),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};throw new r({code:t,message:s})}})}getPinnedGroupMessageList(r){return de(this,void 0,void 0,function*(){let e=[];try{var t,s=yield function(s){return de(this,void 0,void 0,function*(){var e=s["groupID"],{buildAndSendPacket:t}=No.core["common"];return t({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:e}})})}({groupID:r});return s&&({PinnedMsgList:t=[]}=s,e=yield this._updatePinnedMessageInfo({serverPinnedMessageList:t,groupID:r})),{code:0,data:{messageList:e}}}catch(e){throw e}})}_handleGroupMessagePinned(e){let{message:{messageHelper:u,messageFactory:c},notificationCenter:d,OuterEvent:h,OuterConstant:g}=this._core;e.GroupTips.forEach(e=>{var{ToGroupId:e,MsgBody:{PinnedMsg:t,OpType:s,MsgOperatorMemberExtraInfo:r,SdkGroupMessageId:i}}=e,{UserId:r,NickName:n="",ImageUrl:o=""}=r;let a=null,l=!1;if(s===Zo){l=!0;let e=u.parseServerGroupMessage(t);(a=c.createMessage(Object.assign(Object.assign({},e),{conversationType:g.CONV_GROUP,flow:"in"}))).setElement(e.elements),a.pinnerInfo={userID:r,nick:n,avatar:o}}else if(s===ei){let{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:r,MsgSeq:n}=i;a={ID:`${s}-${e}-`+t,sequence:n,random:t,time:r,clientTime:e}}a&&d.emitOuterEvent(h.PINNED_GROUP_MESSAGE_UPDATED,{name:h.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:e,message:a,isPinned:l,operatorInfo:{userID:r,nick:n,avatar:o}}})})}_findMessageBySequence(e,t){var{messageDataHandler:s}=this._core["message"];return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return de(this,arguments,void 0,function*({serverPinnedMessageList:i,groupID:e}){let{OuterConstant:{CONV_GROUP:t},utils:{isEmpty:s}}=this._core,o=[],a=[],l=[],u=new Map,c=""+t+e;for(let n=0;n<i.length;n++){let e=i[n],{Pinner_Account:t,MsgSeq:s}=e,r=this._findMessageBySequence(c,s);a.push(t),u.set(s,t),r?o.push(r):l.push(s)}let r=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:l,pinnerIDList:a});if(r){let{pinnerInfoMap:s,messageList:e}=r;return o.push(...e),o.forEach(e=>{var t=e["sequence"],t=u.get(t),t=s[t]||{userID:t,nick:"",avatar:""};e.pinnerInfo=t}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(i){return de(this,void 0,void 0,function*(){var{message:{},user:{userProfile:e},utils:{isArray:t}}=this._core,{conversationID:s,messageSequenceList:n,pinnerIDList:r}=i,s=yield Promise.all([this._fetchMessageBySequence({conversationID:s,messageSequenceList:n}),null==e?void 0:e.getUserProfile({userIDList:r})]);if(t(s)){let r={};return((null==(n=s[1])?void 0:n.data)||[]).forEach(e=>{var{userID:e,nick:t="",avatar:s=""}=e;r[e]={userID:e,nick:t,avatar:s}}),{messageList:(null==(e=s[0])?void 0:e.messageList)||[],pinnerInfoMap:r}}})}_fetchMessageBySequence(n){return de(this,void 0,void 0,function*(){var{utils:{isEmpty:e},message:{messageHistory:t}}=this._core,{conversationID:s,messageSequenceList:r}=n;return e(r)?[]:t.getGroupRoamingMessagesByAnchor({conversationID:s,messageSequenceList:r,getType:3})})}},qi=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,No.init(e),Mi.init(e),Ai.init(e),Di.init(e),Li.init(e),di.init(e),Pi.init(e),Gi.init(e),hi.init(e),ki.init(e),_i.init(e),Fi.init(e),$i.init(e),e.helper.registerValidateConfig({auth:Ii,params:fi}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),Di.dispose(),Li.dispose(),hi.dispose(),_i.dispose()}_reset(){Li.reset()}},xi=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(p,_){return de(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:n,qs:i,headers:o={},resources:a,dataType:l="text",uploadByIP:u,uploadIP:c}=p,d=n;if(i){let e=this._queryString(i);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(r.toUpperCase(),d,!0),h.responseType=l;var g=Object.assign({},o);if(u&&c&&(g.host=c),!t(g))for(let e in g)g.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&h.setRequestHeader(e,g[e]);return h.onload=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e);if(200===h.status)_(null,e);else{if(c&&!d.includes(c))return p.url=this._domainName2IP(d,c),p.uploadByIP=!0,this.request(p,_);_({code:h.status,message:JSON.stringify(h.responseText)},e)}},h.onerror=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e),t={code:h.status,message:0===h.status?"CORS blocked or network error":JSON.stringify(h.responseText)};_(t,e)},p.onProgress&&h.upload&&(h.upload.onprogress=e=>{var{total:e,loaded:t}=e,s=Math.min(Math.floor(100*t/e),100);p.onProgress({total:e,loaded:t,percent:s/100})}),h.send(a),h})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{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(s,r="&",n="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+n;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let Vi=["unknown","image","video","audio","log"];var ar,Bi=new class{init(e){this._core=e}request(s,r){let{MINI_APP_NAMESPACE:e,IN_ALIPAY_MINI_APP:n,isUniIOSApp:i}=null==(h=this._core)?void 0:h.utils,{resources:o="",headers:a={},url:l,downloadUrl:u=""}=s,c=l,d=null;var h=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(h){var h=decodeURIComponent(h[3]),h=h.includes("?")?h.split("?")[0]:h||"",h={key:s.fileKey||h,success_action_status:200,"Content-Type":""},g={};if(i()){let[e,t]=l.split("?sign=");t&&(c=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:c,header:a,name:"file",filePath:o,formData:Object.assign(Object.assign({},h),g),timeout:s.timeout||3e5};if(n){let{}=t,e=le(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?Vi[s.fileType]:"image"})}return(d=e.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})}}))).onProgressUpdate&&d.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),d}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var n=+t.statusCode;200==n?s(null,{statusCode:n,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:n,message:JSON.stringify(t.data)},{statusCode:n,headers:r,data:void 0})}};function ji(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Ki(e){e=e||99999999;return Math.round(Math.random()*e)}function Hi(e,t=!0,s=!0){var r=Date.now();return t?s?r-e+" ms":Math.round((r-e)/1e3)+" s":s?r-e:Math.round((r-e)/1e3)}function Wi(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Yi(e,t){return Math.round(Number(e)*10**t)/10**t}function zi(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function Ji(e){return e<=1048576?Yi(e/1024,1)+"KB/s":Yi(e/1048576,1)+"MB/s"}let Qi="TIMImageElem",Xi="TIMSoundElem",Zi="TIMFileElem",er="TIMVideoFileElem",tr="RichMediaMessagePlugin",sr=["rich.my-imcloud.com","imrich.qcloud.com"],nr=1,or=2,ir=3,rr=255,cr=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(ar=ar||{}),{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\/)/});var ur,lr=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(s){{var[s,r]=s.split("?");if(!r)return s;let t=r.split("&").reduce((e,t)=>{var[t,s]=t.split("=");return t&&"authKey"!==t&&(e[t]=s||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?s+"?"+e:s}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(cr).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return ji(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(s){return de(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(s):e?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=sr;var s=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==s)try{JSON.parse(s).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=sr}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),n=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,n));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,s=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;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{IN_RN_APP:e,IS_IE:t,IE_VERSION:s,IN_WX_MINI_GAME:r}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===s||r}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,s=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),s()},t.onerror=()=>{e({width:0,height:0}),s()},t.src=r})}},dr={exports:{}},hr=(ur||(ur=1,dr.exports=function(){var r=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function l(e,t){var s=e[0],r=e[1],n=e[2],i=e[3],r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&n|~r&i)+t[0]-680876936|0)<<7|s>>>25)+r|0)&r|~s&n)+t[1]-389564586|0)<<12|i>>>20)+s|0)&s|~i&r)+t[2]+606105819|0)<<17|n>>>15)+i|0)&i|~n&s)+t[3]-1044525330|0)<<22|r>>>10)+n|0;r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&n|~r&i)+t[4]-176418897|0)<<7|s>>>25)+r|0)&r|~s&n)+t[5]+1200080426|0)<<12|i>>>20)+s|0)&s|~i&r)+t[6]-1473231341|0)<<17|n>>>15)+i|0)&i|~n&s)+t[7]-45705983|0)<<22|r>>>10)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&n|~r&i)+t[8]+1770035416|0)<<7|s>>>25)+r|0)&r|~s&n)+t[9]-1958414417|0)<<12|i>>>20)+s|0)&s|~i&r)+t[10]-42063|0)<<17|n>>>15)+i|0)&i|~n&s)+t[11]-1990404162|0)<<22|r>>>10)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&n|~r&i)+t[12]+1804603682|0)<<7|s>>>25)+r|0)&r|~s&n)+t[13]-40341101|0)<<12|i>>>20)+s|0)&s|~i&r)+t[14]-1502002290|0)<<17|n>>>15)+i|0)&i|~n&s)+t[15]+1236535329|0)<<22|r>>>10)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&i|n&~i)+t[1]-165796510|0)<<5|s>>>27)+r|0)&n|r&~n)+t[6]-1069501632|0)<<9|i>>>23)+s|0)&r|s&~r)+t[11]+643717713|0)<<14|n>>>18)+i|0)&s|i&~s)+t[0]-373897302|0)<<20|r>>>12)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&i|n&~i)+t[5]-701558691|0)<<5|s>>>27)+r|0)&n|r&~n)+t[10]+38016083|0)<<9|i>>>23)+s|0)&r|s&~r)+t[15]-660478335|0)<<14|n>>>18)+i|0)&s|i&~s)+t[4]-405537848|0)<<20|r>>>12)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&i|n&~i)+t[9]+568446438|0)<<5|s>>>27)+r|0)&n|r&~n)+t[14]-1019803690|0)<<9|i>>>23)+s|0)&r|s&~r)+t[3]-187363961|0)<<14|n>>>18)+i|0)&s|i&~s)+t[8]+1163531501|0)<<20|r>>>12)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r&i|n&~i)+t[13]-1444681467|0)<<5|s>>>27)+r|0)&n|r&~n)+t[2]-51403784|0)<<9|i>>>23)+s|0)&r|s&~r)+t[7]+1735328473|0)<<14|n>>>18)+i|0)&s|i&~s)+t[12]-1926607734|0)<<20|r>>>12)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r^n^i)+t[5]-378558|0)<<4|s>>>28)+r|0)^r^n)+t[8]-2022574463|0)<<11|i>>>21)+s|0)^s^r)+t[11]+1839030562|0)<<16|n>>>16)+i|0)^i^s)+t[14]-35309556|0)<<23|r>>>9)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r^n^i)+t[1]-1530992060|0)<<4|s>>>28)+r|0)^r^n)+t[4]+1272893353|0)<<11|i>>>21)+s|0)^s^r)+t[7]-155497632|0)<<16|n>>>16)+i|0)^i^s)+t[10]-1094730640|0)<<23|r>>>9)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r^n^i)+t[13]+681279174|0)<<4|s>>>28)+r|0)^r^n)+t[0]-358537222|0)<<11|i>>>21)+s|0)^s^r)+t[3]-722521979|0)<<16|n>>>16)+i|0)^i^s)+t[6]+76029189|0)<<23|r>>>9)+n|0,r=((r+=((n=((n+=((i=((i+=((s=((s+=(r^n^i)+t[9]-640364487|0)<<4|s>>>28)+r|0)^r^n)+t[12]-421815835|0)<<11|i>>>21)+s|0)^s^r)+t[15]+530742520|0)<<16|n>>>16)+i|0)^i^s)+t[2]-995338651|0)<<23|r>>>9)+n|0,r=((r+=((i=((i+=(r^((s=((s+=(n^(r|~i))+t[0]-198630844|0)<<6|s>>>26)+r|0)|~n))+t[7]+1126891415|0)<<10|i>>>22)+s|0)^((n=((n+=(s^(i|~r))+t[14]-1416354905|0)<<15|n>>>17)+i|0)|~s))+t[5]-57434055|0)<<21|r>>>11)+n|0,r=((r+=((i=((i+=(r^((s=((s+=(n^(r|~i))+t[12]+1700485571|0)<<6|s>>>26)+r|0)|~n))+t[3]-1894986606|0)<<10|i>>>22)+s|0)^((n=((n+=(s^(i|~r))+t[10]-1051523|0)<<15|n>>>17)+i|0)|~s))+t[1]-2054922799|0)<<21|r>>>11)+n|0,r=((r+=((i=((i+=(r^((s=((s+=(n^(r|~i))+t[8]+1873313359|0)<<6|s>>>26)+r|0)|~n))+t[15]-30611744|0)<<10|i>>>22)+s|0)^((n=((n+=(s^(i|~r))+t[6]-1560198380|0)<<15|n>>>17)+i|0)|~s))+t[13]+1309151649|0)<<21|r>>>11)+n|0,r=((r+=((i=((i+=(r^((s=((s+=(n^(r|~i))+t[4]-145523070|0)<<6|s>>>26)+r|0)|~n))+t[11]-1120210379|0)<<10|i>>>22)+s|0)^((n=((n+=(s^(i|~r))+t[2]+718787259|0)<<15|n>>>17)+i|0)|~s))+t[9]-343485551|0)<<21|r>>>11)+n|0,e[0]=s+e[0]|0,e[1]=r+e[1]|0,e[2]=n+e[2]|0,e[3]=i+e[3]|0}function u(e){for(var t=[],s=0;s<64;s+=4)t[s>>2]=e.charCodeAt(s)+(e.charCodeAt(s+1)<<8)+(e.charCodeAt(s+2)<<16)+(e.charCodeAt(s+3)<<24);return t}function c(e){for(var t=[],s=0;s<64;s+=4)t[s>>2]=e[s]+(e[s+1]<<8)+(e[s+2]<<16)+(e[s+3]<<24);return t}function s(e){for(var t,s,r,n,i=e.length,o=[1732584193,-271733879,-1732584194,271733878],a=64;a<=i;a+=64)l(o,u(e.substring(a-64,a)));for(t=(e=e.substring(a-64)).length,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0;a<t;a+=1)s[a>>2]|=e.charCodeAt(a)<<(a%4<<3);if(s[a>>2]|=128<<(a%4<<3),55<a)for(l(o,s),a=0;a<16;a+=1)s[a]=0;return n=(n=8*i).toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),n=parseInt(n[1],16)||0,s[14]=r,s[15]=n,l(o,s),o}function o(e){for(var t=0;t<e.length;t+=1)e[t]=function(e){for(var t="",s=0;s<4;s+=1)t+=r[e>>8*s+4&15]+r[e>>8*s&15];return t}(e[t]);return e.join("")}function n(e){return e=/[\u0080-\uFFFF]/.test(e)?unescape(encodeURIComponent(e)):e}function a(e){for(var t=[],s=e.length,r=0;r<s-1;r+=2)t.push(parseInt(e.substr(r,2),16));return String.fromCharCode.apply(String,t)}function i(){this.reset()}return o(s("hello")),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||(ArrayBuffer.prototype.slice=function(e,t){var s=this.byteLength,e=d(e,s),r=s;return(r=void 0!==t?d(t,s):r)<e?new ArrayBuffer(0):(t=r-e,s=new ArrayBuffer(t),r=new Uint8Array(s),e=new Uint8Array(this,e,t),r.set(e),s)}),i.prototype.append=function(e){return this.appendBinary(n(e)),this},i.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;for(var t=this._buff.length,s=64;s<=t;s+=64)l(this._hash,u(this._buff.substring(s-64,s)));return this._buff=this._buff.substring(s-64),this},i.prototype.end=function(e){for(var t,s=this._buff,r=s.length,n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i=0;i<r;i+=1)n[i>>2]|=s.charCodeAt(i)<<(i%4<<3);return this._finish(n,r),t=o(this._hash),e&&(t=a(t)),this.reset(),t},i.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},i.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},i.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},i.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},i.prototype._finish=function(e,t){var s,r=t;if(e[r>>2]|=128<<(r%4<<3),55<r)for(l(this._hash,e),r=0;r<16;r+=1)e[r]=0;t=(t=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(t[2],16),t=parseInt(t[1],16)||0,e[14]=s,e[15]=t,l(this._hash,e)},i.hash=function(e,t){return i.hashBinary(n(e),t)},i.hashBinary=function(e,t){e=o(s(e));return t?a(e):e},(i.ArrayBuffer=function(){this.reset()}).prototype.append=function(e){s=this._buff.buffer,r=e,(n=new Uint8Array(s.byteLength+r.byteLength)).set(new Uint8Array(s)),n.set(new Uint8Array(r),s.byteLength);var t,s,r,n,i=n,o=i.length;for(this._length+=e.byteLength,t=64;t<=o;t+=64)l(this._hash,c(i.subarray(t-64,t)));return this._buff=t-64<o?new Uint8Array(i.buffer.slice(t-64)):new Uint8Array(0),this},i.ArrayBuffer.prototype.end=function(e){for(var t,s=this._buff,r=s.length,n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i=0;i<r;i+=1)n[i>>2]|=s[i]<<(i%4<<3);return this._finish(n,r),t=o(this._hash),e&&(t=a(t)),this.reset(),t},i.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},i.ArrayBuffer.prototype.getState=function(){var e,t=i.prototype.getState.call(this);return t.buff=(e=t.buff,String.fromCharCode.apply(null,new Uint8Array(e))),t},i.ArrayBuffer.prototype.setState=function(e){return e.buff=function(e,t){for(var s=e.length,r=new ArrayBuffer(s),n=new Uint8Array(r),i=0;i<s;i+=1)n[i]=e.charCodeAt(i);return t?n:r}(e.buff,!0),i.prototype.setState.call(this,e)},i.ArrayBuffer.prototype.destroy=i.prototype.destroy,i.ArrayBuffer.prototype._finish=i.prototype._finish,i.ArrayBuffer.hash=function(e,t){e=o(function(e){for(var t,s,r,n,i=e.length,o=[1732584193,-271733879,-1732584194,271733878],a=64;a<=i;a+=64)l(o,c(e.subarray(a-64,a)));for(t=(e=a-64<i?e.subarray(a-64):new Uint8Array(0)).length,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0;a<t;a+=1)s[a>>2]|=e[a]<<(a%4<<3);if(s[a>>2]|=128<<(a%4<<3),55<a)for(l(o,s),a=0;a<16;a+=1)s[a]=0;return n=(n=8*i).toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),n=parseInt(n[1],16)||0,s[14]=r,s[15]=n,l(o,s),o}(new Uint8Array(e)));return t?a(e):e},i;function d(e,t){return(e=0|e||0)<0?Math.max(e+t,0):Math.min(e,t)}}()),dr.exports),gr=Yt(hr),pr=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).utils["IN_MINI_APP"];this.httpRequest=t?Bi:xi,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(u){return de(this,void 0,void 0,function*(){let r=tr+" uploadToCOS",{ssoLog:n,utils:{safeStringify:t}}=this._core,i=u["file"];this.uploadFileType=u.uploadFileType,n.debug("uploadToCOS",r+" options:"+t(u));try{let e=Date.now(),t=yield this._createCosOptions(u),s=t.fileExistsInCOS?{data:{location:t.downloadUrl}}:yield this._uploadFile(t);this._handleUploadError(s,u);var o=this._createUploadResult(i,s),a=Date.now()-e,l=`size:${zi(i.size)} time:${a}ms speed:`+Ji(1e3*i.size/a);return n.debug("uploadToCOS",r+` ok. name:${i.name} `+l),{uploadOptions:t,response:o}}catch(e){throw n.warn("uploadToCOS",r+" failed, error:"+t(e)),e}})}_handleUploadError(e,t){var s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(403===e.statusCode)throw t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new s({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:Hi(Date.now(),!1),uploadSpeed:Ji(1e3*e.size/Hi(Date.now(),!1))}}_createCosOptions(g){return de(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:s}=yield this._prepareUploadParams(g),r=this._isC2CConversation(g.message.conversationID)?1:2;try{var n=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:g.message.from,conversationType:r}),{uploadUrl:i,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,existFlag:d}=n,h=!lr.isPrivateNetWork()&&n.uploadIP;return{url:this._getRawOrUploadProxyUrl(i),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,uploadIP:h||"",fileExistsInCOS:1===d,onProgress:e=>this._handleUploadProgress(e,g)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(o){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t,isEmpty:s}}=this._core,e=(e.debug("_prepareUploadParams"," prepareUploadParams:"+t(o)),o)["file"],t=yield this._generateHashFileName(e),{IN_MINI_APP:r,IN_RN_APP:n}=lr.getPlatformFlags(),r=r||n,n=r&&o.message.type!==Zi,i=e["name"],i=i.slice(i.lastIndexOf(".")),i=""+Ki(999999)+i,n=n?e.name:i;return{fileName:s(t)?Wi(n):t,resources:r?e.url:e,uploadMethod:r?1:0}})}_generateHashFileName(a){return de(this,void 0,void 0,function*(){var{utils:{IN_MINI_APP:e,IN_BROWSER:t,IN_UNI_NATIVE_APP:s,isArray:r},ssoLog:n}=this._core,i=Date.now();let o="";return t&&(o=yield this._generateHashFileNameInWeb(a)),e&&(r(a.tempFiles)&&(a=a.tempFiles[0]),s||(o=yield this._generateFileNameInMiniProgram(a)),s)&&(o=yield this._generateFileNameInUNINativeApp(a)),n.info("_generateHashFileName",`hashFileName:${o} costTime:`+(Date.now()-i)),o})}_generateHashFileNameInWeb(h){return de(this,void 0,void 0,function*(){let{ssoLog:d,utils:{safeStringify:t}}=this._core,e="";try{e=yield new Promise((t,s)=>{let r=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice,n=(r||(d.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),t("")),10485760),i=Math.ceil(h.size/n),o=0,a=new gr.ArrayBuffer,l=new FileReader,u=setTimeout(()=>{l.abort(),d.warn("_generateHashFileNameInWeb","File hash generation timeout"),t("")},2e3);function c(){var e=o*n,t=e+n>=h.size?h.size:e+n;l.readAsArrayBuffer(r.call(h,e,t))}l.onload=e=>{d.debug("_generateHashFileNameInWeb",`read chunk nr ${o+1} of `+i),a.append(e.target.result),++o<i?c():(d.debug("_generateHashFileNameInWeb","finished loading"),clearTimeout(u),t(a.end()))},l.onerror=e=>{clearTimeout(u),s(e)},c()})}catch(e){d.warn("_generateHashFileNameInWeb",t(e))}return e})}_generateFileNameInMiniProgram(n){return de(this,void 0,void 0,function*(){let{utils:{MINI_APP_NAMESPACE:e,safeStringify:t},ssoLog:s}=this._core,r="";try{r=yield new Promise((t,s)=>{e.getFileSystemManager().getFileInfo({filePath:n.tempFilePath,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){s.warn("_generateFileNameInMiniProgram",t(e))}return r})}_generateFileNameInUNINativeApp(r){return de(this,void 0,void 0,function*(){var{utils:{safeStringify:t},ssoLog:s}=this._core;let e="";try{e=yield new Promise((t,s)=>{plus.io.getFileInfo({filePath:r.tempFilePath,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){s.warn("_generateFileNameInMiniProgram",t(e))}return e})}_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 de(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core,r=lr.isSimpleCos(),n=this._prepareCosRequestData(e),i=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(n,i,o){return de(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:n,data:i}),r=s.head.seq+n;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(i,n,this._core);this.fetchCosTryCount=0;var o=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+s(o)),o||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;let s=lr.isSimpleCos(),l=s?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(s){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:r,str_download_url:n,str_upload_url:i,str_snapshot_url:o,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:n,uploadUrl:i,requestSnapshotUrl:o,fileKey:a}}let{upload_url:r,download_url:n,snapshot_url:i,thumb_url:o,large_url:a,file_key:u}=l;return{uploadUrl:r,downloadUrl:n,requestSnapshotUrl:i,thumbUrl:o,largeUrl:a,fileKey:u}}_prepareCosRequestData(e){return lr.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:lr.getPlatform(),uint32_sdkappid:lr.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(n){return de(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(n,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(n).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}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{var r=null==(t=e.error)?void 0:t.Code,n=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===n}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=lr.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let _r=2108,mr=2251,vr=2252,fr=["jpg","jpeg","gif","png","bmp","image","webp"],Ir=20971520,Er={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Sr{constructor(e,t){this.instanceID=Ki(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=lr.addAuthToUrl(e.imageUrl||e.url||""),this.url=lr.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=lr.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Cr(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,n=parseInt(e)||0,s=parseInt(s)||0,i={url:void 0,width:0,height:0};if((n<=s?n:s)<=r)i.url=t,i.width=n,i.height=s;else{s<=n?(i.width=Math.ceil(n*r/s),i.height=r):(i.width=r,i.height=Math.ceil(s*r/n));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";i.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}if(void 0!==t)return i;return le(i,["url"])}class Mr{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Qi;var{uuid:e,file:t,imageFormat:s,imageInfoArray:r=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:s,uuid:e,imageInfoArray:[]},this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:s,ImageInfoArray:r,UUID:n}=t,i=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new Mr({imageFormat:s,imageInfoArray:i,uuid:n})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:n}=lr.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),n)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new Sr(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,s;e.url&&""!==e.imageUrl&&([t,...s]=e.imageUrl.split("://"),s=s.join("://"),r.includes(t)||e.setImageUrl("https://"+s))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=Er[e.toUpperCase()]||Er.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var s,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)s=this.content.imageInfoArray[e],t[e].size&&(s.size=t[e].size),t[e].url&&s.setImageUrl(t[e].url),t[e].width&&(s.width=t[e].width),t[e].height&&(s.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,s=t[2];t[2]=t[1],t[1]=s;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],Cr({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var[e]=this.content.imageInfoArray,e=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(s),UUID:e}}}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:lr.removeAuthToUrl(e.imageUrl)}))}}var yr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Qi,Mr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,r;try{var n=null==(t=this._core.store.get("login"))?void 0:t.userId,i=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),o=this._processImage(e),a=(e.payload.file=o,{imageFormat:Er.UNKNOWN,uuid:lr.generateUUID(o),file:o,imageInfoArray:[]}),l=new Mr(a);return i.setElement(l),this._messageOptionsMap.set(i.clientSequence,e),i}catch(e){throw e}}upload(r){return de(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,n,s){return de(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:nr,file:s,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{uploadOptions:e,response:t}=yield pr.uploadToCOS(e);return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:s,height:r,smallImageUrl:n,smallImageWidth:i,smallImageHeight:o,largeImageUrl:a,largeImageWidth:l,largeImageHeight:u,imageInfoArray:c}=e,e=lr.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):n&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:n,smallImageWidth:i,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return Cr({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,n;for(var i of e)1===i.type?(r=i,r.size=t):2===i.type?(n=i,n.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},n),Object.assign({},r)]}_parseResponse(r,n){return de(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,n,"thumb"),yield this._getImageInfoByUrl(t,n,"large")),lr.isSimpleCos()&&!lr.isPrivateNetWork()&&(yield this._getImageInfoArray(s,n),null!=n)&&n.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,n))}return n}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,n,i){return de(this,void 0,void 0,function*(){var t;try{let e=lr.addAuthToUrl(r),{width:t=0,height:s=0}=yield lr.probeImageWidthHeight(e);n.width=t,n.height=s,"thumb"===i?(n.smallImageUrl=r,n.smallImageWidth=t,n.smallImageHeight=s):(n.largeImageUrl=r,n.largeImageWidth=t,n.largeImageHeight=s)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${i} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:mr});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var s=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return s?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){ji(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var 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=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=lr.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,n){return de(this,void 0,void 0,function*(){var e=tr+" getDownloadIP domainName: "+r;try{var t,s=yield function(o,a){return de(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:o},n=e.generateProtocolData({servcmd:s,data:r}),i=n.head.seq+s;return yield t.sendPacket(n,{requestId:i})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=n.location.split("/"))[0]=s.str_final_ip,n.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,s){return de(this,void 0,void 0,function*(){try{var e=yield function(o,a){return de(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:o},n=e.generateProtocolData({servcmd:s,data:r}),i=n.head.seq+s;return yield t.sendPacket(n,{requestId:i})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return s.imageInfoArray=this._processImageInfoResponse(e),s}catch(e){throw s.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.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){var{utils:t,helper:s}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),fr.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:vr})}_checkImageSize(e){var{utils:t,helper:s}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new s.ChatError({code:_r});if(r>=Ir)throw new s.ChatError({message:"File size exceeds limit: "+zi(Ir)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Or=2108,Ar=2401,Tr="2.5.0",Rr="1.18.0",Dr=104857600;function br(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(;r.length<i;)r.push("0");for(;n.length<i;)n.push("0");for(let s=0;s<i;s++){let e=parseInt(r[s]),t=parseInt(n[s]);if(e>t)return 1;if(e<t)return-1}return 0}let Nr=new class{init(e){this.core=e}};class Lr{constructor(e){this.type=Zi,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:lr.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:s,FileSize:r,UUID:n}=e;return new Lr({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:s,fileName:r,fileSize:n}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:lr.removeAuthToUrl(s),FileName:r,FileSize:n,UUID:e}}}_getFileInfo(e){var t=Nr.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=Ki(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)}}var Pr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Zi,Lr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,r;try{this._checkVersion();var n=this._processFile(e.payload.file),i=(e.payload.file=n,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),a={uuid:lr.generateUUID(n),file:n},l=new Lr(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(s){return de(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),s.getElements()[0]),e=yield this._performFileUpload(t,s,e),e=lr.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),s})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:Ar});if(e.size>Dr)throw new t({message:"File size exceeds limit: "+zi(Dr)});if(0===e.size)throw new t({code:Or})}_performFileUpload(r,n,t){return de(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:rr,file:t,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield pr.uploadToCOS(e))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e||i){let e=lr.extractFileFromInput(t);if(e)return e;throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||n){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(e){if(!(s||r||n))throw new i({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&br(e,Tr)<0)throw new i({message:`WXChooseMessageFile requires SDK version ${Tr} or higher`});if(r&&br(e,Rr)<0)throw new i({message:`QQChooseMessageFile requires SDK version ${Rr} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Gr=2108,wr=2352,Ur=["mp4","quicktime","mov"],kr=104857600;class Fr{constructor(e){this.type=er,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:lr.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:lr.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:lr.addAuthToUrl(e.thumbUrl),snapshotUrl:lr.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:n,VideoUUID:i,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:_,SnapshotUrl:m}=e;return new Fr({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:n,videoUUID:i,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s}=e;lr.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),lr.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),lr.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){var e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:n,videoUUID:i,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:lr.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:n,VideoUUID:i,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:lr.removeAuthToUrl(_),SnapshotUrl:lr.removeAuthToUrl(m)}}}}var $r=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(er,Fr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,r;try{var n=this._processVideo(e),i=(e.payload.file=n,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),a={videoFormat:n.videoFile.type,videoSecond:Yi(n.videoFile.second,0),videoSize:n.videoFile.size,remoteVideoUrl:"",videoUrl:n.videoFile.url,videoUUID:lr.generateUUID(n.videoFile),thumbUUID:lr.generateUUID(n.videoFile,"jpg"),thumbWidth:n.width||200,thumbHeight:n.height||200,thumbUrl:n.thumbUrl,thumbSize:n.thumbSize,thumbFormat:"jpg"},l=new Fr(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(r){return de(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:s}=t,t=lr.addAuthToUrl(t);return e.updateVideoUrl(t),lr.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>kr)throw new t({message:"File size exceeds limit: "+zi(kr)});if(0===e.videoFile.size)throw new t({code:Gr});if(-1===Ur.indexOf(e.videoFile.type))throw new t({code:wr})}_performVideoUpload(r,n,s){return de(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:or,file:s,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{response:e,uploadOptions:t}=yield pr.uploadToCOS(e);return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,n;try{var i=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(n=this._core)?void 0:n.utils;let t=e.payload["file"],s={};if(o&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url,t.type=s.type),a){let e=lr.extractFileFromInput(t);if(!e)throw new i({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,s=this._processWebVideoFile(t)}return t.videoFile=s,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(tr+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:s}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(ji(e))throw new r({message:"FileUnsupportedInMiniApp"});let n=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(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){var{name:t,size:s=1,duration:r=0,type:n}=e,n=n.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:n}}_getSnapshotInfoByUrl(i){return de(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",tr+" _getSnapshotInfoByUrl url:"+i);var t,s,r,n=((yield function(i,o){return de(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,r=t.generateCosSpecifiedData({servcmd:e,data:i}),n=r.head.seq+e;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:lr.getPlatform(),cover_name:Wi(Ki(99999)),snapshot_url:i},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",tr+" _getSnapshotInfoByUrl OK snapshotUrl:"+n),lr.isEmpty(n))?{}:(t=lr.addAuthToUrl(n),{width:s=0,height:r=0}=yield lr.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:s,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class qr{constructor(e){this.uploadProgress=0,this.type=Xi,this.content={downloadFlag:2,second:e.second,size:e.size,url:lr.addAuthToUrl(e.url),remoteAudioUrl:lr.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:n}=e;return new qr({url:e,downloadFlag:t,second:s,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:s,size:r,second:n}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:lr.removeAuthToUrl(s),Download_Flag:t,Second:n,Size:r,UUID:e}}}}let xr=2108,Vr=2300,Br=20971520;var jr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Xi,qr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,r;try{var n=e.payload["file"],n=this._processAudioFile(e.payload.file),i=(e.payload.file=n,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),a={second:Math.floor((n.duration||n.second)/1e3),size:n.fileSize||n.size||1,url:n.tempFilePath||n.uri||n.url,uuid:lr.generateUUID(n)},l=new qr(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(s){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",tr+" uploadAudio message:"+t(s)),this._messageOptionsMap.get(s.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),s.getElements()[0]),e=yield this._performAudioUpload(t,s,e),e=lr.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),s})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:Vr});if(e.size>Br)throw new t({message:"File size exceeds limit: "+zi(Br)});if(0===e.size)throw new t({code:xr})}_performAudioUpload(r,n,t){return de(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:ir,file:t,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield pr.uploadToCOS(e))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:s}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):s?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){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Kr={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}},Hr={createImageMessage:Kr,createAudioMessage:Kr,createVideoMessage:Kr,createFileMessage:Kr},Wr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Yr={[Qi]:yr,[Zi]:Pr,[er]:$r,[Xi]:jr};var ia,ra,aa,zr=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:n}}=(this._core=e)["constants"];Nr.init(e),yr.init(e),Pr.init(e),$r.init(e),jr.init(e),pr.init(e),lr.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,n].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Wr,params:Hr})}sendMessage(r,n){return de(this,void 0,void 0,function*(){var e,t,s;try{return yield this._upload(r),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,n)}catch(e){throw e}})}_upload(s){return de(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(s)),!0!==s._relayFlag)try{let e=Yr[s.type];e&&(yield e.upload(s),t.info("_upload"," type:"+s.type))}catch(t){throw s.status=ar.FAIL,t instanceof Error&&(t.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),t}})}};let Jr=new class{init(e){this.core=e}},Qr=e=>{var{OuterConstant:t,utils:{isString:s}}=Jr["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},Xr=e=>{var{OuterConstant:t,utils:{isString:s}}=Jr["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},Zr=e=>{var{OuterConstant:t,utils:{isString:s}}=Jr["core"];return s(e)&&e===t.CONV_SYSTEM},ea=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:Jr.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 ta(e){var t=Jr.core["OuterConstant"];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 sa(e){var t=Jr.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}function na(e,t){var s=Jr.core["helper"],s=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:",s),s}class oa{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=ea(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{OuterConstant:e,utils:{isUndefined:t}}=Jr["core"];t(this.userProfile)&&this.type===e.CONV_C2C?this.userProfile={}:t(this.groupProfile)&&this.type===e.CONV_GROUP&&(this.groupProfile={}),this.subType&&this.type===e.CONV_GROUP&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){var{OuterConstant:t,utils:{isUndefined:s}}=Jr["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:n}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||n&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=ea(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=Jr["core"]["OuterConstant"],{sequence:e,time:s}=e;return this.type===t.CONV_C2C&&e===this.lastMessage.lastSequence&&s===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&e===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=Jr["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(ia=ia||{}),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ra=ra||{}),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"}(aa=aa||{});let ca=0,ua=1;var la=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:t,notificationCenter:s,appStore:{conversationStore:r},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i},InnerEvent:{SYNC_CONVERSATION_LIST:o,MESSAGE_PUSH:a,NEW_MESSAGE:l,MESSAGE_DELETED:u,MESSAGE_REVOKED:c,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:h,LOGOUT:g,DESTROY:p},InnerEventSubType:{C2C_MESSAGE_PEER_READ:_}}=this._core=e,r=(this._conversationStore=r,t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_GROUP_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_GROUP_TIPS_NOTIFICATION,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s)["InnerEventSubType"]["GROUP_AT_TIPS"];s.subscribeInnerEvent(o,this._handleConversationSynced,this),s.subscribeInnerEvent(l,this._handleNewMessage,this),s.subscribeInnerEvent(a,r,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(h,this._handleConversationUpdated,this),s.subscribeInnerEvent(a,_,this._handleMessageRead,this),s.subscribeInnerEvent(g,this._reset,this),s.subscribeInnerEvent(p,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){let{WORKFLOW_STEP:t}=this._core["constants"],{conversationUpdateFieldList:s=[],groupTipList:r=[],isUnreadC2CMessage:n}=e.result[t.UNREAD_MESSAGE_SYNC]||{},i=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:n}),i=!0)}),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,n=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:i}=this._core.OuterConstant,o=!1;for(let s=0;s<n.length;s++){let e=n[s],t=""+i+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:n=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:n}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:n}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=r,i.__sequence=n,this._groupAtTipsList.push(i)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,n=e.getCurrentUserID(),i=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==n){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),i=!0)}}),i&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:n}=this._core,i=(null==r?void 0:r.getLocalMessageList(t))||[];let o={};for(let e=(i.length||0)-1;0<=e;e--)if(!i[e].isDeleted){o=i[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===o.sequence&&r.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),r.updateLastMessage(o),e=!0),t.startsWith(n.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:n=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(n&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:n}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let 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=n(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){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),this._core.ssoLog.debug("updateLocalConversationList"," newConversationList: "+e.length)}_getTmpConversationListMapping(e){let i=this._core["OuterConstant"],{conversationUpdateFieldList:o,isFromGetConversations:a,isInstantMessage:l,isUnreadC2CMessage:u=!1,updateUnreadCount:c}=e,d=[],t=null==o?void 0:o.length;for(let n=0;n<t;n++){let t=new oa(o[n]),{conversationID:s,type:r}=t;if(!sa(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===i.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===i.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[n].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:o[n].lastMessage,isInstantMessage:l}),!0===c&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:u}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:n}=e,e=this.getLocalConversation(e),i=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:o},common:{deepMerge:a}}=(!1===n&&i.push("lastMessage"),r&&i.push("isPinned"),this._core);r(n)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),o(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,i,[null,void 0,"",0,NaN])}_patchLastMessage(e){let n=this._core["OuterConstant"],{conversationID:t,lastMessage:i,isInstantMessage:o}=e,a=this.getLocalConversation(t);if(a&&i){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=i;o&&(e&&(a.lastMessage.payload=e),a.type===n.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],n=[],i=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?i:n).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(n.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(i);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:n,CONV_C2C:i}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===i){let e=t.replace(i,"");s.push(e)}else if(e===n){let e=t.replace(n,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:n},appStore:{userStore:i},user:s}=this._core,o=!1;null!=(t=s.userProfile)&&t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(t=>{var s=t["userID"],r=this.getLocalConversation(""+n+s);if(r){let e=(null==(s=i.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,n=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,n=!0)}),n&&this.emitConversationListUpdate()}_handleMessageRead(e){let{CONV_C2C:r}=this._core["OuterConstant"],{C2cNotifyMsgArray:t=[]}=e||{};t.forEach(e=>{let{To_Account:s,UinPairReadArray:t=[]}=(null==e?void 0:e.C2cReadedReceipt)||{};null!=t&&t.forEach(e=>{var e=e["LastReadTime"],t=""+r+s;this._updateConversationReadInfo({conversationID:t,peerReadTime:e}),this._updateMessageListPeerRead({conversationID:t,peerReadTime:e})})})}_updateConversationReadInfo(e){var{appStore:t,utils:{isEmpty:s},common:{getCurrentUserID:r}}=this._core,{conversationID:n,peerReadTime:i}=e,o=t.conversationStore.getConversationMap();if(o.has(n)){let e=o.get(n);e.peerReadTime=i;o=null==e?void 0:e.lastMessage;s(o)||o.fromAccount===r()&&o.lastTime<=i&&!o.isPeerRead&&(o.isPeerRead=!0,t.conversationStore.updateConversation(n,{lastMessage:o}))}}_updateMessageListPeerRead(e){let{notificationCenter:t,OuterEvent:s,message:r}=this._core,{conversationID:n,peerReadTime:i}=e,o=r.messageDataHandler.getLocalMessageList(n),a=r.messageDataHandler.getSparseMessageList(n),l=[];o.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,l.push(e))}),a.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,l.push(e))}),t.emitOuterEvent(s.MESSAGE_READ_BY_PEER,{name:s.MESSAGE_READ_BY_PEER,data:l})}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:r},utils:{isUndefined:n}}=this._core,e=this.getLocalConversation(e);return!(!n(e)&&(n=e.type===t&&(null==(n=e.groupProfile)?void 0:n.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===r,n||t))}updateUnreadCount(e,t=!0){let s,r,n=!1;var i,o=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return o&&(i=o.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${i} newUnreadCount:`+a),i!==a)&&(o.unreadCount=a,(n=!0)===t)&&this.emitConversationListUpdate(),n}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,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.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){let{OuterConstant:t,utils:{isEmpty:s}}=this._core,e=this.getLocalConversationList(),r=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(r+=e.unreadCount)}),r}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(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:n=0,lastReadSequence:i=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let r=e-1;0<=r;r--){let e=o[r],t=n&&e.time>n,s=i&&e.sequence>i;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var 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(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:n,CONVERSATION_UPDATED:i,LOGOUT:o,DESTROY:a,SYNC_CONVERSATION_LIST:l}}=this._core,{GROUP_AT_TIPS:u}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(l,this._handleConversationSynced,this),e.unSubscribeInnerEvent(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},da=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return de(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(o){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(o))return la.getLocalConversationList();if(t(o))return 0===o.length?[]:la.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:r,hasUnreadCount:n,hasGroupAtInfo:i}=o;return la.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,n)&&this._filterGroupAtInfo(e,i))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},ha=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return de(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return de(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:r},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=ta(t);la.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},ga=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return de(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:t=[]}=e||{};t.forEach(e=>{var{GroupId:e,MemberList:t}=e,t=(null==(t=t[0])?void 0:t.MsgFlag)||"",e=""+this._core.OuterConstant.CONV_GROUP+e;la.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},pa=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return de(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:n},appStore:{groupStore:i},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=la.getLocalConversation(u);if(Zr(u))o.data.conversation=a;else{let t=!1;var l=Qr(u)?s:r;if(e(a)&&(t=!0,a=new oa({conversationID:u,type:l})),console.log(this._name+`.getConversationProfile conversationID:${u} isNewConversation:`+t),null==(o.data.conversation=a)||!a.getProfileCompleted()){if(l===s){let e=u.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield ha.get([e]))}if(l===r){let e=u.replace(r,"");if(!i.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==n&&(yield ga.get([e]))}}}return o})}_handleC2CConversation(o,a){return de(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:n}}=this._core,i=o["conversationID"],e=yield null==(e=e.userProfile)?void 0:e.getUserProfile({userIDList:[a]});if(0===(null==e?void 0:e.data.length))throw new t.ChatError({code:aa.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=n.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),n=la.hasLocalConversation(i);console.log(this._name+`._handleC2CConversation conversationID:${i} hasLocalConversation: `+n),n?r.updateConversation(i,o):la.appendToPinnedConversation(o)})}_handleGroupConversation(r,n){return de(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:n}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),la.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):la.appendToPinnedConversation(r)})}},_a=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return la.getTotalUnreadMessageCount()}},ma=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{ALL_MESSAGE_READ:i}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(n,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),la.markMessageAsRead({conversationID:e,lastReadTime:t}),la.updateUnreadCount(e)})}})}handleGroupMessageReadSync(e){let{OuterConstant:s,utils:{isUndefined:t}}=this._core;e.forEach(e=>{e=e.MsgBody.GroupReadInfoArray;t(e)||e.forEach(e=>{var{GroupId:e,LastReadMsgSeq:t}=e,e=""+s.CONV_GROUP+e;console.log(this._name+`.handleGroupMessageReadSync conversationID:${e} lastReadSequence:`+t),la.markMessageAsRead({conversationID:e,lastReadSequence:t}),la.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(l){return de(this,void 0,void 0,function*(){var e,t=this._core["OuterConstant"],s=l["conversationID"],r={code:0,data:{}},n=la.getLocalConversation(s);let i=this._name+`.setMessageRead conversationID:${s} unreadCount:`+((null==n?void 0:n.unreadCount)||0);if(r.successLog={message:i},!n)return r;var o=!(null!=(e=null==(o=this._core)?void 0:o.helper)&&e.isEmpty(n.groupAtInfoList));if(n.type===t.CONV_GROUP&&o&&this._deleteGroupAtTips(s),0===n.unreadCount)return r;var a=this._core["helper"]["ChatError"];try{if(n.type===t.CONV_C2C){let e=this._getLocalMessageMaxTime(n);yield this._setC2CMessageRead(s,e),i+="lastMessageTime:"+e}if(n.type===t.CONV_GROUP){let e=this._getLocalMessageMaxSequence(n);yield this._setGroupMessageRead(s,e),i+="lastMessageSequence:"+e}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new a({functionName:"setMessageRead",code:t,message:s,moreMessage:i})}return n.type===t.CONV_SYSTEM&&(n.unreadCount=0),la.emitConversationListUpdate(),Object.assign(Object.assign({},r),{successLog:{message:i}})})}setAllMessageRead(){return de(this,arguments,void 0,function*(t={}){let{OuterConstant:{READ_ALL_MSG:e},utils:{safeStringify:n}}=this._core,i="scope:"+t.scope,s=(t.scope||(t.scope=e),t)["scope"],o=this._generateSetAllMessageReadRequestData(s);if(o.allC2CMessageReadStatus===ca&&0===o.groupMessageReadInfoList.length)return{code:0};try{let r=yield function(s){return de(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return Jr.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(o);if(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&la.emitConversationListUpdate(),i+="failureGroupInfoList:"+n(s)}return{code:0,successLog:{message:i}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e,moreMessage:i})}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&la.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:n},appStore:t}=this._core,i=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of i)if(1<=t.unreadCount){if(o===ua&&t.type===r){let e=this._getLocalMessageMaxTime(t);la.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===n){let t=s.replace(n,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);la.markMessageAsRead({conversationID:s,lastReadSequence:e})}}la.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:n,CONV_GROUP:i,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:ca,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===n&&a.allC2CMessageReadStatus===ca){if(a.allC2CMessageReadStatus=ua,r===o)break}else if(e===i){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:n}=this._core["utils"],i=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;n(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&i.push(e+`-${t}-`+s))}),i}_deleteGroupAtTips(o){return de(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=la.getLocalConversation(o);if(e){var i=(null==e?void 0:e.groupAtInfoList)||[];if(0!==i.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,n=[...i];e({groupID:o.replace(s,"")})&&0===(n=i.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return de(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:n.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+i.length),this._clearGroupAtInfoList(o))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=la.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&la.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.time));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastTime)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${s} to `+t),s=t),s}_getLocalMessageMaxSequence(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.sequence));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastSequence)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${s} to `+t),s=t),s}_setC2CMessageRead(e,t){return de(this,void 0,void 0,function*(){try{yield function(e,t){return de(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),la.markMessageAsRead({conversationID:e,lastReadTime:t}),la.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return de(this,void 0,void 0,function*(){try{yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:{GroupId:e,MsgReadedSeq:t}})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(this._name+"._setGroupMessageRead ok, lastReadSequence:"+t),la.markMessageAsRead({conversationID:e,lastReadSequence:t}),la.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:n,READ_ALL_GROUP_MSG:i}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![r,n].includes(o))&&(e!==s||![r,i].includes(o)))}},va=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,o){var{isArray:t}=this._core["utils"];if(t(e)){let n=this._core["OuterConstant"],i=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=la.getLocalConversation(""+n.CONV_C2C+t):2===e&&(r=la.getLocalConversation(""+n.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+o),o&&!r.isPinned&&(r.isPinned=!0,i=!0),!o)&&r.isPinned&&(r.isPinned=!1,i=!0)}),i&&la.emitConversationListUpdate(!0)}}pinConversation(e){return de(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,helper:{ChatError:n}}=this._core,{conversationID:i,isPinned:o}=e,a={code:0,data:{conversationID:i}},l=la.getLocalConversation(i);if(l&&l.isPinned===o)return a;if(Zr(i))return l&&(l.isPinned=o),la.emitConversationListUpdate(!0),a;var u=`conversationID:${i} isPinned:`+o;try{let e=null,t=(Qr(i)?e={Type:1,To_Account:i.replace(s.CONV_C2C,"")}:Xr(i)&&(e={Type:2,GroupId:i.replace(s.CONV_GROUP,"")}),yield function(r,n){return de(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return n.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(t){if(l)l.isPinned!==o&&(l.isPinned=o);else{let e=new oa({conversationID:i,type:Qr(i)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});la.setLocalConversation(i,e)}la.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},a),{successLog:{message:u}})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n({functionName:"pinConversation",code:t,message:s,moreMessage:u})}})}},fa=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],n=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&n.push(""+r.CONV_C2C+t),2===e&&n.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+n),this._deleteLocalConversationList(n)}}deleteConversation(t){return de(this,void 0,void 0,function*(){var e=this._core["utils"]["isString"];e(t)?yield this._deleteConversation({conversationIDList:[t],flag:ra.ONLY_CONVERSATIONID}):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return de(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:n=0}=e,{ChatError:i}=this._core["helper"],o=`conversationIDList:${s} clearHistoryMessage:`+r;try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:aa.CONV_NOT_FOUND});return{code:0,data:n===ra.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t},successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({code:t,message:s,moreMessage:o})}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!la.hasLocalConversation(e)&&((t=null==(t=la.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,i){return de(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,n={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:i?1:0};if(t.forEach(e=>{var t,s;la.hasLocalConversation(e)&&(t=(null==(t=la.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?n.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&n.conversationList.push({ToGroupid:s,Type:2}))}),0!==n.conversationList.length){var s=yield function(r,n){return de(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return n.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(n,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.Type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{la.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&la.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=la.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(la.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&la.emitConversationListUpdate()}_hasLocalGroup(e){var{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,e=e.replace(t,"");return!!s.getGroup(e)}_deleteConversationLocalMessage(e){console.log(this._name+"._deleteConversationLocalMessage conversationID:"+e),this._core.message.messageDataHandler.deleteConversationMessageList(e)}},Ia=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return de(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),la.hasLocalConversation(e))return null!=(e=la.getLocalConversation(e))&&e.setDraftText(t),la.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:aa.CONV_NOT_FOUND})})}},Ea=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return de(this,void 0,void 0,function*(){30<a.length&&(console.warn(`${this._name}.set userIDList length:${a.length} exceeds limit 30`),a.splice(30));let e=function(){var{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=Jr.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[l],t=yield function(s,r){return de(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:{Peer_Account:e,Mute_Notifications:t}})})}({userIDList:a,receiveMessageOption:e},this._core),{ErrorList:s=[]}=t||{},r=[],n=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),i=[],o=this._core["OuterConstant"];return a.forEach(e=>{i.push(""+o.CONV_C2C+e),n.push({userID:e})}),la.patchMessageRemindType(i,l),{code:0,data:{successUserIDList:n,failureUserIDList:r}}})}},Sa=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,n){return de(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:n},this._core),!t(r)){let e=""+s.CONV_GROUP+r;la.patchMessageRemindType([e],n)}return{code:0,data:{groupID:r,messageRemindType:n}}})}},Ca=new class{constructor(){this._name="SetMessageRemindType"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){let{helper:{isEmpty:t},OuterConstant:i,ssoLog:o}=this._core;e.forEach(e=>{var n=e["MuteNotificationsSync"];if(!t(n)){let{To_Account:e,MuteNotifications:t}=n,s=e.map(e=>""+i.CONV_C2C+e),r=ta(t);o.debug(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),la.patchMessageRemindType(s,r)}})}setMessageRemindType(a){return de(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=a,{helper:n,utils:{isUndefined:i},ssoLog:o}=this._core;try{if(!i(e))return o.debug(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield Sa.set(e,r);if(i(t))throw new n.ChatError({functionName:s,message:"userIDList or groupID is required"});return o.debug(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield Ea.set(t,r)}catch(e){let t=new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},Ma=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,da.init(e),pa.init(e),_a.init(e),ma.init(e),va.init(e),fa.init(e),Ia.init(e),Ca.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];fa.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];va.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];va.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;ma.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;Ca.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;ma.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},ya=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return de(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=o,{startTime:r=0,endTime:n=0}=this._calcStartAndEndTime(o),i=yield function(i){return de(this,void 0,void 0,function*(){var e=Jr.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:n}=i;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:n}})})}({messageRemindType:this._getType(t),startTime:r,endTime:n,isRepeated:s?ia.ON:ia.OFF});return{code:0,data:{errorCode:i.ErrorCode,errorInfo:i.ErrorInfo}}}catch(e){na("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:n=!0}=e,i=new Date,i=new Date(i.getFullYear(),i.getMonth(),i.getDate(),e,t,s),e=Math.round(i.getTime()/1e3);let o=n&&86400<=r?e+86400:e+r;return{startTime:e,endTime:o}}_getType(e){var t=this._core["OuterConstant"];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){var{helper:e,notificationCenter:t,InnerEvent:s}=this._core=e;e.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),t.subscribeInnerEvent(s.MESSAGE_PUSH,t.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){var e=this._handleResult(e),{notificationCenter:t,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:e})}getAllReceiveMessageOpt(){return de(this,void 0,void 0,function*(){try{var e=yield function(){return de(this,void 0,void 0,function*(){var e=Jr.core["common"],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){na("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:n,EndTime:i,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:n,endTime:i,isRepeated:o===ia.ON}}},Aa=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,Ea.init(e),Sa.init(e),ha.init(e),ga.init(e),ya.init(e),Oa.init(e)}};let Ta=e=>!Qr(e)&&!Xr(e)&&!Zr(e),Ra={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Ta(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Ta(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Ta(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{var{utils:{isArray:t,isObject:s,isString:r}}=Jr["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&Ta(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(Ta(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=>!(!Qr(e)&&!Xr(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}}},Da={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var ba=new class{constructor(){this.name="Conversation"}install(e){Jr.init(e),Ma.init(e),Aa.init(e),la.init(e),e.helper.registerValidateConfig({auth:Da,params:Ra})}};let Na=new class{init(e){this.core=e}},La="AVChatRoom",Pa="AV_HISTORY_MSG",Ga="GRP_COUNTER",wa="Set",Ua="Increase",ka="Decrease",Fa=0,$a=1,qa=2,xa=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Va=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ba=["Role","JoinTime","MsgFlag","MsgSeq"],ja=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Ka=0,Ha=1,Wa="notStart",Ya="resolved",za="rejected",Ja=10018,Qa=11e3,Xa=2,Za=["Owner","Admin","Member"],ec=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],tc=0,sc=1,nc=2,oc=4,ic=1,rc=2,ac=3,cc=4,uc=5,lc=1,dc=0,hc=4,gc=6,pc=400,_c=300,mc={from:!0,groupID:!0,groupName:!0,to:!0},vc={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},fc=2,Ic=4,Ec=5,Sc=7,Cc=8,Mc=15,yc=20,Oc=21,Ac=2600,Tc=2602,Rc=2603,Dc=2620,bc=2621,Nc=2623,Lc=2660,Pc=2661,Gc=2681,wc=2683,Uc=2684,kc=2685,Fc=2687,$c=3122,qc=10018,xc=e=>e===Na.core.OuterConstant.GRP_PUBLIC,Vc=e=>e===Na.core.OuterConstant.GRP_AVCHATROOM,Bc=(r,e)=>{var t=Na.core.utils["isArray"];if(!t(r)||!t(e))return!1;let n=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,n=!0):(r.push({key:t,value:e}),n=!0)}),n},jc=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:n,Value:i}=s[e];r.push({key:n,value:i})}return r},Kc=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:n,value:i}=s[e];r.push({Key:n,Value:i})}return r};function Hc(e,t){var s=Na.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:$c,replacement1:e})}function Wc(e,t){var s=Na.core["helper"],s=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:",s),s}let Yc=["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){var t,{isString:s}=Na.core["utils"];for(t in e)Yc.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:n},common:{deepMerge:i}}=Na.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),n(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&Bc(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),i(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&i(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:n,excludedUnreadSequenceList:i}=e,o=Na.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:n,excludedUnreadSequenceList:i},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var Jc=new class{constructor(){this._name="GroupDataHandler"}init(e){var e=(this._core=e)["appStore"]["groupStore"];this._groupMap=e.getGroupMap()}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){var{getCurrentUserID:t}=this._core["common"];let s;e.forEach(e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null!=(t=this.getLocalGroup(s))&&t.updateGroup(e):this._groupMap.set(s,new zc(e))});var r=t();for(let[,e]of this._groupMap)e.selfInfo.userID=r,"Owner"===e.selfInfo.role&&(e.ownerID=r)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){let{GRP_ROOM:t,GRP_LIVE:s}=this._core["OuterConstant"];return[...this._groupMap.values()].filter(e=>{e=e.type;return e!==t&&e!==s})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){var e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(t){let{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:e}}=this._core,r=""+e+t;if(s.getConversation(r)){let e=this.getLocalGroup(t);s.updateConversation(r,{groupProfile:e})}}reset(){this.clearLocalGroup()}};function Qc(o,a){return de(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:n,responseFilter:i}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:n,ResponseFilter:i,SupportTopic:r,NeedAppDefineData:1}})})}let Xc=function(e,t){return{code:0,data:e||{},successLog:t}};var Zc=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Wa,this.PAGING_GRP_COUNT_LIMIT=200}init(e){var{helper:e,constants:{WORKFLOW_NAME:t,WORKFLOW_STEP:s}}=this._core=e;e.registerApi({apiName:"getGroupList",context:this}),e.registerWorkflowStep(t.SYNC_SERVER_INFO_AFTER_LOGIN,s.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return de(this,arguments,void 0,function*(e=!1){if(e){let e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),Jc.updateLocalGroup(e),Jc.getLocalGroupList()}return this._core.ssoLog.debug("getGroupList",this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===za||this._pagingStatus===Wa?this._syncGroupList().then(()=>{var e=Jc.getLocalGroupList();return Xc({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e}):(e=Jc.getLocalGroupList(),Xc({groupList:e,isSyncCompleted:this._isSyncCompleted()},{message:"return group count:"+e.length}))})}_syncGroupList(){return de(this,void 0,void 0,function*(){this._pagingStatus===Wa&&Jc.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Ya,this._groupListTreeShaking(t),Jc.updateLocalGroup(t);var s=Jc.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",this._name+"._syncGroupList ok, count:"+s.length),Jc.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=za,e}})}_pagingGetGroupList(e){return de(this,void 0,void 0,function*(){var n=this._core["ssoLog"],{isCommunityRelay:i=!1,groupList:o}=e;let a,{limit:l,offset:u}=e;var c=[...xa];i&&(a=this._core.OuterConstant.GRP_COMMUNITY,c.push("AtInfoList"));try{let e=yield Qc({type:a,limit:l,offset:u,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:c,SelfInfoFilter:[...Ba]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);var d=u+l,h=!(d<s),g=`offset:${u} limit:${l} total:${s} isCompleted:${h} current:${o.length} isCommunityRelay:`+i;return n.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. "+g),i?h?o:(u=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:l,offset:u,groupList:o})):h?(n.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList start to get community list"),u=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:l,offset:u,groupList:o})):(u=d,this._pagingGetGroupList({limit:l,offset:u,groupList:o}))}catch(e){if(e.ErrorCode===Ja)return n.warn("_pagingGetGroupList",this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+l),this._pagingGetGroupList({isCommunityRelay:i,limit:50,offset:u,groupList:o});if(i)return e.code===Qa&&n.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. community unavailable"),o;throw e}})}_pagingGetJoinedCommunityList(e){return de(this,void 0,void 0,function*(){var{common:{getCurrentUserID:n},OuterConstant:i,ssoLog:o}=this._core,a=e["groupList"];let{limit:l,offset:u}=e;try{let e=yield Qc({limit:l,offset:u,type:i.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...xa],SelfInfoFilter:[...Ba]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);a.push(...r);var c=u+l,d=!(c<s),h=`offset:${u} limit:${l} total:${s} isCompleted:${d} current:`+a.length;return o.debug("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList ok. "+h),d?a:(u=c,this._pagingGetJoinedCommunityList({limit:l,offset:u,groupList:a}))}catch(e){if(e.code===qc)return o.warn("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+l),this._pagingGetJoinedCommunityList({limit:50,offset:u,groupList:a});throw e}})}_groupListTreeShaking(s){var r=new Map([...Jc.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var n=[...r.keys()];for(let e=0,t=n.length;e<t;e++)Jc.deleteLocalGroup(n[e])}_isSyncCompleted(){return this._pagingStatus===Ya}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:n,ApplyJoinOption:i,CreateTime:o,FaceUrl:a,GroupId:l,Introduction:u,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:h,MemberNum:g,MaxMemberNum:p,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:E,LastRecallTime:S,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],n=jc(n),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);r.push({groupCustomField:n,joinOption:i,createTime:o,avatar:a,groupID:l,introduction:u,inviteOption:c,lastInfoTime:d,lastMsgTime:h,memberCount:g,maxMemberCount:p,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:E,selfInfo:C,_lastRevokedTime:S,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:n}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:n}}_convertAtInfoList(r,e){if(0===e.length)return[];let n=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:r,groupAtType:e,sequence:t,from:s})}),n}},eu=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(l){return de(this,void 0,void 0,function*(){var o;this._preCheckParams(l);let e=this._core["helper"]["ChatError"];try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(g,p){return de(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:n,avatar:i,maxMemberNum:o,joinOption:a,inviteOption:l,memberList:u,groupCustomField:c,isSupportTopic:d}=g;let h;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:n,FaceUrl:i,MaxMemberCount:o,ApplyJoinOption:a,InviteJoinOption:l,MemberList:h=u?u.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?Kc(t):void 0}}):h,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return p.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},l),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:n=[]}=s||{},i=`${this._name}.createGroup ok, type:${l.type} groupID:${r} overLimitUserIDList:`+n;e(l.memberList)||e(n)||(l.memberList=null==(o=l.memberList)?void 0:o.filter(e=>n.includes(e.userID))),Jc.updateLocalGroup([Object.assign(Object.assign({},l),{groupID:r})]);var a=Jc.getLocalGroup(r);return this._notNeedSendCustomMessage(l)||(this._sendCustomMessage(r,l.type),Jc.emitGroupListUpdate()),Xc({group:a},{message:i})}catch(o){var{errorCode:a,errorInfo:t}=o;throw new e({functionName:"createGroup",code:a,message:t,moreMessage:" groupID:"+l.groupID})}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:n},common:{isCommunity:i}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:n}=Na.core.OuterConstant;return[e,t,s,r,n]})().includes(t))throw new this._core.helper.ChatError({code:Ac});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:Tc});n(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||n(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||n(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:Tc});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Vc(e)}_canIUseJoinOption(e){return xc(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",n=Ka;t===s.GRP_COMMUNITY&&(r="Create Community",n=Ha);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:n,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},tu=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){var{helper:e,constants:t}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){var e=e["elements"]["newGroupProfile"],{isEmpty:t,isUndefined:s}=this._core["utils"];return!s(e)&&!t(e.groupAttributeOption)}handleGroupAttributesUpdated(e){var{groupID:e,groupAttributeOption:t}=e,{serverMainSequence:t,groupAttributeList:s=[],operation:r}=t,n=(this._core.ssoLog.debug("handleGroupAttributesUpdated",this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];n(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",this._name+`.initGroupAttributesCache. groupID:${e} avChatRoomKey:`+t)}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){var{groupID:s,serverMainSequence:r,groupAttributeList:n,operation:i}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];i!==uc&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:i})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),this._core.ssoLog.debug("refreshGroupAttributesCache",this._name+`.refreshGroupAttributesCache. operation:${i} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;s!==ac?s!==cc?(s===ic&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:n=[]}=e,i={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===n.length)for(let e of t.keys())i[e]=(null==(s=t.get(e))?void 0:s.value)||"";else n.forEach(e=>{t.has(e)&&(i[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return i}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:n}=this._computeValuesChangedData(s);this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+n.length),0===r.length&&0===n.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:n}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],n=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&n.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:n}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},su=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(La)})}dismissGroup(n){return de(this,void 0,void 0,function*(){let{ChatError:t}=this._core["helper"];try{yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(n,this._core);let e=Jc.getLocalGroup(n)["type"];return Jc.deleteLocalGroup(n),Jc.emitGroupListUpdate(),tu.deleteGroupAttributesCache(n),Xc({groupID:n,type:e},{message:n})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"dismissGroup",code:s,message:r})}})}},nu=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return de(this,void 0,void 0,function*(){let{groupID:n,groupCustomFieldFilter:e}=t,i={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...xa],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...ja]}},{ChatError:r}=this._core["helper"];try{let e=yield this.getGroupProfileAdvance(i),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!Jc.hasLocalGroup(n)&&Vc(t[0].type)?new zc(t[0]):(Jc.updateLocalGroup(t),Jc.getLocalGroup(n))).isSupportTopic||Jc.updateConversationGroupProfile(n),Xc({group:r},{message:"groupID:"+n})}catch(e){let{code:t,message:s}=e;throw new r({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(a){return de(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),r=e.filter(e=>t({groupID:e})),n=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),i=[],o=[];return n.forEach(e=>{i.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:i,failureGroupList:o}})}_getGroupProfileAdvance(e){return de(this,void 0,void 0,function*(){let{ssoLog:i,utils:{isUndefined:o}}=this._core,{isCommunityProfile:t=!1}=e,a=le(e,["isCommunityProfile"]);if(0===a.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(a,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),r=s.filter(e=>o(e.errorCode)||0===e.errorCode),n=s.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return i.debug("_getGroupProfileAdvance",this._name+"._getGroupProfileAdvance ok, groupID:"+a.groupIDList.join(",")),{successGroupList:r,failureGroupList:n}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:n,ApplyJoinOption:i,CreateTime:o,FaceUrl:a,GroupId:l,InfoSeq:u,Introduction:c,InviteJoinOption:d,LastInfoTime:h,LastMsgTime:g,MaxMemberNum:p,MemberNum:_,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:I,Owner_Account:E,ShutUpAllMember:S,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:A,ErrorInfo:O}=s[e],n=jc(n),y=this._convertMembers(y);r.push({groupCustomField:n,joinOption:i,createTime:o,avatar:a,groupID:l,infoSequence:u,introduction:c,inviteOption:d,lastInfoTime:h,lastMsgTime:g,maxMemberCount:p,memberCount:_,muteAllMembers:m,name:v,nextMessageSeq:f,notification:I,ownerID:E,shutUpAllMember:S,muteUntil:C,type:M,members:y,errorCode:A,errorInfo:O})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:i,Member_Account:o,MsgFlag:a,MsgSeq:l,NameCard:u,Role:c}=s[e],n=jc(n);r.push({memberCustomField:n,joinTime:i,userID:o,messageRemindType:a,sequence:l,nameCard:u,role:c})}return r}},ou=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){var{groupID:r,counterList:n=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<i&&i<t||(n.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:i,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:t,avChatRoomKey:e})}}setGroupCounters(t,n){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(n).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},iu=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(La)})}joinGroup(s){return de(this,void 0,void 0,function*(){let r=s["groupID"],{helper:{ChatError:n},OuterConstant:e,ssoLog:t}=this._core;try{if(Jc.hasLocalGroup(r))try{return yield nu.getGroupProfile({groupID:r}),Xc({status:e.JOIN_STATUS_ALREADY_IN_GROUP,group:Jc.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:`+e.JOIN_STATUS_ALREADY_IN_GROUP})}catch(n){t.warn("joinGroup",this._name+`.joinGroup ${r} was unjoined, start to join!`),Jc.deleteLocalGroup(r)}return yield this._applyJoinGroup(s)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n({functionName:"joinGroup",code:t,message:s,moreMessage:"groupID:"+r})}})}_applyJoinGroup(h){return de(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t,ssoLog:s}=this._core,r=h["groupID"],n=Object.assign({},h),t=t.checkBusinessCapabilityBits(Pa),n=(t&&(n.historyMessageFlag=1),yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(n,this._core)),{Type:n,JoinedStatus:i,LongPollingKey:o,StartSeq:a,HugeGroupFlag:l,AVChatRoomKey:u,RspMsgList:c=[]}=n||{},t=`groupID:${r} joinedStatus:${i} longPollingKey:${o} startSeq:${a} avChatRoomFlag:${l} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+c.length;s.debug("_applyJoinGroup",this._name+"._applyJoinGroup ok, "+t);let d=new zc({groupID:r,type:n});if(i===e.JOIN_STATUS_WAIT_APPROVAL)return Xc({status:e.JOIN_STATUS_WAIT_APPROVAL,group:d});if(i!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:Lc});try{d=(yield nu.getGroupProfile({groupID:r})).data.group}catch(e){s.warn("_applyJoinGroup",this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${r}, errorCode:`+(null==e?void 0:e.code))}return this._handleJoinResult({group:d,avChatRoomFlag:l,longPollingKey:o,startSequence:a,avChatRoomKey:u,historyMessageList:c})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(tu.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),ou.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),Xc(e)):(Jc.updateLocalGroup([t]),Jc.emitGroupListUpdate(),Xc({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t},{message:"groupID:"+t.groupID}))}},ru=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(La)})}quitGroup(n){return de(this,void 0,void 0,function*(){if(!Jc.hasLocalGroup(n))throw new this._core.helper.ChatError({code:Nc});let{ChatError:t}=this._core["helper"];try{yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(n,this._core);let e=Jc.getLocalGroup(n)["type"];return Jc.deleteLocalGroup(n),Jc.emitGroupListUpdate(),tu.deleteGroupAttributesCache(n),Xc({groupID:n,type:e},{message:"groupID:"+n})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"quitGroup",code:s,message:r,moreMessage:"groupID:"+n})}})}},au=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return de(this,void 0,void 0,function*(){try{var t=yield function(t,s){return de(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...Va]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:e=[],ApplyJoinOption:r,CreateTime:n,FaceUrl:i,Introduction:o,InviteJoinOption:a,MaxMemberNum:l,MemberNum:u,Name:c,Owner_Account:d,Type:h,ErrorCode:g,ErrorInfo:p}=s[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:p});var _=jc(e),m=new zc({groupID:v,name:c,avatar:i,introduction:o,joinOption:r,inviteOption:a,maxMemberCount:l,memberCount:u,type:h,ownerID:d,createTime:n,groupCustomField:_});return Xc({group:m})}catch(e){var{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:t,message:s})}})}},cu=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(o){return de(this,void 0,void 0,function*(){let r=o["groupID"],{utils:{isUndefined:t},ssoLog:s,helper:n}=this._core,i=Jc.getLocalGroup(r);if(i){let e=i["type"];this._canIUseJoinOption(e)||t(o.joinOption)||(s.warn("updateGroupProfile",this._name+`.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),o.joinOption=void 0)}t(o.muteAllMembers)||(o.muteAllMembers=!0===o.muteAllMembers?"On":"Off");try{return yield function(u,c){return de(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:n,muteAllMembers:i,joinOption:o,inviteOption:a,groupCustomField:l}=u,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:n,ShutUpAllMember:i,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:l?Kc(l):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(o,this._core),i?(i.updateGroup(o),Jc.emitGroupListUpdate()):i=new zc(o),Xc({group:i},{message:"groupID:"+r})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n.ChatError({code:t,message:s,moreMessage:"groupID:"+r})}})}_canIUseJoinOption(e){return xc(e)||this._core.common.isCommunity({type:e})}},uu=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(o){return de(this,void 0,void 0,function*(){var t="changeGroupOwner",{groupID:e,newOwnerID:s}=o,e=Jc.getLocalGroup(e),{helper:r,OuterConstant:n,common:{getCurrentUserID:i}}=this._core;if((null==e?void 0:e.type)===n.GRP_AVCHATROOM)throw new r.ChatError({functionName:t,code:Dc});if(s===i())throw new r.ChatError({functionName:t,code:bc});try{return yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(o,this._core),e.ownerID=s,Jc.emitGroupListUpdate(),Xc({group:e})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},lu=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(La)})}getGroupOnlineMemberCount(i){return de(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount";if(!Jc.hasLocalGroup(i))return Xc({memberCount:0});let r=Date.now();if(this._onlineMemberCountMap.has(i)){let e=this._onlineMemberCountMap.get(i),{lastReqTime:t=0,memberCount:s=0}=e||{};if(r-t<=6e4)return Xc({memberCount:s})}try{let e=yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(i,this._core),{OnlineMemberNum:t=0}=e||{};this._onlineMemberCountMap.set(i,{lastReqTime:Date.now(),memberCount:t});var n=`${this._name}.${s} ok. groupID:${i} memberCount:`+t;return Xc({memberCount:t},{message:n})}catch(e){throw new this._core.helper.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},du=new class{init(e,t){e.ssoLog.debug("GroupAction.init"),Zc.init(e),eu.init(e),su.init(e,t),iu.init(e,t),ru.init(e,t),au.init(e),nu.init(e),cu.init(e),uu.init(e),lu.init(e,t)}dismissGroup(e){return su.dismissGroup(e)}joinGroup(e){return iu.joinGroup(e)}quitGroup(e){return ru.quitGroup(e)}getGroupOnlineMemberCount(e){return lu.getGroupOnlineMemberCount(e)}},hu=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return de(this,void 0,void 0,function*(){var t="getGroupApplicationList";try{var e=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]),s=(this._core.ssoLog.debug("getGroupApplicationList",this._name+`.${t} ok.`),this._handleGroupApplicationResult([...e[0],...e[1]]));return Xc({applicationList:s})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_getGroupApplicationList(i){return de(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=i||{},r=this._core["common"];let n;try{n=yield function(n,i){return de(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;n={}}var{NextStartTime:e=0,PendencyList:t=[]}=n||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},i),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=le(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:n,From_Account:i,GroupId:o,GroupName:a,PendencyType:l,To_Account:u}=e;return{handled:e,messageKey:t,applicant:i,applicantNick:n,groupID:o,groupName:a,authentication:r,applicationType:l,userID:u,note:s}}},gu=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return de(this,void 0,void 0,function*(){var t=e["application"],s=this._handleParams(e);try{(null==t?void 0:t.applicationType)===Xa?yield function(o,a){return de(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:n,invitee:i}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:n,Invited_Account:i}})})}(s,this._core):yield function(o,a){return de(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:n,messageKey:i}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:n,MsgKey:i}})})}(s,this._core);let e=Jc.getLocalGroup(s.groupID);return Xc({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{handleAction:e,handleMessage:t,message:s,application:r}=e;let n,i,o,a,l;if(s){let e=(s||{})["payload"];n=e.operatorID,i=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else n=(null==r?void 0:r.applicant)||"",i=(null==r?void 0:r.groupID)||"",o=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return(null==r?void 0:r.applicationType)===Xa&&(l=r.userID),{handleAction:e,handleMessage:t,applicant:n,invitee:l,groupID:i,authentication:o,messageKey:a}}},pu=new class{init(e){e.ssoLog.debug("GroupApplication.init"),hu.init(e),gu.init(e)}};let _u=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){var{utils:{isUndefined:t},common:{deepMerge:s}}=Na["core"],t=(t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus),[null,void 0,"",0,NaN]);e.memberCustomField&&Bc(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function mu(a,l){return de(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:n,memberCustomField:i}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:n,AppMemberDefinedData:o=i?Kc(i):o};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var vu=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(La)})}getGroupMemberList(r){return de(this,void 0,void 0,function*(){let u="getGroupMemberList",{groupID:c,offset:d=0,count:e=100,role:t="",filter:s=""}=r,h=Jc.getLocalGroup(c),g=100<e?100:e,p={groupID:c,offset:d,limit:g,memberRoleFilter:Za.includes(t)?[t]:void 0,memberInfoFilter:ec};try{let e=yield function(i,o){return de(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:r,memberInfoFilter:n}=i;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:r,MemberInfoFilter:n}})})}(p,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{},n=`${this._name}.${u} ok, totalMemberCount:${s} next:`+r,{utils:{isArray:i,isEmpty:o},common:{isCommunity:a}}=this._core;if(h&&(h.memberCount=s),!i(t)||0===t.length)return Xc({memberList:[],offset:0},{message:n});let l=d+g;a({groupID:c})&&(l=o(r)?0:r),t.length<g&&(l=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),m=this._generateGroupMember(_);return Xc({memberList:m,offset:l},{message:n})}catch(e){throw new this._core.helper.ChatError({functionName:u,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:i,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u,NameCard:c}=s[e],n=jc(n);r.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:n,nameCard:c})}return r}_patchAvatarAndNick(i){return de(this,void 0,void 0,function*(){let e,t=i.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],n=new Map(r.map(e=>[e.userID,e]));return i.forEach(e=>{var t,s;n.has(e.userID)&&({nick:t="",avatar:s=""}=n.get(e.userID),e.nick=t,e.avatar=s)}),i})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var n=new _u(s[e]);r.push(n)}return r}},fu=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(c){return de(this,void 0,void 0,function*(){let t="getGroupMemberProfile",{groupID:r,userIDList:n,memberCustomFieldFilter:i}=c,e=Jc.getLocalGroup(r),{helper:s,utils:{isArray:o},ssoLog:a}=this._core;if(e&&Vc(e.type))throw new s.ChatError({functionName:t,replacement1:t,code:Fc});50<n.length&&(a.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${n.length} exceeds limit 50`),n.splice(50));var l=`userIDList length:${n.length} groupID:`+r;try{let e=yield function(n,i){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:n,memberCustomFieldFilter:i,memberInfoFilter:[...ec]},this._core),t=(e||{})["MemberList"];if(!o(t)||0===t.length)return Xc({memberList:[]});var u=this._convertMemberInfo(t),u=yield this._getMemberAvatarAndNick(u);let s=this._generateGroupMember(u);return Xc({memberList:s},{message:l})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:l})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:i,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u,NameCard:c}=s[e],n=jc(n);r.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:n,nameCard:c})}return r}_getMemberAvatarAndNick(i){return de(this,void 0,void 0,function*(){let e,t=i.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],n=new Map(r.map(e=>[e.userID,e]));return i.forEach(e=>{var t,s;n.has(e.userID)&&({nick:t="",avatar:s=""}=n.get(e.userID),e.nick=t,e.avatar=s)}),i})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var n=new _u(s[e]);r.push(n)}return r}},Iu=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(r){return de(this,void 0,void 0,function*(){let t="addGroupMember",{groupID:o,userIDList:e}=r,a=Jc.getLocalGroup(o),s=this._core["helper"];if(a&&Vc(a.type))throw new s.ChatError({functionName:t,code:Pc});var l=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:o,userIDList:l},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:i}=this._handleResult(t);return Xc({failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:i,group:a},{message:` groupID:${o} successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${n} overLimitUserIDList:`+i})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){let s=[],r=[],n=[],i=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;e===tc?s.push(t):e===sc?r.push(t):e===nc?n.push(t):e===oc&&i.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:i}}},Eu=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(La)})}deleteGroupMember(a){return de(this,void 0,void 0,function*(){var t="deleteGroupMember",{groupID:e,userIDList:s}=a,r=Jc.getLocalGroup(e),{helper:n,utils:{isUndefined:i},ssoLog:o}=this._core;if(i(r))throw new n.ChatError({functionName:t,code:Rc});20<s.length&&(o.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${s.length} exceeds limit 20`),s.splice(20));try{return yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:s},this._core),Xc({group:r,userIDList:s},{message:`groupID:${e} userIDList length:`+s.length})}catch(e){throw new n.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Su=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return de(this,void 0,void 0,function*(){let t=this._core["helper"],{groupID:s,userID:r,muteTime:n}=o,i=` groupID:${s} userID:${r} muteTime:`+n;this._preCheckSettingMuteParams(o);try{yield mu(o,this._core);let e=Jc.getLocalGroup(s),t=new _u({userID:r,muteTime:n});return Xc({group:e,member:t},{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){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:kc})}},Cu=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(a){return de(this,void 0,void 0,function*(){let t="setGroupMemberRole",s=this._core["helper"],{groupID:r,userID:n,role:i}=a,o=`${this._name}.${t} ok, groupID:${r} userID:${n} role:`+i;this._preCheckSettingRoleParams(a);try{yield mu(a,this._core);let e=Jc.getLocalGroup(r),t=new _u({userID:n,role:i});return Xc({group:e,member:t},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:n,OuterConstant:i,common:{isCommunity:o}}=this._core,a=Jc.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==i.GRP_MBR_ROLE_OWNER)throw new n.ChatError({functionName:"setGroupMemberRole",code:Gc});if(t===r.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberRole",code:Uc});a=[...Za];if(o({groupID:e})&&a.push(i.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new n.ChatError({functionName:"setGroupMemberRole",code:wc})}},Mu=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(u){return de(this,void 0,void 0,function*(){let n="setGroupMemberNameCard",{helper:t,common:{getCurrentUserID:i}}=this._core;this._preCheckSettingNameCardParams(u);try{let{groupID:e,userID:t=i(),nameCard:s}=u,r={groupID:e,userID:t,nameCard:s};yield mu(r,this._core);var o=`${this._name}.${n} ok, groupID:${e} userID:${t} nameCard:`+s,a=Jc.getLocalGroup(e),l=new _u({userID:t,nameCard:s});return Xc({group:a,member:l},{message:o})}catch(e){throw new t.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:logText})}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=Jc.getLocalGroup(e);if(Vc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:Fc})}},yu=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(a){return de(this,void 0,void 0,function*(){let t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:e}}=this._core;this._preCheckSettingCustomFiledParams(a);var{groupID:r,userID:n=e(),memberCustomField:i}=a,o=`${this._name}.${t} ok, groupID:${r}userID:${n} memberCustomField:`+JSON.stringify(i);try{let e={groupID:r,userID:n,memberCustomField:i},t=(yield mu(e,this._core),Jc.getLocalGroup(r)),s=new _u({userID:n,memberCustomField:i});return Xc({group:t,member:s},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=Jc.getLocalGroup(e);if(Vc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:Fc})}},Ou=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),vu.init(e,t),fu.init(e),Iu.init(e),Eu.init(e,t),Su.init(e),Cu.init(e),Mu.init(e),yu.init(e)}getGroupMemberList(e){return vu.getGroupMemberList(e)}deleteGroupMember(e){return Eu.deleteGroupMember(e)}},Au=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return de(this,void 0,void 0,function*(){var t="getGroupCounters";try{Hc(t,Ga);var e,s,r,{groupID:n,keyList:i=[]}=l,{avChatRoomKey:o,lastUpdateTime:a}=ou.getLocalGroupCounters(n);return Date.now()-a>=this._getExpireTime()&&(e=yield function(n){return de(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=n,r=Na.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:n,keyList:i,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:r}=e,ou.updateLocalGroupCounters({groupID:n,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:ou.getLocalCounters(n,i)}}}catch(e){Wc(t,e)}})}_getExpireTime(){var{store:e,utils:{isUndefined:t}}=this._core,e=(e.get("cloudConfig")||{})["grp_counter_expire_time"];return t(e)?3e4:Number(e)}},Tu=new class{init(e){e=e.helper;e.registerApi({apiName:"setGroupCounters",context:this}),e.registerApi({apiName:"increaseGroupCounter",context:this}),e.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(wa,e)})}increaseGroupCounter(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(Ua,e)})}decreaseGroupCounter(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(ka,e)})}_handleCounterOperation(a,l){return de(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{Hc(t,Ga);var{groupID:e,key:s,value:r=0}=l,n=ou.getLocalGroupCounters(e)["avChatRoomKey"],i=a===wa?this._convertObjectToList(l.counters):[{Key:s,Value:r}],o=yield this._updateGroupCounters({groupID:e,counterList:i,avChatRoomKey:n,mode:a});return ou.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){Wc(t,e)}})}_updateGroupCounters(i){return de(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=i,n=Na.core["common"];return n.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},Ru=new class{init(e){this._core=e,Au.init(e),Tu.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;e!==Fa&&e!==qa||this._processAndNotifyCounterUpdate(r,t,s),e===$a&&ou.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:n}=this._core;ou.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{n.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){ou.reset()}},Du=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return de(this,void 0,void 0,function*(){let{groupID:n,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a}=tu.getGroupAttributesCache(n),l=tu.convertKeyValueMapToList(i);try{let e=yield function(n,i){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:i[e],sequence:t}});return tu.saveGroupAttributesCacheValuesCopy(n),tu.refreshGroupAttributesCache({groupID:n,serverMainSequence:t,groupAttributeList:r,operation:ic}),tu.emitGroupAttributesUpdated(n),Xc({groupAttributes:i},{message:` groupID:${n} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},bu=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return de(this,void 0,void 0,function*(){let{groupID:n,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a,values:r}=tu.getGroupAttributesCache(n),l=tu.convertKeyValueMapToList(i).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=r.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(n,i){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:i[e],sequence:t}});return tu.saveGroupAttributesCacheValuesCopy(n),tu.refreshGroupAttributesCache({groupID:n,serverMainSequence:t,groupAttributeList:r,operation:rc}),tu.emitGroupAttributesUpdated(n),Xc({groupAttributes:i},{message:` groupID:${n} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Nu=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(l){return de(this,void 0,void 0,function*(){var t="deleteGroupAttributes",{groupID:e,keyList:s=[]}=l;try{var{resultList:r,serverMainSequence:n,operation:i,groupAttributeList:o}=(0===s.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,s))||{},a=this._name+`.${t} ok. groupID:${e} operation: `+i;return tu.saveGroupAttributesCacheValuesCopy(e),tu.refreshGroupAttributesCache({groupID:e,serverMainSequence:n,groupAttributeList:o,operation:i}),tu.emitGroupAttributesUpdated(e),Xc({keyList:r},{message:a})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_deleteGroupAttributes(o,a){return de(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=tu.getGroupAttributesCache(o),r=[],n=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},n.push({key:e,seq:t}),r.push(e))});var i=((yield function(n,i){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:n,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:i,groupAttributeList:n,operation:cc}})}_clearGroupAttributes(r){return de(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=tu.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:ac}})}},Lu=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(l){return de(this,void 0,void 0,function*(){let r=l["groupID"],{avChatRoomKey:n,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=tu.getGroupAttributesCache(r),{ChatError:i}=this._core["helper"],o=`groupID:${r} localMainSequence:${t} serverMainSequence:${s} keyList:`+l.keyList;if(3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:r,avChatRoomKey:n}),t=tu.getGroupAttributesCacheValues(l),{serverGroupAttributeList:s=[]}=e||{};return Xc({groupAttributes:t},{message:o,moreMessage:"from server, count:"+s.length})}catch(e){throw new i({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}var a=tu.getGroupAttributesCacheValues(l);return Xc({groupAttributes:a},{message:o,moreMessage:"from cache"})})}getGroupAttributesFromServer(n){return de(this,void 0,void 0,function*(){var{utils:{isUndefined:e},ssoLog:t}=this._core,{groupID:s,avChatRoomKey:r}=n,{AttrMainSeq:e=0,GroupAttrAry:r}=(yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:s,avChatRoomKey:r,groupType:e(r)?dc:lc},this._core))||{},t=(t.debug("getGroupAttributesFromServer",this._name+`._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:`+e),r.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return tu.refreshGroupAttributesCache({groupID:s,serverMainSequence:e,groupAttributeList:t,operation:uc}),{serverGroupAttributeList:r}})}},Pu=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),Du.init(e),bu.init(e),Nu.init(e),Lu.init(e),tu.init(e)}isGroupAttributesUpdated(e){return tu.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:n,withChangedAttributeInfo:i}=r,o=tu.getGroupAttributesCache(t)["localMainSequence"],a=n-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:`+a),0!=a)if(tu.saveGroupAttributesCacheValuesCopy(t),1!==i||1!=a){if(tu.hasGroupAttributesCache(t)){let e=tu.getGroupAttributesCache(t)["avChatRoomKey"];Lu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{tu.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else tu.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){tu.reset()}};function Gu(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:n,MsgPriority:i,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,TinyId:u,ToGroupId:c,GroupInfo:d,MsgBody:h}=e,g=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:n,From_Account:i,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:n,from:i,to:o}}();return{clientSequence:s,from:r,clientTime:n,priority:i,random:o,sequence:a,time:l,tinyID:u,to:c,groupProfile:g,elements:("tips"===t?wu:ku)(h)}}function wu(r){let t={};return Object.keys(r).forEach(s=>{var e;switch(s){case"MemberNum":t.memberCount=r[s];break;case"OpType":t.operationType=r[s];break;case"Operator_Account":t.operatorID=r[s];break;case"List_Account":t.userIDList=r[s];break;case"MsgMemberExtraInfo":t.memberInfoList=null==(e=r[s])?void 0:e.map(e=>Uu(e));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=Uu(r[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(o){let e={};return Object.keys(o).forEach(i=>{switch(i){case"GroupIntroduction":e.introduction=o[i];break;case"GroupName":e.groupName=o[i];break;case"GroupFaceUrl":e.avatar=o[i];break;case"GroupNotification":e.notification=o[i];break;case"ApplyJoinOption":e.joinOption=o[i];break;case"InviteJoinOption":e.inviteOption=o[i];break;case"ShutupAll":e.muteAllMembers=o[i];break;case"Owner_Account":e.ownerID=o[i];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:n}=o[i];return{changedKeyList:e,groupAttributeList:n.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":t.msgMemberInfo=null==(e=r[s])?void 0:e.map(e=>{var{ShutupTime:e,User_Account:t}=e;return{muteTime:e,userID:t}});break;case"OnlineMemberInfo":t.onlineMemberInfo=function(){var{ExpireTime:e,OnlineMemberNum:t}=r[s];return{expireTime:e,onlineMemberNum:t}}();break;case"GroupCounterInfo":t.groupCounterInfo=r[s].map(e=>{var{GroupCounterSeq:e,GroupCounter:t,Type:s}=e;return{type:s,groupCounterSeq:e,counterList:t}})}}),t}function Uu(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function ku(t){let s={};return Object.keys(t).forEach(e=>{switch(e){case"MsgKey":s.messageKey=t[e];break;case"Operator_Account":s.operatorID=t[e];break;case"ReportType":s.operationType=t[e];break;case"Authentication":s.authentication=t[e];break;case"MsgFlag":s.messageRemindType=t[e];break;case"UserDefinedField":s.userDefinedField=t[e];break;case"RemarkInfo":s.remarkInfo=t[e];break;case"BanDuration":s.duration=t[e];break;case"MuteTime":s.muteTime=t[e]}}),s}class Fu{constructor(e){this.type=Na.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=wu(e);return new Fu(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"groupProfile":this._initGroupProfile(t[e]);break;case"operatorInfo":this._initOperatorInfo(t[e]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(t[e]);break;case"newGroupProfile":this._initNewGroupProfile(t[e]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[e]=t[e]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];mc[r]&&(this.content.groupProfile[r]=t[r])}}_initOperatorInfo(t){this.content.operatorInfo={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];this.content.operatorInfo[r]=t[r]}}_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(t){this.content.newGroupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];"muteAllMembers"!==r?this.content.newGroupProfile[r]=t[r]:this.content.newGroupProfile.muteAllMembers=1===t.muteAllMembers}}}var $u=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:n}=e;null!=e&&e.registerElementClass(n.MSG_GRP_TIP,Fu),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,r.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this)}onNewGroupTips(e){let t=(e||{})["data"],{messageList:s,conversationUpdateFieldList:r}=this._handleGroupTips(t),{notificationCenter:n,OuterEvent:i,appStore:{conversationStore:o}}=this._core;return null!=r&&r.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:r=0}=o.getConversation(e)||{};o.updateConversation(e,{lastMessage:t,unreadCount:s+r})}),0<s.length&&(n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:s}),this._handleGroupTipMessage(s)),{conversationUpdateFieldList:r}}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:n}=e,i=new Map,t=[],o=[];for(let t=0,e=n.length;t<e;t++){let e=Gu(n[t],"tips");if(r===gc){if(Pu.isGroupAttributesUpdated(e)){Pu.handleGroupAttributesUpdated(e);continue}if(Ru.isGroupCounterUpdated(e)){Ru.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(Jc.hasLocalGroup(a)){a=this._assembleMessage(e);if(r===gc&&(a._onlineOnlyFlag=!0,o.push(a)),r===hc){if(!this._core.message.messageDataHandler.storeConversationMessage(a)&&s)continue;o.push(a)}this._handleConversationOptions(i,a)}}return t.push(...i.values()),{conversationUpdateFieldList:t,messageList:o}}_assembleMessage(e){var{OuterConstant:t,message:{messageFactory:s}}=this._core,t=(e.flow="in",e.conversationType=t.CONV_GROUP,s.createMessage(e)),s=(this._patchNickAndAvatar(e.elements,t),new Fu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:n,memberInfoList:i,operatorInfo:o}=e,a={};if(t(i)?t(o)||(a=o):n!==r.JOINED&&n!==r.KICKED&&n!==r.ADMIN_SET&&n!==r.ADMIN_CANCELED||(a=Object.assign({},i[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:n,conversationType:i}=t;let o;if(e.has(n))o=e.get(n),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=i,o.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:n,unreadCount:e,type:i,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(n,o)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:n}=e.payload,i=r.groupID,o=Jc.getLocalGroup(i);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(i,s);break;case"groupName":o.name=s[e];break;default:o[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(n)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==n.userID||Object.keys(n).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:n[e]}),"role"===e&&this._updateSelfRole(o,n[e])}),Jc.emitGroupListUpdate(),Jc.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=Jc.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;t===pc?r=s.GRP_MBR_ROLE_OWNER:t===_c&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=Jc.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,Jc.emitGroupListUpdate(),Jc.updateConversationGroupProfile(t))}_handleGroupTipsRecover(e){var t=this._core["utils"]["isArray"],e=((null==e?void 0:e.result)||{})["groupTipList"];t(e)&&e.forEach(e=>{e=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1).messageList;this._handleGroupTipMessage(e)})}};class qu{constructor(e){this.type=Na.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=ku(e);return new qu(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"remarkInfo":this.content.handleMessage=t[e];break;case"groupProfile":this._initGroupProfile(t[e]);break;case"memberInfoList":break;default:this.content[e]=t[e]}})}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];vc[r]&&(this.content.groupProfile[r]=t[r])}}}var xu=new class{constructor(){this._name="GroupSystemNotification"}init(e){var{message:{messageFactory:e},OuterConstant:{MSG_GRP_SYS_NOTICE:t}}=this._core=e;null!=e&&e.registerElementClass(t,qu)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:r,OuterEvent:n}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let n={};for(let e=0;e<t.length;e++){var i=Gu(t[e],"system"),o=i["elements"]["operationType"];o!==Mc&&(o=this._assembleMessage(i),this._core.message.messageDataHandler.storeConversationMessage(o))&&(r.push(o),n=this._handleConversationOptions(o,s))}return n.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[n]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new qu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})),e=(s.setElement(t),s.isSystemMessage=!0,1===s.sequence&&1===s.random),t=2===s.sequence&&2===s.random;return(e||t)&&(s.sequence=r(),s.random=r(),s.generateMessageID()),s}_handleConversationOptions(e,t){var s=this._core["OuterConstant"],s={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&s.unreadCount++,s}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{var t=e.payload["operationType"];switch(t){case fc:this._handleGroupJoinResult(e);break;case Ic:this._handleMemberKicked(e);break;case Ec:this._handleGroupDismissed(e);break;case Sc:this._handleGroupInvitedResult(e);break;case Cc:this._handleGroupQuitResult(e);break;case yc:this._handleMessageRemindTypeSynced(e);break;case Oc:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=Jc.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${t} type:${s} hasLocalGroup:`+r),r||Vc(s)||(Jc.updateLocalGroup([Object.assign({},e)]),Jc.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];Jc.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];Jc.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=Jc.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${e} hasLocalGroup:`+t),t||nu.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];Jc.updateLocalGroup([Object.assign({},e)]),Jc.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=Jc.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${e} type:${t} hasLocalGroup:`+s),s&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleMessageRemindTypeSynced(e){var{groupProfile:{groupID:e},messageRemindType:t}=e.payload;this._updateConversationProfile(e,{messageRemindType:t})}_handleAVChatRoomMemberBanned(e){var{groupID:e,type:t}=e.payload["groupProfile"];this._deleteLocalGroup(e,t)}_deleteLocalGroup(s,e){if(Vc(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}Jc.deleteLocalGroup(s),Jc.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},Vu=new class{init(e){(this._core=e).ssoLog.debug("GroupNotificationHandler.init"),$u.init(e),xu.init(e);var{notificationCenter:e,InnerEvent:t}=e,s=e["InnerEventSubType"];e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){xu.onNewGroupSystemNotification(e)}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core,s=e["InnerEventSubType"];e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};let Bu={required:!0,rules:["string"],allowEmpty:!1},ju={required:!0,rules:["number"],allowEmpty:!1},Ku={required:!0,rules:["array"],allowEmpty:!1},Hu={required:!0,rules:["object"],allowEmpty:!1},Wu={createGroup:{name:Bu,type:Bu},dismissGroup:[Object.assign({key:"groupID"},Bu)],joinGroup:{groupID:Bu,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},Bu)],searchGroupByID:[Object.assign({key:"groupID"},Bu)],getGroupProfile:{groupID:Bu,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:Bu,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:Bu,newOwnerID:Bu},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},Bu)],handleGroupApplication:{handleAction:Bu},getGroupMemberList:{groupID:Bu},getGroupMemberProfile:{groupID:Bu,userIDList:Ku,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:Bu,userIDList:Ku},deleteGroupMember:{groupID:Bu,userIDList:Ku},setGroupMemberMuteTime:{groupID:Bu,userID:Bu,muteTime:Object.assign(Object.assign({},ju),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:Bu,userID:Bu,role:Bu},setGroupMemberNameCard:{groupID:Bu,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:Bu},setGroupMemberCustomField:{groupID:Bu,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Ku},markGroupMemberList:{groupID:Bu,markType:Object.assign(Object.assign({},ju),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Ku},initGroupAttributes:{groupID:Bu,groupAttributes:Hu},setGroupAttributes:{groupID:Bu,groupAttributes:Hu},deleteGroupAttributes:{groupID:Bu,keyList:Object.assign(Object.assign({},Ku),{allowEmpty:!0})},getGroupAttributes:{groupID:Bu,keyList:Object.assign(Object.assign({},Ku),{allowEmpty:!0})},getGroupCounters:{groupID:Bu,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:Bu,counters:Hu},increaseGroupCounter:{groupID:Bu,key:Bu,value:ju},decreaseGroupCounter:{groupID:Bu,key:Bu,value:ju}},Yu={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=Jc,this.groupAction=du,this.groupAttribute=Pu,this.groupMember=Ou,this.name="Group"}install(e,t=[]){this._core=e,Na.init(e),Jc.init(e),du.init(e,this),Ou.init(e,this),pu.init(e),Ru.init(e),Pu.init(e),Vu.init(e),e.helper.registerValidateConfig({auth:Yu,params:Wu}),this._installSubPlugins(t);var{notificationCenter:t,InnerEvent:e}=e;t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){var{isArray:t}=this._core["utils"];e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){Jc.reset(),Pu.reset(),Ru.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Ju=new class{init(e){this.core=e}},Qu="AV_MBR_LIST",Xu="AV_BAN_MBR",Zu={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},el={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},tl=60,sl=2603,nl=2686,ol=2688,il=3122;class rl{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:n,onFail:i}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=n,this._onFail=i}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getCurrentPollingInterval(this._groupID))}isRunning(){return this._isRunning}_request(){return de(this,void 0,void 0,function*(){try{var e=yield function(n,i){return de(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getCurrentPollingInterval(this._groupID));this._runNextPolling(t)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(-1<this._timeoutID&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(this._name+".stop timerID:"+this._timeoutID),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class al{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){let e=(null==(t=this._map.entries().next().value)?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()}}let cl=e=>e===Zu.GROUP_TIPS_HAS_NO_ROAMING||e===Zu.GROUP_TIPS_HAS_ROAMING,ul=e=>e===Zu.GROUP_SYSTEM_MESSAGE;function ll(g){var e,t,s,r,n,i,o,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:n,GId:i,MS:o,CCD:a,F_Account:l,IsSys:u,GInf:c,MsgBody:d}=g,h=le(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:n,ToGroupId:i,MsgSeq:o,CloudCustomData:a,From_Account:l,IsSystemMsg:u,GroupInfo:dl(c),MsgBody:hl(d)},h)}(),l=a,u=l["Event"];if((cl(u)||ul(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===Zu.BROADCAST_MESSAGE||u===Zu.NORMAL_MESSAGE){var c=l;let e=Ju["core"]["OuterConstant"];c.CloudCustomData=c.CloudCustomData||"",c.MsgBody=c.MsgBody.map(t=>{if(t.MsgType===e.MSG_CUSTOM){let{content:e={}}=t;t.content=Object.assign({Data:"",Desc:"",Ext:""},e)}return t})}return cl(u)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:n,OpType:i}=(c=l).MsgBody||{},"number"==typeof e||1!==i&&2!==i||(c.MsgBody.GroupJoinType=2===i?0:1),s||(c.MsgBody.MsgMemberExtraInfo=null==n?void 0:n.map(e=>({UserId:e}))),1!==i||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),ul(u)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:n}=(o=l).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:n,ImageUrl:"",NickName:""},e),o.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*o.MsgTimeStamp},o.MsgBody),o.MsgBody=Object.keys(o.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:o.MsgBody[t]}),{})),a}function dl(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:n,F_Ll:i}=e,e=le(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),n&&(t.From_AccountNick=n),i&&(t.From_AccountLevel=i),t}function hl(e){let t=e;var s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:n,UDF:i,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:l}=e,e=le(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:n,UserDefinedField:i},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=le(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=null==l?void 0:l.map(e=>{var{Img:t,NN:s}=e,e=le(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},e)})),a&&(t.OnlineMemberInfo=function(){var{ET:e,Num:t}=a;return{ExpireTime:e,OnlineMemberNum:t}}()),t});return Array.isArray(e)?s:s[0]}var gl=new class{constructor(){this._name="MessageParser",this._sequenceList=new al(200),this._messageIDList=new al(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(n,e,i=!1){this._sortServerMessageList({groupID:n,serverMessageList:e,isHistoryMessage:i});var o=this._handleMessageList(n,e);if(0!==o.length){if(!i){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=Ju["core"];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}})(o[o.length-1]);e.updateConversation(""+t+n,{lastMessage:s})}this._checkMessageStacked(o);let e=o.filter(e=>!0===e.isModified),t=o.filter(e=>!1===e.isModified),{MESSAGE_RECEIVED:s,MESSAGE_MODIFIED:r}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:r,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let r=[];r=this._avChatRoomHandler.isPollingSimplifiedMessage()&&!s?(t.sort((e,t)=>e.MS-t.MS),t.map(e=>e.MS)):(t.sort((e,t)=>e.MsgSeq-t.MsgSeq),t.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${e} count:${r.length} sequenceList:`+r),r.length=0}_handleMessageList(s,r){var n,i,{messageDataHandler:o,messageHelper:a}=this._core["message"],l=this._avChatRoomHandler.isPollingSimplifiedMessage(),u=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(l&&(e=ll(e)),ul(e.Event)&&Object.values(el).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),n=a.parseServerGroupMessage(e),(i=this._createMessage(n)).level=e.GroupInfo.From_AccountLevel,cl(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(n)?this._avChatRoomHandler.handleGroupAttributesUpdated(n):null===this._filterDuplicateMessage(i)||o.isMessageSentByCurrentInstance(i)||(1===n.isModified&&(i.isModified=!0),cl(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(i)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];cl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),ul(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(Zu).includes(t)?t===Zu.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===Zu.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===Zu.MESSAGE_REACTION?null:e:(console.warn(this._name+".onMessageReceived unknown event:"+t),null)}_createMessage(e){var{message:{messageFactory:t},OuterConstant:s}=this._core;let r=s.CONV_GROUP;e.event===Zu.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:i,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:o,Reason:a=""}}=e,l=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+n.CONV_GROUP+i,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:r};l.push(e)}),0!==l.length&&this._emitEvent({name:t,data:l})}_onLiveCustomData(e){var t=this._core["OuterEvent"]["ROOM_CUSTOM_DATA_RECEIVED"],{ToGroupId:e,MsgSeq:s,MsgTimeStamp:r,MsgBody:n}=e,n=(null==n?void 0:n.Content)||(null==n?void 0:n.MsgContent)||"";this._emitEvent({name:t,data:n}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+n)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let 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(s){var{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),i=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];n&&(e=ll(e));var a=r.parseServerGroupMessage(e);Object.values(Zu).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(i.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<i.length&&this._emitEvent({name:e,data:i})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:n=tl}=r,i=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:i,memberCount:r,expireTime:n}:(e.latestUpdateTime=i,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let pl=e=>{var{store:t}=Ju["core"];return(t.get("cloudConfig")||{})[e]},_l=e=>{var{utils:{isUndefined:t}}=Ju["core"];return!t(e)},ml=()=>{var e=pl("polling_interval");return _l(e)?parseInt(e,10):300},vl=()=>{var e=pl("polling_simplified_msg");return _l(e)?parseInt(e,10):0};var fl=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,gl.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:r,GroupInfo:{GroupId:n,GroupType:i}}=s[e],r=Object.values(el).includes(r.ReportType);i===t&&r&&this.reset(n)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||ml()}isPollingSimplifiedMessage(){return 0!==vl()}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}updateLocalOnlineMemberCount(e,t){this._onlineMemberCountMap.set(e,t)}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){let{GRP_LIVE:t}=this._core["OuterConstant"],e=[];return e=0<this._joinedGroupMap.size?[...this._joinedGroupMap.values()].filter(e=>e.type===t):e}handleJoinGroupResult(l){return de(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:n,group:i,historyMessageList:o=[]}=l,a=i["groupID"];return yield this._preCheck(i),this._joinedGroupMap.set(a,i),this._parentPlugin.groupDataHandler.updateLocalGroup([i]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<o.length&&gl.onMessageReceived(a,o,!0),e(n)?{code:0,data:{status:r.JOIN_STATUS_SUCCESS,group:i}}:{code:0,data:this.startMessageLongPolling(l)}})}_preCheck(i){return de(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:r},ssoLog:n}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=pl("polling_count_limit"),_l(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:ol,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&i.type!==e.GRP_LIVE){var[t,s]=this._joinedGroupMap.entries().next().value;if(s.selfInfo.role===e.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(t);else try{yield r(t)}catch(e){n.debug("quitGroup",this._name+`._preCheck quitGroup failed, groupID:${t} info:`,e)}this.reset(t)}})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,n=r["groupID"];return this._pollingRequestInfoMap.set(n,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(n,ml()),this._startPolling(n),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:r}}_startPolling(t){if(this._core.ssoLog.debug("_startPolling",this._name+"._startPolling groupID:"+t),this._pollingInstanceMap.has(t)){let e=this._pollingInstanceMap.get(t);void((null==e?void 0:e.isRunning())||null==e||e.start())}else{let e=new rl({core:this._core,manager:this,groupID:t,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});e.start(),this._pollingInstanceMap.set(t,e)}}_handleRequestParams(e){var{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:vl()}:{longPollingKey:t,startSequence:s,simplifiedMessage:vl()}}_handleSuccess(s,e){var r=e["ErrorCode"];if(0!==r){let{longPollingKey:e,startSequence:t}=this._pollingRequestInfoMap.get(s)||{};void console.warn(`${this._name}._handleSuccess groupID:${s} key:${e} startSeq:${t} errorCode:`+r)}else this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,e)}_handleResponseData(t,e){var{Key:e,NextSeq:s,NextBroadcastSeq:r,RspMsgList:n=[],RspBroadcastMsgList:i=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<n.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,ml())),gl.onMessageReceived(t,n);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=pl("polling_no_msg_count"),_l(s)?parseInt(s,10):20)){let e=ml()+(r=pl("polling_interval_plus"),_l(r)?parseInt(r,10):2e3);this._pollingIntervalMap.set(t,e)}}0<i.length&&gl.onBroadcastMessageReceived(i)}_handleFailure(e,t){var{ssoLog:s,utils:{safeStringify:r}}=this._core;s.warn("polling",this._name+`._handleFailure groupID:${e} error: `+r(t))}_joinedAVChatRoomCount(){let t=this._core["OuterConstant"],e=[];return(e=0<this._joinedGroupMap.size?this.getJoinedGroups().filter(e=>e.type===t.GRP_AVCHATROOM):e).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){gl.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,r,n;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:r,count:n}=(()=>{var e=pl("av_members_freq_limit");if(_l(e)){var{interval:e,count:t}=JSON.parse(e);if(0<t&&0<e)return{interval:e,count:t}}return{interval:30,count:4}})(),Date.now()-t>1e3*r)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),n<s)}_stopPolling(e){var t,s;if(this._core.ssoLog.debug("_stopPolling",this._name+"._stopPolling groupID:"+e),e)({appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:t}}=this._core),s.deleteConversation(""+t+e),null!=(s=this._pollingInstanceMap.get(e))&&s.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),this._membersReqInfoMap.delete(e);else{for(let 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(){var o=this._joinedGroupMap.size;if(1<o){let{common:e,OuterConstant:s,ssoLog:t}=this._core,r=e.isUnlimitedAVChatRoom()?1:0,n=[],i=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?i:n).push(e)}),t.info("longPollingCount",String(o),{moreMessage:`av:${n.join(",")} live:${i.join(",")} code: `+r,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,gl.reset()}},Il=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(n){return de(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(n),{status:s,group:{type:r}}=t["data"];return r!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:fl.handleJoinGroupResult(t.data)})}},El=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}quitGroup(r){return de(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&fl.reset(r),t})}},Sl=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}dismissGroup(r){return de(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&fl.reset(r),t})}},Cl=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(n){return de(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=n["groupID"],e=e.getGroup(r);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits(Qu)){if(fl.isOverFrequencyLimit(r))throw{code:2996,message:"Over frequency limit: get_members-"+r};return this._getGroupMemberList(n)}return this._parentPlugin.groupMember.getGroupMemberList(n)})}_getGroupMemberList(i){return de(this,void 0,void 0,function*(){let n="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(i,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${n} ok, groupID:${i.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:n=0,Marks:i=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:n,marks:i,isOnline:!0}})}},Ml=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupOnlineMemberCount(s){return de(this,void 0,void 0,function*(){var{appStore:{groupStore:e},OuterConstant:t}=this._core,e=e.getGroup(s);return e?e.type===t.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(r){return de(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=fl.getLocalOnlineMemberCount(r);if(e(s)||this._isExpired(r)){let{memberCount:e=0}=yield this._getOnlineMemberCountFromServer(r);return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${e} from server.`),{code:0,data:{memberCount:e}}}return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${s.memberCount} from local.`),{code:0,data:{memberCount:s.memberCount}}})}_isExpired(e){var e=fl.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(i){return de(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(i,this._core),{OnlineMemberNum:t=0,ExpireTime:s=tl}=e||{},r=Date.now(),n={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return fl.updateLocalOnlineMemberCount(i,n),{memberCount:t}}catch(e){var 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}})}},yl=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}deleteGroupMember(o){return de(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:n}=this._core,i=o["groupID"],t=t.getGroup(i);if(s(t))throw new r.ChatError({functionName:e,code:sl});if(t.type!==n.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(r.checkBusinessCapabilityBits(Xu))return this._deleteGroupMember(o);throw new r.ChatError({functionName:e,code:il})})}_deleteGroupMember(a){return de(this,void 0,void 0,function*(){var t="_deleteGroupMember",{appStore:{groupStore:e},helper:s,ssoLog:r}=this._core,{groupID:n,duration:i=0,userIDList:o}=a;if(0===i)throw new s.ChatError({functionName:t,code:nl});try{return yield function(n,i){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(a,this._core),r.debug(t,this._name+`.${t} ok, groupID:`+n),{code:0,data:{group:e.getGroup(n),userIDList:o}}}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ol=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return de(this,void 0,void 0,function*(){var n="markGroupMemberList",{groupID:i,markType:o,enableMark:a,userIDList:l=[]}=e,u=this._generateRequestData(e);try{let e=yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(u,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,l);return{code:0,data:{successUserIDList:s,failureUserIDList:r},successLog:{message:`${this._name}.${n} ok, groupID:${i} markType:${o} enableMark:${a} success:${s.length} fail:`+r.length}}}catch(e){throw new this._core.helper.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:n=[]}=e,i=!0===r?1:2,o=[...n];return 500<o.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:i,memberList:o.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){let s=[],r=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:r).push(t)}),{successUserIDList:s,failureUserIDList:r}}},Al=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),Il.init(e,t),El.init(e,t),Sl.init(e,t),Cl.init(e,t),Ml.init(e,t),yl.init(e,t),Ol.init(e)}},Tl=new class{constructor(){this._name="LiveHandler"}init(e){var{helper:e,ssoLog:t}=this._core=e;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),t.debug("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:r,ssoLog:n}=this._core,{groupID:e,longPollingKey:i,longPollingSequence:o=1}=e;if(s(i))return n.warn("startMessageLongPolling",this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});fl.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=fl.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),n.debug("startMessageLongPolling",this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${i} longPollingSequence:`+o),s={groupID:e,type:r.GRP_LIVE};return fl.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:i,startSequence:o}),fl.startMessageLongPolling({group:s,longPollingKey:i,startSequence:o})}stopMessageLongPolling(e){e=e.groupID;return fl.reset(e),this._core.ssoLog.debug("stopMessageLongPolling",this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(n){return de(this,void 0,void 0,function*(){var t=this._core["ssoLog"],s=n["groupID"];try{var e=yield function(r,n){return de(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(n,this._core),{RspMsgList:r=[]}=e||{};t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages ok, groupID:${s} count:`+r.length),0<r.length&&fl.handleLiveHistoryMessages(s,r)}catch(e){t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages failed, groupID:${s} info:`+e.message)}})}},Rl=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,Ju.init(e),fl.init(e,t),Al.init(e,t),Tl.init(e);var{notificationCenter:t,InnerEvent:e}=e,s=t["InnerEventSubType"];t.subscribeInnerEvent(e.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){fl.onAVChatRoomSystemNotification(e)}_reset(){fl.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core,s=e["InnerEventSubType"];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)}};let Dl=new class{init(e){this.core=e}},bl="message",Nl="user",Ll={OR:"or",AND:"and"},Pl=20,Gl=20,wl=20,Ul={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},kl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Ll.OR,Ll.AND].includes(e)||"keywordListMatchType should be OR or AND"},Fl={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},$l={required:!1,rules:["string"],allowEmpty:!0},ql={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=Dl.core["OuterConstant"];if(!Array.isArray(t))return"groupTypeList should be an array";var s=[e.GRP_PUBLIC,e.GRP_COMMUNITY,e.GRP_WORK,e.GRP_MEETING];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"groupTypeList should be supported group type"}},xl={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=Dl.core["OuterConstant"],s=[e.MSG_TEXT,e.MSG_IMAGE,e.MSG_AUDIO,e.MSG_FILE,e.MSG_VIDEO,e.MSG_LOCATION,e.MSG_CUSTOM,e.MSG_MERGER];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"messageTypeList should be supported message type"}},Vl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Dl.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Bl=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),jl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Dl.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Kl={searchCloudMessages:{keywordList:Ul,keywordListMatchType:kl,cursor:$l,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:xl,conversationID:Vl,timePosition:Bl("timePosition"),timePeriod:Bl("timePeriod")},searchCloudUsers:{keywordList:Ul,keywordListMatchType:kl,cursor:$l,count:Fl,miniBirthday:Bl("miniBirthday"),maxBirthday:Bl("maxBirthday"),gender:jl},searchCloudGroupMembers:{keywordList:Ul,keywordListMatchType:kl,cursor:$l,count:Fl,groupTypeList:ql,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Ul,keywordListMatchType:kl,cursor:$l,count:Fl,groupTypeList:ql}},Hl={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Ql,Wl=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,Dl.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:Hl,params:Kl})}searchCloudMessages(p){return de(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a}=this._core,{conversationID:e,timePeriod:t,timePosition:s}=p,r=le(p,["conversationID","timePeriod","timePosition"]),n=Object.assign({count:100},r);e&&(e.startsWith(o.CONV_C2C)?n.account=e.replace(o.CONV_C2C,""):e.startsWith(o.CONV_GROUP)&&(n.groupID=e.replace(o.CONV_GROUP,""))),this._setTimeRangeParams(n,{timePeriod:t,timePosition:s});var i=yield function(c){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:n,endTime:i,startTime:o,cursor:a,account:l,groupID:u}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:n,EndTime:i,StartTime:o,Cursor:a,PeerAccount:l,GroupID:u};return Dl.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(n);if(!i)return{code:0,data:{}};var{ErrorCode:l,ErrorInfo:u,TotalCount:c,Cursor:d="",ConversationMsgs:h=[]}=i;if(0!==l)throw{errorCode:l,errorInfo:u};var g=`keywordList:${p.keywordList} keywordListMatchType:${p.keywordListMatchType} cursor:${p.cursor} res: totalCount:`+c;return{code:0,data:{searchResultList:h.map(e=>{let{MsgList:t,Count:s,GroupID:n,UserID:r}=e,i=n?""+o.CONV_GROUP+n:""+o.CONV_C2C+r;return this._isSearchingAllConversations(p)&&1<s?{conversationID:i,messageCount:s,messageList:[]}:{conversationID:i,messageCount:s,messageList:t.map(e=>{return a.isEmpty(n)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}),cursor:d,totalCount:c},successLog:{message:g}}}catch(e){var{errorCode:i,errorInfo:l}=e||{};this._handleError({errorCode:i,errorInfo:l,searchType:bl,functionName:"searchCloudMessages"})}})}searchCloudUsers(v){return de(this,void 0,void 0,function*(){var s;try{var{keywordListMatchType:e,count:t=Gl}=v,r=le(v,["keywordListMatchType","count"]),n=Object.assign({count:t,keywordListMatchType:e===Ll.AND?1:0},r),i=(this._setBirthdayRangeParams(n,v),yield function(a){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:n,cursor:i,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,UserBirthStart:r,UserBirthEnd:n,Gender:o};return Dl.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(n));if(!i)return{error:0,data:{}};var{ErrorCode:o,ErrorInfo:a,TotalCount:l,Cursor:u="",Users:c=[]}=i;if(0!==o)throw{errorCode:o,errorInfo:a};var d=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} count:${v.count} res: totalCount:`+l,h=[];for(let e=0,t=c.length;e<t;e++){var g,p,{UserID:_,ProfileItems:m}=c[e];_!==this._core.OuterConstant.USER_NOT_FOUND&&""!==_&&(g=m.map(e=>({tag:e.Tag,value:e.StrValue})),p=null==(s=this._core.user.userProfile)?void 0:s.createProfile(_,g),h.push(p))}return{code:0,data:{searchResultList:h,cursor:u,totalCount:l},successLog:{message:d}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Nl,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(d){return de(this,void 0,void 0,function*(){try{var{count:t=wl,keywordListMatchType:s}=d,r=le(d,["count","keywordListMatchType"]),n=yield function(o){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:n,groupIDList:i}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,GroupType:r,GroupIdList:i};return Dl.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Ll.AND?1:0},r));if(!n)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:o,GroupMembers:a=[],Cursor:u,TotalCount:c}=n;if(0!==i)throw{errorCode:i,errorInfo:o};let e=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+c,l=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:r,GroupMemberUserName:n,GroupMemberUserID:i,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:i,nick:n,nameCard:o,avatar:a};if(l.has(t)){let e=l.get(t);e.memberList.push(s),l.set(t,e)}else l.set(t,{groupInfo:e,memberList:[s]})}),{code:0,data:{searchResultList:[...l.values()],cursor:u,totalCount:c},successLog:{message:e}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Nl,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(c){return de(this,void 0,void 0,function*(){try{var{count:t=Pl,keywordListMatchType:s}=c,e=le(c,["count","keywordListMatchType"]),r=yield function(i){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:n}=i,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,GroupType:r};return Dl.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Ll.AND?1:0},e));if(!r)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:i,Groups:o,Cursor:a,TotalCount:l}=r;if(0!==n)throw{errorCode:n,errorInfo:i};var u=`keywordList:${c.keywordList} keywordListMatchType:${c.keywordListMatchType} cursor:${c.cursor} count:${c.count} res: totalCount:`+l;return{code:0,data:{searchResultList:(null==o?void 0:o.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:r,GroupName:n,GroupOwnerTinyID:i,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:l,GroupAddOption:u,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:n,ownerTinyID:i,ownerID:o,ownerNick:a,type:l,joinOption:u,inviteOption:c}}))||[],cursor:a,totalCount:l},successLog:{message:u}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Nl,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&0<t&&(e.startTime=s&&0<s?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&0<s&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s}){var r=this._core["helper"];let n=e;throw 60020===e?n="SearchUnable":s!==bl&&27003===e?n="SearchParamsError":s!==bl&&60018===e&&(n="SearchOverLimit"),new r.ChatError({code:n,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){var{miniBirthday:t,maxBirthday:s}=t;void 0!==t&&(e.miniBirthday=t,void 0===s)&&(e.maxBirthday=4294967295),void 0!==s&&(e.maxBirthday=s)}};function Yl(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let zl="qualityStat",Jl="im-ssolog-quality-stat",Xl=(!function(e){e[e.ONLINE=8]="ONLINE"}(Ql=Ql||{}),"networkRTT"),Zl="messageE2EDelay",ed="sendMessageC2C",td="sendMessageGroup",sd="sendMessageGroupAV",nd="sendMessageRichMedia",od="cosUpload",id="messageReceivedGroup",rd="messageReceivedGroupAVPush",ad="messageReceivedGroupAVPull",cd={[Xl]:2,[Zl]:3,[ed]:4,[td]:5,[sd]:6,[nd]:7,[id]:8,[rd]:9,[ad]:10,[od]:11},ud=[ed,td,sd,nd,od],ld=[id,rd,ad],dd=[Xl,Zl,ed,td,sd,nd,od,id,rd,ad],hd={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},gd="quality_stat";var pd=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(hd))}init(e){this._core=e,Object.values(ud).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,n=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case n.TOTAL_COUNT:this._handleTotalCount(t);break;case n.SUCCESS_COUNT:this._handleSuccessCount(t);break;case n.FAILED_COUNT:this._handleFailedCount(t,s);break;case n.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,n,i,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:n}=o,r=Yl(s/t*100,2),i=Yl((n=s+n)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:n,percent_platform:i,average_value:o}):null}_handleTotalCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.totalCount++}_handleSuccessCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.successCount++}_handleFailedCount(s,e){var t=null!=(t=null==e?void 0:e.code)?t:null==e?void 0:e.errorCode;if(this._isUserSideError(t)){let e=this._getSendMessageSpecifiedKey(s),t=e&&this._messageStatsMap.get(e);t&&t.failedCountOfUserSide++}}_handleSendCost(e,t){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&(e.costSum+=Date.now()-t,e.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||120001<=e&&e<=13e4||10100<=e&&e<=10200}_getSendMessageSpecifiedKey(s){let{MSG_IMAGE:e,MSG_AUDIO:t,MSG_VIDEO:r,MSG_FILE:n,CONV_C2C:i,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,n].includes(s.type))return nd;if(s.conversationType===i)return ed;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?sd:td}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===od?Math.round(1e3*e.fileSizeSum/e.costSum):Math.round(e.costSum/e.costCount)}_resetStat(e){e=this._messageStatsMap.get(e);e&&(e.totalCount=0,e.successCount=0,e.failedCountOfUserSide=0,e.costSum=0,e.costCount=0,e.fileSizeSum=0)}},_d=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){var{OuterEvent:e,notificationCenter:t}=this._core=e;this._initStatsMap(),t.subscribeOuterEvent(e.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){var t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:r},ssoLog:n}=this._core;s(t)||!this._currentCycleStats.has(t)?n.warn("addMessageSequence",zl+".addMessageSequence invalid key:"+t):({conversationID:s,sequence:n}=e,e=s.replace(r,""),0!==(s=this._lastCycleStats.get(t)).size&&s.has(e)&&n>(r=s.get(e)).minSeq&&n<r.maxSeq?this._insertToLastCycle(n,r):this._addToCurrentCycle(t,e,n))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,n=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(n+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:n,percent_business:Yl(n/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(ld).forEach(e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)})}_onMessageReceived(e){var{data:e=[]}=e;e.forEach(e=>{this.addMessageSequence(e)})}_transferCycleDataOptimized(e){var t=this._currentCycleStats.get(e);if(t){let r=new Map;t.forEach((e,t)=>{var s=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;r.set(t,{sortedSequences:s,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,r),this._currentCycleStats.set(e,new Map)}}_getReceivedMessageSpecifiedKey(s){let{CONV_GROUP:e,GRP_AVCHATROOM:r}=this._core["OuterConstant"];if(s.conversationType===e&&!0!==(null==s?void 0:s._onlineOnlyFlag)){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);return t?(s=t["type"],s===r?ad:id):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var 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,r=e.length-1;for(;s<=r;){var n=Math.floor((s+r)/2);if(e[n]===t)return n;e[n]<t?s=n+1:r=n-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},md=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(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)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],n=[s,r];t.forEach(e=>{!n.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Yl(this._totalDelay/e,1)}_calculatePercentage(e,t){return Yl(e/t*100,2)}},vd=new class{init(e){this.core=e}},fd=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:n,DESTROY:i},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;vd.init(e),pd.init(e),_d.init(e),md.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(n,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){var{store:e,helper:t,utils:{isUndefined:s}}=this._core,e=(e.get("cloudConfig")||{})["q_rpt_interval"],s=s(e)?12e4:Number(e);t.taskScheduler.addTask({id:gd,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...dd.map(e=>{e=this._buildQualityReportItem(e);return e?Object.assign(Object.assign({},e),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){var t=this._core["constants"]["QUALITY_METRICS"],{label:e,data:s}=e;e===t.MESSAGE_SEND_SUCCESS_RATE&&pd.dispatchSendStats(s)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){var{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},e=(e.get("instance")||{})["sdkAppId"],{q_rpt_sdkappid_bl:s=[]}=s;if(!t.isEmpty(s))return s.split(",").map(e=>Number(e)).includes(e)}_isTinyIDInWhitelist(){var{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},e=e.get("login")||{},e=Number(e.tinyID),{q_rpt_tinyid_wl:s=[]}=s;if(!t.isEmpty(s))return s.split(",").includes(e)}_buildQualityReportItem(e){var t=this._getStatResultByKey(e);return null===t?null:(e={quality_type:cd[e],timestamp:Date.now(),network_type:Ql.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case Zl:return md.getStatResult();case ed:case td:case sd:case nd:case od:return pd.getStatResult(e);case id:case rd:case ad:return _d.getStatResult(e);default:return null}}_uploadQualityReports(t){return de(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=vd.core,s="imopenstat.tim_web_report_v2",e=e.generateSSOLogProtocolData({servcmd:s,data:r}),s=e.head.seq+s;t.sendPacket(e,{requestId:s})}(),this._reportIndex++,this._wholePeriod=!1}catch(e){console.warn("doReport failed. error:",e),this._pendingReports=this._pendingReports.concat(t),this._cacheFailedLogs()}})}_cacheFailedLogs(){var e=this._pendingReports,t=zl+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(Jl)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(Jl,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(gd)}_dispose(){var{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:r}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(r,this._dispose,this),this._reset(),md.dispose(),_d.dispose()}};let Id=1,Ed=300;var Sd=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:n}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(n.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return de(this,void 0,void 0,function*(){let n=this._core["OuterConstant"],i=[],o=[];return yield Promise.all(null==e?void 0:e.map(r=>de(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+n.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:o})),i.push(e.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:i,groupTipList:o}})}_recoverHistoryForConversation(e){return de(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:E,serverLastMessageSequence:S,groupTipList:C}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:n,notificationCenter:i,message:o,appStore:a,common:{getMessagePreviewText:l}}=this._core,u=S-E,c=Math.min(20,u),d={},h=yield o.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:I,sequence:E+c,direction:n.Direction.FORWARD,count:c}),{nextReqMessageIDFromServer:g,hasNoMoreHistoryMessage:p,messageList:_,serverGroupTipList:m}=h,v=(e(m)&&C.push(...m),p&&g<0),f=[];if(e(_)&&(_.forEach(e=>{o.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===n.CONV_SYSTEM&&(e.isSystemMessage=!1),o.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:I,localLastMessageSequence:e,serverLastMessageSequence:S,groupTipList:C})}t(d.lastMessage)&&(d.lastMessage.messageForShow=l(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(I,d))}catch(E){this._core.ssoLog.error("_recoverHistoryForConversation","Recovery failed for conversation:"+I,{error:E})}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var n;0<(null==e?void 0:e.length)&&(n=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,n))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&t>=Id&&t<Ed}};let Cd=Rs.STANDARD,Md=[];Cd=Rs.STANDARD,Md=[$n,Fn,Bn,Xn,to,fd,Sd,qi,zr,ba,zu,Rl,Wl,bo];var yd=Object.freeze({__proto__:null,ChatError:Xs,WorkflowManager:ln,buildAndSendPacket:mn,get builtInPlugins(){return Md},checkBusinessCapabilityBits:un,deepMerge:Cn,getCurrentUserID:En,getErrorMessage:Qs,getMessagePreviewText:Mn,isC2CConv:e=>t(e)&&e.slice(0,3)===Is.CONV_C2C,isCommunity:hn,isGroupConv:e=>t(e)&&e.slice(0,5)===Is.CONV_GROUP,isTopic:gn,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=ts.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:dn,registerInterceptor:an,registerValidateConfig:cn,requireAuth:Zs,get sdkEdition(){return Cd},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:i}=As;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:n}=As,{groupID:i,sequence:o}=t,a=!1;return hn({groupID:i})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[n]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[n],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(n)&&(e=[i]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:rn,validateParameters:en});class Od{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Od._instance||(Od._instance=new Od),Od._instance}static setInstance(e){Od._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){var s=[];let r=(s=n(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=-1<r?s.splice(r,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&ss(e.install)?(t.add(e.name),ss(e.getInstalledSubPlugins)?e.install(Nd.getInstance().exposeApiForPlugin(),i):e.install(Nd.getInstance().exposeApiForPlugin()),ss(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):ss(e)?(t.add(e.name),e(Nd.getInstance().exposeApiForPlugin()),ss(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=ts.store.get("login"))?void 0:e.isLoggedIn)}}var Ud,kd,Fd,Vd,Ad=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:n}=s,i=this._conversationMap.get(e);i&&!ve(t)&&(Object.keys(t).forEach(e=>{i[e]=t[e]}),r)&&ts.notificationCenter.emitInnerEvent(cs.CONVERSATION_UPDATED,{needSort:n})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),ts.notificationCenter.emitInnerEvent(cs.CONVERSATION_UPDATED))}},Td=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){let s=this._groupMap.get(e);s&&!ve(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},Rd=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:n,updateUnreadCount:i=!0}=e,o=le(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(r=this._messagesByConversation.get(s))?void 0:r.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(n,{conversationID:s,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];gn(s)?ts.notificationCenter.emitInnerEvent(ms[e],t):ts.notificationCenter.emitInnerEvent(e,t)}},Dd=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)}},bd=Object.freeze({__proto__:null,conversationStore:Ad,groupStore:Td,messageStore:Rd,userStore:Dd});class Nd{static getInstance(){return Nd._instance||(Nd._instance=new Nd),Nd._instance}static setInstance(e){Nd._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ts.notificationCenter.subscribeOuterEvent.bind(ts.notificationCenter),off:ts.notificationCenter.unSubscribeOuterEvent.bind(ts.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Od.getInstance().installExternalPlugin.bind(Od.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){ts.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){ts.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){ts.ssoLog.debug("setLogLevel",e),ts.ssoLog.setLogLevel(e)}setApplicationID(e){ts.store.set("instance",{applicationID:e})}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{common:{timeManager:i},utils:{safeStringify:t}}=ts,{apiName:o,context:s,methodName:a=o,matcher:r}=e;this._apiHandlersMap[o]||(this._apiHandlersMap[o]=[]),this._apiHandlersMap[o].push({context:s,methodName:a,matcher:r}),this._apiMap[o]&&1!==this._apiHandlersMap[o].length||(this._apiMap[o]=(...s)=>{let r=i.getServerTimeMs(),n=0;"login"===o&&(n=4),Gs.includes(o)&&ts.ssoLog.debug(o,o+" start params: "+t(s)),rn(a,s);for(let t of this._apiHandlersMap[o])if(!t.matcher||t.matcher(s))try{let e=t.context[t.methodName].bind(t.context)(...s);return this._isPromiseLike(e)?this._handleAsyncResult(e,o,n,r):(this._reportApiSuccessLog({result:e,apiName:o,eventType:n,startTime:r}),e)}catch(s){throw ts.ssoLog.error(o,`${o} fail ${null==s?void 0:s.message})`,{error:s,costTime:i.getServerTimeMs()-r,eventType:n,method:o}),s}})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return de(this,void 0,void 0,function*(){var e,t;try{null!=(e=ts.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),ts.notificationCenter.emitInnerEvent(cs.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{ts.notificationCenter.emitOuterEvent(rs.SDK_DESTROY,{SDKAppID:null==(t=ts.store.get("instance"))?void 0:t.sdkAppId}),dn.clear(),Od.getInstance().clear(),ln.getInstance().destroy(),ts.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:cs,InnerEventSubType:ts.notificationCenter.InnerEventSubType,OuterEvent:rs,OuterConstant:As,SignalingEvent:us,helper:Object.assign(Object.assign(Object.assign({},ts.utils),ts.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:an,registerValidateConfig:cn,checkBusinessCapabilityBits:un,registerWorkflowStep:ln.getInstance().registerWorkflowStep.bind(ln.getInstance()),ChatError:Xs}),apiMap:this._apiMap},ts),{constants:Object.assign(Object.assign({},ws),ts.constants),common:Object.assign(Object.assign(Object.assign({},yd),ts.common),{workflowManager:ln.getInstance()}),utils:ts.utils,appStore:bd})}callExperimentalAPI(e,t){return ts.ssoLog.debug(`callExperimentalAPI.${e} start params: `+ts.utils.safeStringify(t)),this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new Xs({code:Ts.INVALID_OPERATION}))}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,r){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:r}),e)).catch(e=>{throw ts.ssoLog.error(t,`${t} fail ${null==e?void 0:e.message})`,{error:e,costTime:ts.common.timeManager.getServerTimeMs()-r,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:r,eventType:n}=e;var e=ts.common["timeManager"],{successLog:{message:i,moreMessage:o}={message:"",moreMessage:""}}=t||{},a=e.getServerTimeMs();"login"===s&&(r+=e.getTimeOffsetWithServer()),Gs.includes(s)&&ts.ssoLog.info(s,s+` success ${i} `+o,{costTime:a-r,eventType:n,message:i,moreMessage:o}),null!=t&&t.successLog&&delete t.successLog}}class Ld{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){var{notificationCenter:e,store:t}=ts;t.set("login",{isReady:!1}),Nd.getInstance().registerApi({apiName:"login",context:this}),Nd.getInstance().registerApi({apiName:"logout",context:this}),Nd.getInstance().registerApi({apiName:"getLoginUser",context:this}),Nd.getInstance().registerApi({apiName:"isReady",context:this}),Nd.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),e.subscribeInnerEvent(cs.RECONNECTED,this._reLogin,this),ts.notificationCenter.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}login(l){return de(this,void 0,void 0,function*(){var e;let t=(ts.store.get("instance")||{})["sdkEdition"];try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Xs({functionName:"login",code:Ts.REPEAT_LOGIN});var s=yield this._performLogin(l),r=(this._validateAfterLogin(s),this._handleLoginSuccess(s),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,null==(e=ts.channel.getSocketAdapter())?void 0:e.getId()),{appId:n,href:i}=ts.store.get("instance")||{},{instanceID:o,customStatus:a}=s||{};return{code:0,data:s,successLog:{message:t,moreMessage:`socketID:${r} instanceID:${o} customStatus:${a} href: ${i} appId: `+n}}}catch(e){let t=e["errorCode"],s=(t!==Ts.REPEAT_LOGIN&&(this._latestLoginAt=0),new Xs({functionName:"login",code:t}));throw console.error(s),s}})}_reLogin(){return de(this,void 0,void 0,function*(){var e,t,s,r,n;try{this._isLoginIn()&&(t=yield Js(this._customLoginInfo))&&({instanceID:s,customStatus:r}=t,ts.store.set("login",{statusInstanceId:s}),ln.getInstance().executeWorkflow(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:vs.USER_STATUS_ONLINE}),n=null==(e=ts.channel.getSocketAdapter())?void 0:e.getId(),ts.ssoLog.info("reLogin",`socketId:${n} instanceId:`+s))}catch(e){console.warn(e)}})}logout(){return de(this,arguments,void 0,function*(t=Us.USER_INITIATED){let e=ts["ssoLog"];e.debug("logout","logout start logoutReason: "+t);try{yield this._performLogout(t),e.info("logout","logout success"),ts.ssoLog.uploadSSOLogData()}catch(t){let e=t["errorCode"];throw new Xs({functionName:"logout",code:e})}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?En():""}isReady(){var e;return null==(e=ts.store.get("login"))?void 0:e.isReady}setCustomLoginInfo(e=""){this._customLoginInfo=e}_updateAndEmitSDKReady(){ts.store.set("login",{isReady:!0}),setTimeout(()=>{ts.notificationCenter.emitOuterEvent(rs.SDK_READY,{name:rs.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ts.store.set("login",{isReady:!1}),ts.notificationCenter.emitOuterEvent(rs.SDK_NOT_READY,{name:rs.SDK_NOT_READY})}_validateAfterLogin(e){if(!e)throw new Xs({functionName:"login",message:"login response is empty"});var{tinyID:e,a2Key:t}=e||{};if(!e)throw new Xs({functionName:"login",code:Ts.NO_TINYID});if(!t)throw new Xs({functionName:"login",code:Ts.NO_A2KEY})}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Qs({code:"RepeatLogin",replacement1:null==(e=ts.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return de(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return ts.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Js(this._customLoginInfo)})}_ensureAsyncComplete(){return de(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=ts.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:n,purchaseBits:i}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),ts.user.userStatus.setCustomStatus(n),ln.getInstance().executeWorkflow(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),ts.common.taskScheduler.addTask({id:qs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(s){return de(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=ts.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield ts.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ln.getInstance().reset(),ts.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;ts.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return de(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=ts.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield ts.channel.sendPacket(t,{requestId:e})}catch(e){ts.ssoLog.warn("_sendOnlinePresenceRequest"," error:"+e.message)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=ts.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ts.common.taskScheduler.removeTask(qs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ts.store.clear("login"),ts.store.set("login",{isReady:!1}),ts.store.set("instance",{applicationID:0})}_dispose(){this._reset();var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}let Pd={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Gd={logout:!0};class wd{constructor(){this.loginAction=new Ld,this.kickedOutHandler=new zs,this.loginAction.init(),this.kickedOutHandler.init(),cn({auth:Gd,params:Pd})}}!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Ud=Ud||{}),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(kd=kd||{}),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"}(Fd=Fd||{});let $d={1:kd.MSG_PRIORITY_HIGH,2:kd.MSG_PRIORITY_NORMAL,3:kd.MSG_PRIORITY_LOW,4:kd.MSG_PRIORITY_LOWEST},qd=0,xd=1,Bd=(!function(e){e.IN="in",e.OUT="out"}(Vd=Vd||{}),2),Kd={};function Hd(e){var t,s,r;return e?(void 0===Kd[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),Kd[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Kd[e])):Kd[e]+=1,Kd[e]):0}class Wd{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=kd.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=ts.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:n,needReadReceipt:i,isSupportExtension:o,customModerationConfigurationId:a,to:l,from:u,nick:c="",avatar:d="",time:h,messageControlInfo:g,tinyID:p,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:E=0,isPlaceMessage:S=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:A=hs.SUCCESS,revokeReason:O="",conversationSubType:T,clientSequence:R,protocol:D="JSON",revokerInfo:b={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:L,groupProfile:P,atUserList:G,flow:w,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||p,this.needReadReceipt=!0===i||1===i,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=l,this.nick=c,this.avatar=d,this.protocol=D,this.random=void 0===L?(t=t||99999999,Math.round(Math.random()*t)):L,this.time=h||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==g||!g.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==g||!g.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=_,this.messageLifeTime=m,this.from=u||null,this.sequence=I||0,this.conversationType=f||Ud.CONV_C2C,this.hasRiskContent=1<E,this.version=v,this.isPlaceMessage=S,this.isRevoked=2===S||8===C,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=O,this.revokerInfo=b,this._receiverList=M,this.conversationSubType=T,this.revoker=(null==b?void 0:b.revoker)||"",this.clientSequence=R||I||0,this.status=A,this.atUserList=G||[],this.flow=w,this.isRead=U,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(P)}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;return this._relayFlag?{isValid:!0}:0<(null==(e=this._elements)?void 0:e.length)?null==(t=null==(e=this._elements[0])?void 0:e.validateBeforeSend)?void 0:t.call(e):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){var{readReceiptSentByPeer:e,timestamp:t=0}=e;this.conversationType===Ud.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===e,this.readReceiptInfo.timestamp=t)}_extractGroupInfo(e){var t,s;e&&({From_AccountNick:e,From_AccountHeadurl:t,MsgFrom_AccountExtraInfo:s}=e,s=(s||{})["NameCard"],"string"==typeof e&&(this.nick=e),"string"==typeof t&&(this.avatar=t),"string"==typeof s)&&(this.nameCard=s)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){var t=this.conversationType;t!==Ud.CONV_SYSTEM?(e=t!==Ud.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=Ud.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Hd(e)),0===this.sequence&&this.conversationType===Ud.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Ud.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class Yd{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new Yd({data:e,description:s,extension:t})}constructor(e){this.type=Fd.MSG_CUSTOM;var{data:e="",description:t="",extension:s=""}=e;this.content={data:e,description:t,extension:s}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{data:e,description:t,extension:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:s,Desc:t}}}validateBeforeSend(){let t=ts.utils["isEmpty"],e=[this.content.data,this.content.description,this.content.extension].some(e=>!t(e));return{isValid:e,error:e?null:{message:"content can not be empty"}}}}class zd{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new zd({text:e})}constructor(e){this.type=ds.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e;return 0<(null==(e=null==(e=this.content)?void 0:e.text)?void 0:e.length)?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},e=(e?this.payload:this.content)["text"];return{MsgType:this.type,MsgContent:{Text:e}}}}var Jd=new class{constructor(){this._elementClassMap={[Fd.MSG_CUSTOM]:Yd,[Fd.MSG_TEXT]:zd}}init(){Nd.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Nd.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){void 0!==t.prototype&&"constructor"in t.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){var{from:t,flow:s=Vd.OUT}=e,r=(ts.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:r})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:r})&&(e.flow=Vd.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new Wd(t)}createCustomMessage(t){let e=En(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[Fd.MSG_CUSTOM];if(!s)return null;if(r){let e=new r(t.payload);s.setElement(e)}return s}createTextMessage(e){var t,s;return e?(t="string"==typeof e.payload?e.payload:(null==(t=null==e?void 0:e.payload)?void 0:t.text)||"",t=new zd({text:t}),s=En(),(e=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:r,tinyID:n}=ts.store.get("login")||{},i=Dd.getUserProfile(r);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||n||"",e.from=r,e.status=hs.UNSENT,e.flow=Vd.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Vd.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Vd.OUT}};let Qd={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}},Xd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Zd={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function eh(r,n){return Object.keys(n).forEach(e=>{var{range:t,defaultValue:s}=n[e];r[e]=t.includes(r[e])?r[e]:s}),r}function th(e){var t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function sh(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,e=eh(e,Xd),{sound:s="",FCMChannelID:r=""}=e,e=le(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:th(s),OPPOChannelID:t,GoogleChannelID:r})}function nh(t){var{apnsInfo:t={},ignoreIOSBadge:s=!1,disableVoipPush:r}=t,t=eh(t,Zd),{ignoreIOSBadge:n,disableVoipPush:i,enableIOSBackgroundNotification:o}=t,t=le(t,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),n=!0===n||!0===s?1:0;let a;return e(r)||(a=!1===r?1:0),e(i)||(a=!1===i?1:0),Object.assign(Object.assign({},t),{BadgeMode:n,IsVoipPush:a,ContentAvailable:o?1:0})}function oh(e){return ts.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:nh(e),AndroidInfo:sh(e)}:Qd}function ih(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:n,IsSyncMsg:i,MsgBody:o,MsgClientTime:a,MsgLifeTime:l,MsgRandom:u,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,E,{From_Account:S,To_Account:C}=e;if(1===i){let e=C;C=S,S=e}if(I){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;E={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:S,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:i,clientTime:a,messageLifeTime:l,random:u,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:g,to:C,tinyID:p,checkResult:_,cloudCustomData:m,revokerInfo:E,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:n,elements:uh(o)}}function rh(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:n,MsgTimeStamp:i,To_Account:o,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:n,time:i,to:o,elements:uh(t),messageVersion:a,cloudCustomData:l}}function ah(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:n,MsgClientTime:i,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,TinyId:d,CloudCustomData:h,MsgVersion:g,MsgCheckResult:p,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,E=kd.MSG_PRIORITY_NORMAL;if(Object.keys($d).includes(String(e.MsgPriority))&&(E=$d[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}var S=function(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{e.GroupAtAllFlag===qd?t.push(e.GroupAt_Account):e.GroupAtAllFlag===xd&&t.push(As.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:i,priority:E,random:o,sequence:a,time:l,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:c,tinyID:d,cloudCustomData:h,messageVersion:g,messageCheckResult:p,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:S,elements:uh(n),to:ch(e)}}function ch(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=ts,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:n}={}}=e;return r!==s||t(n)?e:n}function uh(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=ts.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=ts.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function lh(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:n,MsgTimeStamp:i,GroupId:o,TopicId:a,MsgVersion:l,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:n,time:i,groupID:o,topicID:a,elements:uh(t),messageVersion:l,cloudCustomData:u}}function dh({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:n,flow:i,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&i===Vd.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:n,unreadCount:t?1:0,lastMessage:a})}function hh(e){return e.filter(e=>{var t=!ve(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||ts.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:`+e.sequence),t&&!s})}function gh(e){var t=ts.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var ph=Object.freeze({__proto__:null,autoIncrementIndex:Hd,filterValidMessages:hh,parseServerGroupMessage:ah,parseServerPushC2CModifyMessage:rh,parseServerPushGroupModifyMessage:lh,parseServerPushMessage:ih,parseServerPushMessageElement:uh,shouldStoreMessage:gh,updateConversationFields:dh});let _h=ts.utils["isPlainObject"];function mh(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,n=t["offlinePushInfo"],i=(e.conversationType===Ud.CONV_C2C&&!0===s&&(n?n.disablePush=!0:n={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(i=e.cloudCustomData);var o=[];if(r&&_h(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:o,offlinePushInfo:n}}function vh(e){var t,{webhookInfo:{disableCloudMessagePreHook:e=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(e||s)return t=[],e&&t.push("ForbidBeforeSendMsgCallback"),s&&t.push("ForbidAfterSendMsgCallback"),t}function fh(t,s){return de(this,void 0,void 0,function*(){var e=yield mn((t.conversationType===Ud.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:o,offlinePushInfo:a}=mh(e,t),l=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let u;return n(e._receiverList)&&0<e._receiverList.length&&(u=e._receiverList,50<e._receiverList.length)&&(u=e._receiverList.slice(0,50),console.warn("ReceiverListLimit")),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null==(s=ts.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:l,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:oh(a),SendMsgControl:r?void 0:o,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:u,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:vh(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:n,messageControlInfo:i,offlinePushInfo:o}=mh(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=ts.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:n,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?i: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:oh(o),forbidCallbackControl:vh(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let Ih=ts.utils["isPlainObject"],{MSG_AUDIO:Eh,MSG_FILE:Sh,MSG_IMAGE:Ch,MSG_VIDEO:Mh,MSG_MERGER:yh}=As;class Oh{init(){Nd.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![Eh,Sh,Ch,Mh,yh].includes(e[0].type)})}sendMessage(c,d){return de(this,void 0,void 0,function*(){let{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:t}=Ps;if(!(c instanceof Wd))throw new Xs({code:Ts.MSG_INSTANCE_REQUIRED});let s=c.validateBeforeSend();if(!s.isValid){let{code:e,message:t=""}=s.error||{};throw new Xs({code:e,message:t})}this._reportMessageSendQuality({name:e,message:c});let l=!1;var u=(ts.message||{})["messageDataHandler"];try{let r=(d||{})["messageControlInfo"],n=null,i=(u.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===Ud.CONV_C2C?(l=!0===(null==d?void 0:d.onlineUserOnly),n=yield fh(c,d)):c.conversationType===Ud.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),n=yield fh(c,d)),n){let{messageDropReason:e,sequence:t,time:s}=n;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t,e),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:o,message:c,startTs:i}),!0===c.isResend){let e=u.findMessage(c.ID);e&&(ts.ssoLog.debug("sendMessage","sendMessage resend ok. ID:"+e.ID),u.deleteConversationMessage(e))}return c.status=hs.SUCCESS,c.time=s,c.conversationType===Ud.CONV_GROUP&&(c.sequence=t),l?c._onlineOnlyFlag=!0:(u.storeConversationMessage(c),this._applySentMessageControlInfo(c,r),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=hs.FAIL,u.removeRandomOfSentMessage(c.random);var r=(e||{})["errorCode"],n=(null==e?void 0:e.errorMessage)||(null==e?void 0:e.message)||"";throw this._hasRiskContent(r)&&(c.hasRiskContent=!0),l||this._isRejectedByRestApi(r)||u.storeConversationMessage(c),this._reportMessageSendQuality({name:t,message:c,error:e}),n=`type:${c.type} from:${c.from} to:${c.to} `+n,new Xs({code:r,message:n,data:{message:c}})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,n=gn(s)?cs.TOPIC_NEW_MESSAGE:cs.NEW_MESSAGE;ts.notificationCenter.emitInnerEvent(n,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Ih(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t,s){e=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:`+s;ts.ssoLog.warn("messageDropReason",e)}_updateNickAndAvatarOfSentMessageByMe(e){var t=(ts.message||{})["messageDataHandler"];let s=!1;var r,n=e["conversationID"],i=t.getLatestMsgSentByMe(n);i&&({nick:i,avatar:r}=i,s=i!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(n){return de(this,void 0,void 0,function*(){var{to:t,from:s}=n;let r=t,e=Td.getGroup(r);if(hn({groupID:r})&&null!=e&&e.isSupportTopic)throw new Xs({code:Ts.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(gn(t)&&([r]=t.split(Ms.TOPIC),e=Td.getGroup(r)),!e&&"function"==typeof(null==(t=Nd.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield Nd.getInstance().getApiMap().getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===As.GRP_AVCHATROOM){let e=Qs({code:Ts.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new Xs({code:Ts.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){ts.notificationCenter.emitInnerEvent(cs.QUALITY_STAT,{label:Ls.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class Ah{constructor(e){this.value=e,this.next=null}}class Th{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new Ah(e);this.head?this.tail.next=e:this.head=e,this.tail=e,this.size+=1}delete(t){if(this.head)if(this.head.value===t)this.head=this.head.next;else{let e=this.head;for(;e.next;){if(e.next.value===t)return void(e.next=e.next.next);e=e.next}}}has(e){if(!this.head)return!1;let t=this.head,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,--this.size)}peek(){var e;return null==(e=this.head)?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}var Rh=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Th(100)}init(){ts.notificationCenter.subscribeInnerEvent(cs.LOGOUT,this._reset,this),ts.notificationCenter.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}get _messagesByConversation(){return Rd.getMessages()}storeConversationMessage(e,t=!1){var s=e["conversationID"];return!!s&&(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),!this._shouldSkipStoreMessage(e,t))&&(t=this._getUniqueIdOfMessage(e),this._messagesByConversation.get(s).set(t,e),this._updateLatestMessageMap(e),!0)}_updateLatestMessageMap(e){var t=e["conversationID"];"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){var s=this._getUniqueIdOfMessage(e),r=this._messagesByConversation.get(e.conversationID);if(null!=r&&r.has(s)){let e=null==r?void 0:r.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var{conversationID:t=""}=e,e=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(t)&&null!=(t=this._messagesByConversation.get(t))&&t.delete(e)}modifyConversationMessage(a,t){var l;if(this._messagesByConversation.has(a)||this._sparseMessagesByConversation.has(a)){let e=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(a,e);if(o){let{messageVersion:s,elements:r,cloudCustomData:n,checkResult:e=0}=t,i=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:`+s),o.version<s){let e=this._getUniqueIdOfMessage(o),t=fe(r);return null!=(l=this._messagesByConversation.get(a))&&l.has(e)?Rd.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:n,hasRiskContent:i,operation:gs.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=n,o.isModified=!0,o.hasRiskContent=i),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,s){var t;if(this._messagesByConversation.has(e))return null==(t=this._messagesByConversation.get(e))?void 0:t.get(s);if(this._sparseMessagesByConversation.has(e)){let t=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<t.length;e++)if(this._getUniqueIdOfMessage(t[e])===s)return t[e]}return null}findMessage(t){let s=null,e=Array.from(this._messagesByConversation.values());for(var r of e)if(s=Array.from(r.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var n of e)if(s=n.get(t)||null,s)break}return s}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:t,sequence:s,random:r,revoker:n}){let e=this._messagesByConversation.get(t),i=null;if(e){var o=Array.from(e.values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(i);return Rd.updateMessage(t,[e],{isRevoked:!0,revoker:n,operation:gs.revoke}),i}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(i=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return i.isRevoked=!0,i.revoker=n,i}}_findMessageBySequenceAndRandom({messageList:s,sequence:r,random:n}){for(let t=0;t<s.length;t+=1){var i=s[t];if(i.sequence===r&&(e(n)||i.random===n))return i}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],n=[],i=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);i.has(e)||(r.push(t),n.push([e,t]))}if(0<n.length){let e=new Map([...n,...i.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var n=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];n.has(e.ID)||n.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:n}=e;return e+`-${t}-${s}-${r}-`+n}_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.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:i,latestNick:o,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),n=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===n&&(t!==o&&(e.nick=o),s!==i)&&(e.avatar=i)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ts.notificationCenter.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),ts.notificationCenter.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}};function Dh(e,t){var s,r,n,i,o,a,l,u=Ad.getConversation(e);null!=u&&u.lastMessage&&(u=u["lastMessage"],{lastTime:s,lastSequence:r,version:n}=u,{time:t,sequence:i,messageVersion:o,elements:a,cloudCustomData:l}=t,s===t)&&r===i&&n!==o&&(u.type=a[0].type,u.payload=a[0].content,u.messageForShow=Mn(u.type,u.payload),u.cloudCustomData=l,u.version=o,Ad.updateConversation(e,{lastMessage:u}))}class bh{init(){Nd.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(u){return de(this,void 0,void 0,function*(){let{to:r,payload:t,sequence:n,conversationType:i,random:o,time:a,from:l,type:s}=u;if(this._canModifyMessageElement(s)){let e=u.getElements();1<e.length&&(e[0].type=s,e[0].content=t)}try{let t=null,s;if(i===Ud.CONV_C2C?t=yield function(c){return de(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:n,time:i,type:o,cloudCustomData:a}=c,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:n,MsgTime:i,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},u=yield mn({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:uh(e),messageVersion:t,cloudCustomData:s}}})}(u):i===Ud.CONV_GROUP&&(t=yield function(o){return de(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=o,n={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:r},i=yield mn({servcmd:"openim.modify_group_msg",data:n});if(i){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=i;return{elements:uh(e),messageVersion:t,cloudCustomData:s}}})}(u)),t){let e=""+i+r;return r===En()&&i===Ud.CONV_C2C&&(e=""+i+l),s={conversationType:i,from:l,to:r,time:a,random:o,sequence:n,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:u},successLog:{message:"to:"+r}}}}catch(e){let t=(e||{})["errorCode"];throw new Xs({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent(rs.MESSAGE_MODIFIED,{name:rs.MESSAGE_MODIFIED,data:[r]}),ts.notificationCenter.emitInnerEvent(cs.MESSAGE_MODIFIED,{conversationID:t,message:r}),Dh(t,e)}_canModifyMessageElement(e){return[Fd.MSG_TEXT,Fd.MSG_CUSTOM,Fd.MSG_LOCATION,Fd.MSG_FACE].includes(e)}}class Nh{init(){var e=ts["notificationCenter"],t=e["InnerEventSubType"];ln.getInstance().registerWorkflowStep(Ds.RECEIVE_C2C_NEW_MESSAGE,bs.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ln.getInstance().registerWorkflowStep(Ds.RECEIVE_C2C_NEW_MESSAGE,bs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){ln.getInstance().executeWorkflow(Ds.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(ts.message||{})["messageDataHandler"],r=[],n=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):gh(e)&&(s.storeConversationMessage(e)&&dh({conversationUpdateFields:n,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||r.push(e))}),{conversationUpdateFieldList:[...n.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[bs.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[bs.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(e)}_emitMessageEvents(e){var t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=Ud.CONV_C2C,e=ih(e),t=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Vd.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(i){var s;let o=(ts.message||{})["messageDataHandler"],r=null==(s=ts.store.get("login"))?void 0:s.userId,{from:n,nick:a,avatar:l,conversationID:u=""}=i;if(n!==r){let n=o.getLatestMsgSentByPeer(u);if(n){let{nick:s,avatar:r}=n;e(a)||e(l)?(i.nick=t(s)?s:i.nick,i.avatar=t(r)?r:i.avatar):a===s&&l===r||(o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:l,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:u,nick:a,avatar:l}))}}else{let e=o.getLatestMsgSentByMe(u);!e||a===e.nick&&l===e.avatar||o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:l,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=Ad.getConversation(e)||{};r.avatar===s&&r.nick===t||Ad.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),ts.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Dh(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=Ud.CONV_C2C,e=rh(e),{to:s,from:r}=e;let n=""+t+s;s===(null==(s=ts.store.get("login"))?void 0:s.userId)&&(n=""+t+r),e=Object.assign({conversationType:t,conversationID:n},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=ts["notificationCenter"],e=e["InnerEventSubType"];ts.notificationCenter.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ts.notificationCenter.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ts.notificationCenter.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}class Lh{init(){var e=ts["notificationCenter"],t=e["InnerEventSubType"];ln.getInstance().registerWorkflowStep(Ds.RECEIVE_GROUP_NEW_MESSAGE,bs.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ln.getInstance().registerWorkflowStep(Ds.RECEIVE_GROUP_NEW_MESSAGE,bs.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&ln.getInstance().executeWorkflow(Ds.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=ts.message["messageDataHandler"],r=[],n=new Map,i=null==t?void 0:t.GroupMsgArray;return null!=i&&i.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):gh(e)&&s.storeConversationMessage(e)&&(r.push(e),dh({conversationUpdateFields:n,message:e})))}),{conversationUpdateFieldList:[...n.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[bs.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=Ud.CONV_GROUP,e=ah(e),t=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Vd.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(n){var e;let t=(ts.message||{})["messageDataHandler"],s=null==(e=ts.store.get("login"))?void 0:e.userId,{from:r,nick:i,avatar:o,conversationID:a="",_elements:l}=n;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!0})}else if(r===As.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=l,r={};if(ve(t)?ve(s)||(r=s):[ys.JOINED,ys.KICKED,ys.ADMIN_SET,ys.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!ve(r)){let{nick:e="",avatar:t=""}=r;n.nick=e,n.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Dh(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=Ud.CONV_GROUP,{topicID:s,groupID:r}=e=lh(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=ts["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var{GroupId:e,GroupType:t}=(null==(e=null==(e=null==e?void 0:e.GroupMsgArray)?void 0:e[0])?void 0:e.GroupInfo)||{},t=t===Cs.GRP_AVCHATROOM;return!(!Td.getGroup(e)&&t)}}var Ph=new class{constructor(){this.c2cMessageReceiver=new Nh,this.groupMessageReceiver=new Lh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let Gh={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=>{return"string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(e=null==e?void 0:e.text)?void 0:e.length))||"payload.text must be a string"}}}},wh={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var Uh=new class{getGroupRoamingMessagesByAnchor(i){return de(this,void 0,void 0,function*(){try{var{conversationID:t,count:s,direction:l,sequence:u,messageSequenceList:e,getType:r}=i,c=t.replace(Is.CONV_GROUP,""),d=[];let a=u;if(l===ps.BACKWARD){if("number"!=typeof u)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=u+s-1}var h=yield function(o){return de(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s,messageSequenceList:r,getType:i}=o,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1,GetType:i};return s&&(e.ReqMsgSeq=s),n(r)&&0<r.length&&(e.ReqMsgSeqList=r),yield mn({servcmd:"group_open_http_svc.group_msg_get",data:e})})}({groupID:c,count:s,messageSequence:a,messageSequenceList:e,getType:r});if(h){let{RspMsgList:s=[],NextReqMsgSeq:e=0,IsFinished:t,InvisibleMsgSeq:r}=h,n=`groupID:${c} sequence:${u} reqSeq:${a} direction:${l} complete:${t} nextSequence:${e} remoteMsgCount:${s.length} invisibleSequenceList:`+r,i=[];for(let t=0;t<s.length;t++){var g=s[t];g.From_Account===As.CONV_SYSTEM&&d.push(g);let e=this._parseMessage(g);i.push(e)}i.reverse();let o=t===Bd;l===ps.BACKWARD&&(o=i[i.length-1].sequence>=u);var p=hh(i);return ts.ssoLog.info("getGroupRoamingMessagesByAnchor",n),{messageList:p,invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,serverGroupTipList:d}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new Xs({code:t,message:s})}})}_parseMessage(e){var t=Is.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=As.MSG_GRP_TIP),ah(e)),t=Jd.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class kh{constructor(){this.messageHelper=ph,this.messageFactory=Jd,this.messageSender=new Oh,this.messageAction=new bh,this.messageReceiver=Ph,this.messageDataHandler=Rh,this.messageHistory=Uh,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),cn({auth:wh,params:Gh})}}let Fh="Tag_Profile_IM_",$h={NICK:Fh+"Nick",GENDER:Fh+"Gender",BIRTHDAY:Fh+"BirthDay",LOCATION:Fh+"Location",SELFSIGNATURE:Fh+"SelfSignature",ALLOWTYPE:Fh+"AllowType",LANGUAGE:Fh+"Language",AVATAR:Fh+"Image",MESSAGESETTINGS:Fh+"MsgSettings",ADMINFORBIDTYPE:Fh+"AdminForbidType",LEVEL:Fh+"Level",ROLE:Fh+"Role"},qh="Tag_Profile_Custom",xh="profileCustomField",Vh="USER_STATUS",Bh=1,jh=1e3,Kh={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:[]},Hh=new Map([[$h.NICK,"nick"],[$h.GENDER,"gender"],[$h.BIRTHDAY,"birthday"],[$h.LOCATION,"location"],[$h.SELFSIGNATURE,"selfSignature"],[$h.ALLOWTYPE,"allowType"],[$h.LANGUAGE,"language"],[$h.AVATAR,"avatar"],[$h.MESSAGESETTINGS,"messageSettings"],[$h.ADMINFORBIDTYPE,"adminForbidType"],[$h.LEVEL,"level"],[$h.ROLE,"role"]]);var lg,dg,hg,Wh=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(qh)?s.profileCustomField.push({key:e,value:t}):Hh.has(e)&&(s[Hh.get(e)]=t)}),Object.assign(Object.assign({},Kh),s)}parseProfileItem(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.Value})}),t}parseProfileList(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.ValueBytes})}),t}convertParamsToProfile(t){let s=[];return Object.keys(t).forEach(e=>{e!==xh&&s.push({tag:$h[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&n(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let r={},n=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(qh)&&n.push({key:t,value:s}),Hh.has(t)&&void 0!==s){let e=Hh.get(t);r[e]=s}}),0<n.length&&(r.profileCustomField=n),r}};let Yh=ts.common["generateProtocolData"];function zh(r){return de(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:En(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var i=Yh({servcmd:e,data:t}),s=i.head.seq+e,i=yield ts.channel.sendPacket(i,{requestId:s});if(i){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:n}=i,o=[];return n.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:n,ProfileItem:i}=e,i=Wh.parseProfileItem(i);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:n,profileItem:i})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:o}}})}function Jh(e){return Dd.getFriendMap().has(e)}let Qh=ts.utils["isEmpty"];class Xh{constructor(){this._strangerProfileMap=new Map}init(){Nd.getInstance().registerApi({apiName:"getMyProfile",context:this}),Nd.getInstance().registerApi({apiName:"getUserProfile",context:this}),Nd.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Wh.createProfile.bind(Wh);var e=ts["notificationCenter"];ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,bs.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}getMyProfile(){return de(this,void 0,void 0,function*(){try{var e,t=En(),s=yield zh([t]);if(s)return e=this._handleProfileFormResponse(s)[0],Dd.getUserProfileMap().set(t,e),{code:0,data:e}}catch(e){var{errorCode:s,errorInfo:t}=e;throw new Xs({functionName:"getMyProfile",code:s,message:t})}})}getUserProfile(u){return de(this,void 0,void 0,function*(){try{var t=u["userIDList"],{userIdListToRequest:e,profileFromCache:s}=this._filterRequestAndCacheUsers(t);if(0===e.length)return{code:0,data:s,successLog:{message:"userIDList.length:"+t.length}};e.length>jh&&(ts.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),e.length=jh);var{data:r,error:i}=yield this._batchFetchUserProfiles(e),o=e.length,a=r.length,l=o-a;if(0===s.length&&o===l&&!Qh(i))throw i;if(n(r)){r.forEach(e=>{(Jh(e.userID)?Dd.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=r.concat(s);return{code:0,data:e,successLog:{message:`getUserProfile query:${o} success:${a} fail:${l} from cache:`+s.length}}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return de(this,void 0,void 0,function*(){var e=En(),e=Dd.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return de(this,void 0,void 0,function*(){let t=En(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);var r=Wh.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};yield function(r){return de(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Yh({servcmd:e,data:r}),s=""+t.head.seq+e,n=yield ts.channel.sendPacket(t,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=n;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var n=Dd.getUserProfile(t),i=n?Object.assign(Object.assign({},n),s):Wh.createProfile(t,r),o=!ns(n,i,["lastUpdatedTime"]);return i.lastUpdatedTime=Date.now(),Dd.getUserProfileMap().set(t,i),o&&this._emitProfileUpdated(i),{code:0,data:i,successLog:{message:"profileArray: "+ts.utils.safeStringify(r)}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(n){return de(this,void 0,void 0,function*(){var e=En(),t=Date.now(),s=Dd.getUserProfile(e),r={};(r=s?Object.assign(s,n):Wh.createProfile(e,n)).lastUpdatedTime=t,Dd.getUserProfileMap().set(e,r)})}_onProfileDataModify(r){var e,t=function(){var{Profile_Account:e,PushType:t,ProfileList:s}=r.ProfileDataMod[0];return{userId:e,pushType:t,profileList:Wh.parseProfileList(s)}}();Qh(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){ts.notificationCenter.emitInnerEvent(cs.PROFILE_UPDATE,{name:cs.PROFILE_UPDATE,data:[e]}),ts.notificationCenter.emitOuterEvent(rs.PROFILE_UPDATED,{name:rs.PROFILE_UPDATED,data:[e]}),Ad.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=Dd.getUserProfile(t);if(!(En()===t||Jh(t)&&r))return{isProfileUpdated:!1,profile:null};let n=Wh.normalizeProfileFields(s),i=Object.keys(n).some(e=>e===xh?!ns(r.profileCustomField,n.profileCustomField):r[e]!==n[e]);return i?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),n),{lastUpdatedTime:e}),Dd.getUserProfileMap().set(t,e),{isProfileUpdated:i,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=Dd.getUserProfileMap().has(e);Jh(e)&&t?r.push(Dd.getUserProfile(e)):this._isStrangerAndProfileValid(e)?r.push(this._strangerProfileMap.get(e)):s.push(e)}),{userIdListToRequest:s,profileFromCache:r}}_handleProfileFormResponse(e){e=e.userProfile;if(!Array.isArray(e))return[];let t=e.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Qh(e.profileItem)),s=Date.now();return t.map(e=>{e=Wh.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!Jh(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=ts.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,r){return Array.from({length:Math.ceil(s.length/r)},(e,t)=>s.slice(t*r,(t+1)*r))}_batchFetchUserProfiles(e){return de(this,void 0,void 0,function*(){let t=[],r=[],i={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(zh(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);n(t)&&r.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};i={errorCode:e,message:t}}}),{data:r,error:i}})}_reset(){Dd.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}let Zh=new Map,eg=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=eg.length;e<t;e++)Zh.set(e,eg[e]);function tg(e){if(!e)return"";var n=String(e).replace(/[=]+$/,"");let i="";if(n.length%4==1)return"";for(let e,t,s=0,r=0;t=n.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(i+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(i))}catch(e){return console.warn(e),""}}let sg=ts.utils["isEmpty"],ng=ts.common["generateProtocolData"];function og(n){return de(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=ng({servcmd:s,data:{To_Account:n}}),s=r.head.seq+s,r=yield ts.channel.sendPacket(r,{requestId:s});if(r)return{ErrorCode:s,ErrorInfo:r,ErrorList:e=[],UserStatusList:t=[]}=r,{errorCode:s,errorInfo:r,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:tg(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:sg(t)?e:t,code:s,message:r}})}})}class ig{constructor(){this._customStatus=""}init(){var e=ts["notificationCenter"];Nd.getInstance().registerApi({apiName:"getUserStatus",context:this}),Nd.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Nd.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Nd.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}setSelfStatus(s){return de(this,void 0,void 0,function*(){let e=En(),t=s["customStatus"];try{return yield function(n){return de(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=ng({servcmd:e,data:{CustomStatus:n}}),s=""+t.head.seq+e,r=yield ts.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,{code:0,data:{userID:e,statusType:Bh,customStatus:t},successLog:{message:"customStatus: "+t}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(s){return de(this,void 0,void 0,function*(){var{userIDList:e=[]}=s;let t={};return this._isOnlyMeInArray(e)&&(t=this._getMyStatus()),t=yield this._getUserStatus(e),Object.assign(Object.assign({},t),{successLog:{message:"userIDList length: "+e.length}})})}setCustomStatus(e){e=tg(e);this._customStatus=e}subscribeUserStatus(n){return de(this,void 0,void 0,function*(){try{var{userIDList:e=[]}=n,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return de(this,void 0,void 0,function*(){var e=ts["channel"],t="im_open_status.ws_status_subscribe",s=ng({servcmd:t,data:{To_Account:r}}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(n){return de(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=n,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return de(this,void 0,void 0,function*(){var e=ts["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=ng({servcmd:t,data:s}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){var{UserStatusList:e=[]}=e||{},e=e.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:tg(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=tg(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:En(),statusType:Bh,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){ts.notificationCenter.emitOuterEvent(rs.USER_STATUS_UPDATED,{name:rs.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){var{ErrorList:e=[]}=e;return e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:ts.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!ts.store.get("commercialConfig").get(Vh))throw new Xs({functionName:e,code:Ts.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=ts.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:En(),statusType:Bh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return de(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");var t=this._getMaxUserCount("query"),{successUserList:e,failureUserList:s}=(yield og(this._sliceUserIDList(r,t)))||{};return{code:0,data:{successUserList:e,failureUserList:s}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){var t=En();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let rg={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(var 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||!t.key.startsWith(qh))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}}},ag={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class cg{constructor(){this.userProfile=new Xh,this.userStatus=new ig,this.userProfile.init(),this.userStatus.init(),cn({auth:ag,params:rg})}}function ug(s){var r=[];if(t(s)){var n=s.length;if(0!==n)for(let e=n-1;0<=e;e--)"1"===s[e]&&r.push(2**(n-e-1))}return r}!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(lg=lg||{}),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(dg=dg||{}),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(hg=hg||{});class gg{constructor(){this._name="SyncConversationHandler",this._pagingStatus=lg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=ts["notificationCenter"];ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.CONVERSATION_RECOVER,this._syncConversationList,this),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,bs.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this),ts.ssoLog.debug(this._name+".init")}isSyncCompleted(){return this._pagingStatus===lg.RESOLVED}_syncConversationListAfterLogin(){return de(this,void 0,void 0,function*(){return this._pagingStatus=lg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return de(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:s}}=ts;t.debug("_syncConversationList","start");try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=lg.RESOLVED;var{conversationList:r=[]}=e||{};return t.info("_syncConversationList","success count:"+r.length),e}catch(e){var{errorCode:r,errorInfo:n}=e,r=new Xs({code:r,message:n});t.error("_syncConversationList","fail "+s(e),{error:r})}})}_pagingGetConversationList(c){return de(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=lg.PENDING,yield function(i){return de(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:n}=i;return mn({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:n,TopTimeStamp:r}})})}({fromAccount:En(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:n=[],TimeStamp:i,StartIndex:o,TopTimeStamp:a,TopStartIndex:l}=s||{};if(0<n.length){let e=this._getConversationOptions(n);t.push(...e);var u=ts["notificationCenter"];u.emitInnerEvent(cs.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=i,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=l,1!==r&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){let{isUndefined:t}=ts["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===dg.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===dg.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(As.CONV_C2C)?e.replace(As.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+As.CONV_C2C+e.userID,type:As.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:null!=(t=e.lastMsg)&&t.elements[0]?null==(t=e.lastMsg)?void 0:t.elements[0].type:null,payload:null!=(t=e.lastMsg)&&t.elements[0]?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===hg.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null==(t=null==(t=e.lastMsg)?void 0:t.revokerInfo)?void 0:t.revoker)||null},unreadCount:0,userProfile:s,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:ug(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var{userID:e,nick:t,peerAvatar:s}=e,t=[{tag:"Tag_Profile_IM_Nick",value:t},{tag:"Tag_Profile_IM_Image",value:s}];return null==(s=ts.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===En()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+As.CONV_GROUP+e.groupID,type:As.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===hg.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null==(t=null==(t=e.lastMsg)?void 0:t.revokerInfo)?void 0:t.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:ug(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(s){var e,t,r=ts["utils"]["isEmpty"];if(r(s))return null;let n="",i=null;if(!r(s.GroupTips)){let{From_Account:e,GroupName:t}=(null==(r=s.GroupTips)?void 0:r.GroupInfo)||{};n=As.MSG_GRP_TIP,i=Object.assign(Object.assign({},this._parseContent(n,s.GroupTips.MsgBody)),{groupProfile:{from:e,groupName:t}})}return s.MsgBody&&(n=null==(e=s.MsgBody[0])?void 0:e.MsgType,i=this._parseContent(n,s.MsgBody[0])),{event:s.Event,elements:[{type:n,content:i,cloudCustomData:s.CloudCustomData}],revokerInfo:{revoker:null==(t=s.RevokerInfo)?void 0:t.revoker}}}_parseContent(e,t){return t&&((e=ts.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return le(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=As.MSG_REMIND_ACPT_AND_NOTE:1===e?t=As.MSG_REMIND_DISCARD:2===e?t=As.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=As.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=ts["utils"]["isUndefined"],{event:e,elements:s=[]}=e.lastMsg||{};return t(e)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:As.MSG_GRP_TIP,payload:(null==(t=null==s?void 0:s[0])?void 0:t.content)||{}}}_computeGroupUnreadCount(e){var{unreadCount:e=0,noUnreadCount:t=0}=e,e=e-t;return 0<e?e:0}_reset(){this._pagingStatus=lg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}class pg{constructor(){this.syncConversationHandler=new gg,this.syncConversationHandler.init()}}ts.ssoLog.debug("TencentCloudLiteChat.VERSION:"+it);var _g={create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:n="",oversea:i=!1,instance:o,disableIndependentDomain:a=!1}=e,l=e;if("number"!=typeof l&&(e=Number(l),Number.isNaN(e)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(l=Number(l),dn.has(l))return dn.get(l);let u=null;if(o)(u=o)._workflowManager&&ln.setInstance(u._workflowManager),u._pluginManager&&u._pluginManager.installBuiltInPlugin(Md),!o.isReady()||null!=(o=(e=ln.getInstance()).executeWorkflow)&&o.call(e,Ds.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(c()+c())+c()+c()+c()+c()+c()+c();ts.init({sdkAppId:l,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:r,disableIndependentDomain:a,scene:n,oversea:i,sdkEdition:Cd}),ln.getInstance().init(),ts.message=new kh,ts.user=new cg,ts.login=new wd,ts.conversation=new pg,Od.getInstance().installBuiltInPlugin(Md),(u=Nd.getInstance().exposeApiForClient())._workflowManager=ln.getInstance(),u._pluginManager=Od.getInstance()}function c(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return dn.set(l,u),u},TSignaling:us,EVENT:rs,VERSION:it,TYPES:As};export{_g as default};
1
+ let e=e=>void 0===e,t=e=>"string"==typeof e,s=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[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=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},a=e=>{if("object"!=typeof e||null===e)return!1;e=Object.getPrototypeOf(e);if(null===e)return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return e===t};function c(e=99999999){return Math.round(Math.random()*e)}let u=(r,n,o,a)=>{if(!i(r)||!i(n))return 0;let l=0;var c,d=Object.keys(n);for(let t=0,s=d.length;t<s;t++)if(c=d[t],!(e(n[c])||o&&o.includes(c)))if(i(r[c])&&i(n[c]))l+=u(r[c],n[c],o,a);else{if(a&&a.includes(n[c]))continue;r[c]!==n[c]&&(r[c]=n[c],l+=1)}return l};function l(s){let r,i,n=s,o="";for(let e=0,t=(n=s.length%8!=0?"0".repeat(8-s.length%8)+s:n)["length"];e<t;e+=8)r=parseInt(n.slice(e,e+4),2),i=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(r)+base16Map.get(i);return o}let 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 g,S;!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"}(g=g||{});let p="LiteChat",_={[g.DEBUG]:console.debug,[g.INFO]:console.info,[g.WARN]:console.warn,[g.ERROR]:console.error},m={[g.INFO]:4,[g.WARN]:5,[g.ERROR]:6},v=1e3,f=2,I=5e3,E=50;!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 C=Object.freeze({__proto__:null,CONSOLE_METHOD:_,CloudConfigReportLevelMap:m,get ConvModifyPushType(){return S},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:E,DEFAULT_GLOBAL_THROTTLE_TIME:I,DEFAULT_SINGLE_MAX_TOTAL_COUNT:f,DEFAULT_SINGLE_THROTTLE_TIME:v,ENUM_PLATFORM:d,IS_TOPIC_MESSAGE:2,get LogLevel(){return g},NOT_NEED_CRC_SERVCMD:h,SDK_NAME:p});let M="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),y="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||M,O=y&&"function"==typeof wx.createGamePortal,A="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),R=T&&"function"==typeof tt.onShow,D="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),b="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,L="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,P=y&&"object"==typeof wx.miniapp,w="undefined"!=typeof uni,G=y||A||T||D||b||L||N,U="undefined"==typeof window&&!G&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,k="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),F="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),$="undefined"!=typeof uni?!G:"undefined"!=typeof window&&!G&&!k,q=A?qq:T?tt:D?swan:b?my:y?wx:L?uni:N?jd:{},x=$&&window&&window.navigator&&window.navigator.userAgent||"",V=/(micromessenger|webbrowser)/i.test(x),B=function(){let e="WEB";return V?e="WEB":A?e="QQ_MP":T?e="TT_MP":D?e="BAIDU_MP":b?e="ALI_MP":y?e=P?"DONUT_NATIVE_APP":"WX_MP":L?e="UNI_NATIVE_APP":U?e="NS_NATIVE_APP":k&&(e="RN_NATIVE_APP"),d[e]}(),j=/iPad/i.test(x),K=/iPhone/i.test(x)&&!j,H=/iPod/i.test(x),W=K||j||H,Y=function(){var e=x.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),z=/Android/i.test(x),J=function(){var e,t,s=x.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);return s?(e=s[1]&&parseFloat(s[1]),t=s[2]&&parseFloat(s[2]),e&&t?parseFloat(s[1]+"."+s[2]):e||null):null}(),Q=/Firefox/i.test(x),X=/Edge/i.test(x),Z=!X&&/Chrome/i.test(x),ee=/MSIE/.test(x)||-1<x.indexOf("Trident")&&-1<x.indexOf("rv:11.0"),te=function(){var e=/MSIE\s(\d+)\.\d/.exec(x);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(x)&&/rv:11.0/.test(x)?11:t}(),se=/Safari/i.test(x)&&!Z&&!z&&!X,ne=/Windows/i.test(x),oe=/MAC OS X/i.test(x),ie=$&&"undefined"!=typeof Worker&&!ee,re=z||W,ae=$&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ce=function(){var e;return"undefined"!=typeof window&&void 0!==window.navigator&&(e=window.navigator["standalone"],!(!W||e||se))}();function ue(){let e="unknown";if(oe&&(e="mac"),ne&&(e="windows"),W&&(e="ios"),z&&(e="android"),G)try{var t=q.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}function le(e,t){var s={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]]);return s}function de(e,o,a,l){return new(a=a||Promise)(function(s,t){function r(e){try{n(l.next(e))}catch(e){t(e)}}function i(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,i)}n((l=l.apply(e,o||[])).next())})}let he=2800,ge=2801,pe=3e3,_e="application/x-www-form-urlencoded;charset=UTF-8";function me(e){return de(this,arguments,void 0,function*({method:i,url:n,data:o,timeout:a=pe}){return new Promise(G?(t,e)=>{q.request({url:n,data:o,method:i,timeout:a,header:{"content-type":_e},success:e=>t(e.data),fail:()=>e(new Error(`{"message":"Network error","code":${he}}`))})}:(t,e)=>{let s=new XMLHttpRequest,r=setTimeout(()=>{s.abort(),e(new Error(`{"message":"Request timeout","code":${ge}}`))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(r),200===s.status||304===s.status)try{t(s.responseText?JSON.parse(s.responseText):null)}catch(e){t(s.responseText)}else e(new Error(`{"message":"Network error","code":${he}}`))},s.open(i,n,!0),s.setRequestHeader("Content-type",_e),s.send(o||null)})})}function ve(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(var 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 fe(r){if(null===r||"object"!=typeof r)return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp)return new RegExp(r.source,r.flags);if(r instanceof Map){let s=new Map;return r.forEach((e,t)=>{s.set(fe(t),fe(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(fe(e))}),t}if(Array.isArray(r))return r.map(e=>fe(e));let e=Object.getPrototypeOf(r),s=Object.create(e);return[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)].forEach(e=>{var t=Object.getOwnPropertyDescriptor(r,e);t&&(t.get||t.set?Object.defineProperty(s,e,t):s[e]=fe(r[e]))}),s}function Ie(e,s,t){let r=new WeakSet;try{return JSON.stringify(e,(e,t)=>{if(void 0===(t=s?s(e,t):t))return"undefined";if(null===t)return null;if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if("function"==typeof t)return`[Function: ${t.name||"anonymous"}]`;if("symbol"==typeof t)return t.toString();if("bigint"==typeof t)return t.toString()+"n";if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t instanceof Date?t.toISOString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof Set?{dataType:"Set",value:Array.from(t.values())}:t},t)}catch(e){return console.error("Failed to stringify:",e),""}}function Ee(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var Se,Te,Ce=Object.freeze({__proto__:null,ANDROID_VERSION:J,IE_VERSION:te,IN_ALIPAY_MINI_APP:b,IN_BAIDU_MINI_APP:D,IN_BROWSER:$,IN_DONUT_NATIVE_APP:P,IN_JD_MINI_APP:N,IN_MINI_APP:G,IN_NS_NATIVE_APP:U,IN_QQ_MINI_APP:A,IN_RN_APP:k,IN_TT_MINI_APP:T,IN_TT_MINI_GAME:R,IN_UNI_APP:w,IN_UNI_NATIVE_APP:L,IN_WX_MINI_APP:y,IN_WX_MINI_APP_DESK:M,IN_WX_MINI_GAME:O,IN_WX_MINI_PLUGIN:F,IOS_VERSION:Y,IS_ANDROID:z,IS_CHROME:Z,IS_EDGE:X,IS_FIREFOX:Q,IS_IE:ee,IS_IOS:W,IS_IPAD:j,IS_IPHONE:K,IS_IPOD:H,IS_MAC:oe,IS_SAFARI:se,IS_WECHAT:V,IS_WIN:ne,IS_WORKER_AVAILABLE:ie,MINI_APP_NAMESPACE:q,USER_AGENT:x,base16EncodeBinaryString:l,deepCopyWithMethods:fe,deepMerge:u,generatePromise:Ee,getPlatformType:ue,getType:s,httpRequest:me,isArray:n,isArrayOrObject:i,isEmpty:ve,isFlutterWeb:ae,isH5:re,isIOSWebView:ce,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:o,isPlainObject:a,isString:t,isUndefined:e,isUniIOSApp:function(){return L&&"ios"===uni.getDeviceInfo().platform.toLocaleLowerCase()},isValidRequestKey:r,platform:B,randomInt:c,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t},safeStringify:Ie});class Me{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,r){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!r||e.context===r;return!(t&&e)}))}emit(s,...r){var e=this.listeners[s];e&&e.forEach(e=>{var{fn:e,context:t}=e;try{e.apply(t,r)}catch(e){console.warn(`Error in event handler for ${s} error: `+Ie(e))}})}once(t,s,r){let i=(...e)=>{s.apply(r,e),this.off(t,i)};this.on(t,i)}}!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"}(Se=Se||{});let ye=[16,17];function Oe(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{2===e.GroupInfo.MillionGroupFlag?s.push(Se.TOPIC_TIPS_NOTIFICATION):ye.includes(null==(e=null==e?void 0:e.MsgBody)?void 0:e.OpType)?s.push(Se.GROUP_MESSAGE_PINNED):s.push(Se.GROUP_TIPS_NOTIFICATION)}),s}let Ae=[{conditions:[{type:"event",value:100}],subType:Se.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Se.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Se.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Se.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Se.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Se.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Se.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Se.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Se.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Se.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.C2cNotifyMsgArray)&&t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(Se.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(Se.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(Se.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(Se.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Oe},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(Se.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(Se.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(Se.TOPIC_MESSAGE_READ_SYNC):s.push(Se.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(Se.TOPIC_SYSTEM_NOTIFICATION):s.push(Se.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Oe},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{var e=e["GroupAtTips"]["TopicId"];e?s.push(Se.TOPIC_AT_TIPS):s.push(Se.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{switch(e.PushType){case S.CONV_MARK_UPDATED:s.push(Se.CONVERSATION_MARK_UPDATED);break;case S.CONV_GROUP_ADDED:s.push(Se.CONVERSATION_GROUP_ADD);break;case S.CONV_GROUP_DELETED:s.push(Se.CONVERSATION_GROUP_DELETED);break;case S.CONV_GROUP_UPDATED:s.push(Se.CONVERSATION_GROUP_UPDATED);break;default:s.push(Se.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Se.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Se.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Se.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Se.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Se.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Se.ALL_MESSAGE_READ}];function Re(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],i=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=Ae.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(!e)return null;let s=[];"function"==typeof e.subTypeParser?s=e.subTypeParser(t):e.subType&&(s=e.subType),Array.isArray(s)?s.forEach(e=>{i.push({type:Te.SERVER_PUSH_MESSAGE+":"+e,data:t})}):i.push({type:Te.SERVER_PUSH_MESSAGE+":"+s,data:t})}),i}!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"}(Te=Te||{});let De={[Te.SERVER_PUSH_MESSAGE]:Re,[Te.SERVER_PUSH_MESSAGE_MULTIPLE]:Re,[Te.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},be=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new Me,this._innerEventEmitter=new Me,this.InnerEventSubType=Se}subscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,i)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(De).includes(t)){let e=null==(t=De[t])?void 0:t.call(De,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,i)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};class Ne{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t;try{null!=(t=this._socket)&&t.send(e)}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,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 Le{connectSocket(e){return this._socket=q.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),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)}}let Pe="CONNECT",we="SEND",Ge="DISCONNECT",Ue="OPEN",ke="MESSAGE",Fe="CLOSE",$e="ERROR",qe="SEND_FAIL";class xe{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){var 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:Pe,url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:we,data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:r,onClose:i,onError:n,onSendFail:o}=e;if(this._worker){let s={[Ue]:t,[ke]:r,[Fe]:i,[$e]:n,[qe]:o};this._onSendFail=o,this._worker.onmessage=e=>{var t=((null==e?void 0:e.data)||{})["type"];"function"==typeof s[t]&&null!=(t=s[t])&&t.call(s,null==e?void 0:e.data)}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Ge}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Ve,Be=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return G?b?my.getStorageSync({key:e}).data:q.getStorageSync(e):this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){var 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){G?b?my.setStorageSync({key:e,data:JSON.stringify(t)}):q.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}};!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(Ve=Ve||{});class je{constructor(e){this._url="",this._readyState=Ve.DISCONNECTED,this._url=e,this._id=c(),this._emitter=new Me,y||L||R?this._socket=new Le:this._canUseWebWorker()?this._socket=new xe:this._socket=new Ne,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Ve.CONNECTED,Ve.CONNECTING].includes(this._readyState)||(this._readyState=Ve.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Ve.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Ve.CONNECTED,Ve.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===Ve.CONNECTED}disconnect(){this._readyState=Ve.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Ve.CONNECTING&&(this._readyState=Ve.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Ve.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Ve.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Ve.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(){var t=Be.get("cloudConfig")||{};return(e(t.isWorkerEnabled)||"1"===t.isWorkerEnabled)&&ie}}let Ke="CHINA",He="OVERSEA",We="SINGAPORE",Ye="KOREA",ze="GERMANY",Je="IND",Qe="JPN",Xe="USA",Ze="INDONESIA",et={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"}},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"}}},st={[We]:[[2e7,3e7],[172e7,173e7]],[Ye]:[[3e7,4e7],[173e7,174e7]],[ze]:[[4e7,5e7],[174e7,175e7]],[Je]:[[5e7,6e7],[175e7,176e7]],[Qe]:[[6e7,7e7],[176e7,177e7]],[Xe]:[[7e7,8e7],[177e7,178e7]],[Ze]:[[8e7,9e7],[178e7,179e7]]};function nt(t){var e;if(null!=(e=Be.get("instance"))&&e.oversea)return He;for(let e of Object.keys(st))for(var[s,r]of st[e])if(t>=s&&t<r)return e;return Ke}var ot,it="4.1.2";!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"}(ot=ot||{});let rt=ot.INITIAL;function at(){var e=Math.random();return 0===e?at():e}function ct(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:i}=Be.get("instance"),n=at(),o=ue(),a=function(){var e=ue();let t=-1;return"ios"===e?t=Y||-1:"android"===e&&(t=J||-1),t}(),r=(s={sdkappid:r,instanceid:i,random:n,platform:B,host:o,version:a,sdkversion:it},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}function ut(e){var{sdkAppId:t,testEnv:s}=Be.get("instance"),t=nt(t);if(s)return ct(et.TEST[t].DEFAULT,{isBinary:e});let r=et.PRODUCTION[t],i=$&&r.ANYCAST,n=$,o=!!r.BACKUP_CN;return ct({[ot.INITIAL]:()=>(rt=ot.DEFAULT,r.DEFAULT),[ot.DEFAULT]:()=>(rt=ot.IPV6,r.IPV6),[ot.IPV6]:()=>(rt=ot.BACKUP,r.BACKUP),[ot.BACKUP]:()=>{return n?(rt=ot.BACKUP_WEB_ONLY,e=r.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):o?(rt=ot.BACKUP_CN,r.BACKUP_CN):i?(rt=ot.ANYCAST,r.ANYCAST):r.DEFAULT;var e,t},[ot.BACKUP_WEB_ONLY]:()=>o?(rt=ot.BACKUP_CN,r.BACKUP_CN):i?(rt=ot.ANYCAST,r.ANYCAST):r.DEFAULT,[ot.BACKUP_CN]:()=>(rt=i?ot.ANYCAST:ot.DEFAULT,r[rt]),[ot.ANYCAST]:()=>(rt=ot.DEFAULT,r.ANYCAST="",r.DEFAULT)}[rt](),{isBinary:e})}var lt=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){var s=Date.now();this._timeOffsetWithServer=t+(s-e)-s}};let dt=16;var ht=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){var t=e["id"];this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){var{id:e,callback:t,context:s,isOnce:r=!1,intervalMs:i=dt}=e,n=Math.max(i,dt);return{id:e,nextExecuteTime:Date.now()+n,intervalMs:i,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.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);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var 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 gt(t){var s=[];for(let e=0;e<t.length;e+=1){var r,i=t.charCodeAt(e);55296<=i&&i<=56319?(r=t.charCodeAt(++e)-56320+(i-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):i<=127?s.push(i):i<=2047?s.push(192|i>>6,128|63&i):s.push(224|i>>12,128|i>>6&63,128|63&i)}return new Uint8Array(s)}function pt(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=pt(e[t]));return s}function _t(e,t){if(h.includes(e))return 0;var s=gt(JSON.stringify(t));let r=4294967295;var i=s["length"];for(let e=0;e<i;e++){r^=s[e];for(let e=0;e<8;e++)1&~r?r>>>=1:r=r>>>1^3988292384}return(4294967295^r)>>>0}function mt(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=Be.get("login")||{},t=Be.get("instance")||{},{servcmd:r,ver:"v4",platform:B,websdkappid:537048168,websdkversion:"1.7.3",a2:i.a2Key||void 0,tinyid:i.tinyID||void 0,status_instid:i.statusInstanceId||0,sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:i.a2Key?void 0:i.userId,usersig:i.a2Key?void 0:i.userSig,sdkability:75689843,sdkability_ext:l(""),cappid:t.applicationID||0,tjgID:"",seq:It(),cs:0}),i=pt(s);return r.cs=_t(e,i),{head:r,body:i}}function vt(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=Be.get("login")||{},t=Be.get("instance")||{},{servcmd:r,ver:"v4",platform:B,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:i.statusInstanceId||0,sdkability:75689843,sdkability_ext:l(""),cappid:t.applicationID||0,seq:It(),cs:0}),i=pt(s);return r.cs=_t(e,i),{head:r,body:i}}let ft=c();function It(){return ft=ft<2415919103?ft+1:c()}function Et(){var e=Be.get("login")||{},t=Be.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"4.1.2",tiny_id:Number(e.tinyID),user_id:e.userId,platform:B,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var St,Ot,Ct=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=Be.get("login")||{},t=Be.get("instance")||{},{servcmd:r,ver:"v4",platform:B,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:i.userId,usersig:i.userSig,status_instid:i.statusInstanceId||0,sdkability:75689843,sdkability_ext:l(""),cappid:t.applicationID||0,seq:It(),cs:0}),i=pt(s);return r.cs=_t(e,i),{head:r,body:i}},generateProtocolData:mt,generateSSOLogProtocolData:vt,generateSequence:It,getCommonHead:Et,taskScheduler:ht,timeManager:lt});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(St=St||{});let Mt={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 yt{constructor(e){this.level=St.info,this._canSendLog=!0,this._logCreatedAt=lt.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();var{method:e,eventType:t=0,message:s="",costTime:r=0,error:i,moreMessage:n=""}=e||{};this.eventType=t,this.method=e,this.message=s,this.costTime=r,this.moreMessage=n,i&&this.setError(i)}setMoreMessage(e){this.moreMessage=this.moreMessage+" "+e}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=lt.getTimeOffsetWithServer()}end(e=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=lt.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),e)&&this._ssoLogModule.uploadSSOLogData()}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=Be.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=St.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(Mt).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{Mt[e]&&(t[Mt[e]]=this[e])}),t}_getUiPlatform(){var e,t=null==(e=Be.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null==(e=Be.get("instance"))?void 0:e.sdkEdition}}!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(Ot=Ot||{});var At=Ot;let Tt=20,Rt=6e4,Dt=[4,5,6],bt=[],Nt=[],Lt="report-logger";var Pt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Tt,this._maxThreshold=100,this._waitingTime=Rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=g.DEBUG,this._throttleConfig={global:{throttleTime:I,maxCount:E},single:{throttleTime:v,maxCount:f}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,be.subscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ht.addTask({id:Lt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=Tt,evt_rpt_waiting:t=Rt,evt_rpt_level:s=Dt,evt_rpt_sdkappid_bl:r=bt,evt_rpt_tinyid_wl:i=Nt,evt_rpt_global_throttle_time:n=I,evt_rpt_global_throttle_count:o=E,evt_rpt_single_throttle_time:a=v,evt_rpt_single_throttle_count:l=f}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=i,this._throttleConfig={global:{throttleTime:n,maxCount:o},single:{throttleTime:a,maxCount:l}}}createSSOLogData(e){var t=new yt(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){[g.DEBUG,g.ERROR,g.INFO,g.NONE,g.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(g.DEBUG,e,t,s)}info(e,t="",s){this._log(g.INFO,e,t,s)}warn(e,t="",s){this._log(g.WARN,e,t,s)}error(e,t="",s){this._log(g.ERROR,e,t,s)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&0<this._logQueue.length&&this.uploadSSOLogData()}uploadSSOLogData(){return de(this,void 0,void 0,function*(){var e,t;0!==this._logQueue.length&&(t=this._logQueue.slice(),t=this._filterLogs(t),this._logQueue=[],0===t.length||ve((t={Header:Et(),Event:t}).Header.user_id)||(e=(t=vt({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void es.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(y){var s=null==(t=null==(e=wx.getAccountInfoSync)?void 0:e.call(wx))?void 0:t.miniProgram;if(s){let{appId:e,envVersion:t}=s;Be.set("instance",{appId:e,envVersion:t})}}else $&&Be.set("instance",{href:window.location.href})}_filterLogs(e){var t=(Be.get("login")||{})["tinyID"],s=(Be.get("instance")||{})["sdkAppId"];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(){var 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){var 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!==g.NONE}_shouldReport(e){return this._reportLevel.includes(m[e])}_formatLog(e,t,s){var r=new Date,r=`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:`+r.getMilliseconds(),e=`<${g[e]}>`;return ee||G?[p+` [${r}] ${e} [${t}] `+s]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",p,"",`[${r}] ${e} [${t}] `+s]}_log(e,t,s,r){if(this._shouldLog(e)){var i=this._formatLog(e,t,s);if(_[e].apply(console,i),this._shouldReport(e)){let e=this._getThrottleKey(t,s,r);this._checkThrottle(e)||this.createSSOLogData(Object.assign(Object.assign({message:s},r),{method:t})).end()}}}_getThrottleKey(e,t,s){var e=""+e+t+Ie(Object.assign(Object.assign({},s),{costTime:""})),r=gt(JSON.stringify(e));let i=4294967295;var n=r["length"];for(let e=0;e<n;e++){i^=r[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"),ht.removeTask(Lt),be.unSubscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Tt,this._maxThreshold=100,this._waitingTime=Rt,this._logQueue=[],this._logLevel=g.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};let wt=15e3,Gt="Channel",Ut="channel_schedule_task",kt="channel_reconnect_task",Ft="connected",$t="connecting",qt="disconnected",xt=1e3,Vt="network_status_change",Bt="activity_status_change",jt="send_fail",Kt="reconnect_failed",Ht="socket_error",Wt="socket_close";function Yt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zt(e){return(zt="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})(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 Qt,os,Xt={exports:{}},Zt=(Qt||(Xt.exports=function s(r,i,n){function o(t,e){if(!i[t]){if(!r[t]){if(!e&&Jt)return Jt(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=i[t]={exports:{}};r[t][0].call(e.exports,function(e){return o(r[t][1][e]||e)},e,e.exports,s,r,i,n)}return i[t].exports}for(var a=Jt,e=0;e<n.length;e++)o(n[e]);return o}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,i=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var i=r.shift();if(i){if("object"!=zt(i))throw new TypeError(i+"must be non-object");for(var n in i)t=i,s=n,Object.prototype.hasOwnProperty.call(t,s)&&(e[n]=i[n])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,i){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),i);else for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){for(var t,s,r,i,n=t=0,o=e.length;n<o;n++)t+=e[n].length;for(i=new Uint8Array(t),n=s=0,o=e.length;n<o;n++)r=e[n],i.set(r,s),s+=r.length;return i}}),n={arraySet:function(e,t,s,r,i){for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,i)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(r)},{}],2:[function(e,t,s){var l=e("./common"),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var u=new l.Buf8(256),r=0;r<256;r++)u[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,l.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}u[254]=u[254]=1,s.string2buf=function(e){for(var t,s,r,i,n=e.length,o=0,a=0;a<n;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new l.Buf8(o),a=i=0;i<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[i++]=s:(s<2048?t[i++]=192|s>>>6:(s<65536?t[i++]=224|s>>>12:(t[i++]=240|s>>>18,t[i++]=128|s>>>12&63),t[i++]=128|s>>>6&63),t[i++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new l.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,i,n=t||e.length,o=new Array(2*n),a=s=0;a<n;)if((r=e[a++])<128)o[s++]=r;else if(4<(i=u[r]))o[s++]=65533,a+=i-1;else{for(r&=2===i?31:3===i?15:7;1<i&&a<n;)r=r<<6|63&e[a++],i--;1<i?o[s++]=65533:r<65536?o[s++]=r:(r-=65536,o[s++]=55296|r>>10&1023,o[s++]=56320|1023&r)}return c(o,s)},s.utf8border=function(e,t){for(var s=(t=(t=t||e.length)>e.length?e.length:t)-1;0<=s&&128==(192&e[s]);)s--;return!(s<0||0===s)&&s+u[e[s]]>t?s:t}},{"./common":Qt=1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var i=65535&e,n=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;n=n+(i=i+t[r++]|0)|0,--o;);i%=65521,n%=65521}return i|n<<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 a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var i=a,n=r+s;e^=-1;for(var o=r;o<n;o++)e=e>>>8^i[255&(e^t[o])];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,r,i,n,o,a,l=e.state,u=e.next_in,c=e.input,d=u+(e.avail_in-5),h=e.next_out,g=e.output,p=h-(t-e.avail_out),_=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,I=l.wnext,S=l.window,E=l.hold,C=l.bits,M=l.lencode,y=l.distcode,A=(1<<l.lenbits)-1,O=(1<<l.distbits)-1;e:do{for(C<15&&(E+=c[u++]<<C,C+=8,E+=c[u++]<<C,C+=8),s=M[E&A];;){if(E>>>=r=s>>>24,C-=r,0==(r=s>>>16&255))g[h++]=65535&s;else{if(!(16&r)){if(!(64&r)){s=M[(65535&s)+(E&(1<<r)-1)];continue}if(32&r){l.mode=12;break e}e.msg="invalid literal/length code",l.mode=30;break e}for(i=65535&s,(r&=15)&&(C<r&&(E+=c[u++]<<C,C+=8),i+=E&(1<<r)-1,E>>>=r,C-=r),C<15&&(E+=c[u++]<<C,C+=8,E+=c[u++]<<C,C+=8),s=y[E&O];;){if(E>>>=r=s>>>24,C-=r,!(16&(r=s>>>16&255))){if(!(64&r)){s=y[(65535&s)+(E&(1<<r)-1)];continue}e.msg="invalid distance code",l.mode=30;break e}if(n=65535&s,C<(r&=15)&&(E+=c[u++]<<C,(C+=8)<r)&&(E+=c[u++]<<C,C+=8),m<(n+=E&(1<<r)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(E>>>=r,C-=r,(r=h-p)<n){if(f<(r=n-r)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=S,(o=0)===I){if(o+=v-r,r<i){for(i-=r;g[h++]=S[o++],--r;);o=h-n,a=g}}else if(I<r){if(o+=v+I-r,(r-=I)<i){for(i-=r;g[h++]=S[o++],--r;);if(o=0,I<i){for(i-=r=I;g[h++]=S[o++],--r;);o=h-n,a=g}}}else if(o+=I-r,r<i){for(i-=r;g[h++]=S[o++],--r;);o=h-n,a=g}for(;2<i;)g[h++]=a[o++],g[h++]=a[o++],g[h++]=a[o++],i-=3;i&&(g[h++]=a[o++],1<i)&&(g[h++]=a[o++])}else{for(o=h-n;g[h++]=g[o++],g[h++]=g[o++],g[h++]=g[o++],2<(i-=3););i&&(g[h++]=g[o++],1<i)&&(g[h++]=g[o++])}break}}break}}while(u<d&&h<_);u-=i=C>>3,E&=(1<<(C-=i<<3))-1,e.next_in=u,e.next_out=h,e.avail_in=u<d?d-u+5:5-(u-d),e.avail_out=h<_?_-h+257:257-(h-_),l.hold=E,l.bits=C}},{}],8:[function(e,t,s){var N=e("../utils/common"),L=e("./adler32"),P=e("./crc32"),G=e("./inffast"),w=e("./inftrees"),U=0,k=-2,F=1,r=852,i=592;function q(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function n(){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 o(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=F,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(r),t.distcode=t.distdyn=new N.Buf32(i),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):k}function l(e,t){var s,r;return!e||!e.state||(r=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t))?k:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=s,r.wbits=t,a(e))}function u(e,t){var s;return e?(s=new n,(e.state=s).window=null,(s=l(e,t))!==U&&(e.state=null),s):k}var x,V,B=!0;function j(e,t,s,r){var i,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(i=e.wsize-e.wnext)&&(i=r),N.arraySet(e.window,t,s-r,i,e.wnext),(r-=i)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=i,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=i))),0}s.inflateReset=a,s.inflateReset2=l,s.inflateResetKeep=o,s.inflateInit=function(e){return u(e,15)},s.inflateInit2=u,s.inflate=function(e,t){var s,r,i,n,o,a,l,u,c,d,h,g,p,_,m,v,f,I,S,E,C,M,y,A,O=0,T=new N.Buf8(4),R=[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 k;12===(s=e.state).mode&&(s.mode=13),o=e.next_out,i=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,d=a,h=l,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(2&s.wrap&&35615===u)T[s.check=0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0),c=u=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&u)<<8)+(u>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&u))e.msg="unknown compression method",s.mode=30;else{if(c-=4,C=8+(15&(u>>>=4)),0===s.wbits)s.wbits=C;else if(C>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<C,e.adler=s.check=1,s.mode=512&u?10:12,c=u=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(s.flags=u,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=u>>8&1),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.head&&(s.head.time=u),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,T[2]=u>>>16&255,T[3]=u>>>24&255,s.check=P(s.check,T,4,0)),c=u=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.head&&(s.head.xflags=255&u,s.head.os=u>>8),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.length=u,s.head&&(s.head.extra_len=u),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&((g=a<(g=s.length)?a:g)&&(s.head&&(C=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),N.arraySet(s.head.extra,r,n,g,C)),512&s.flags&&(s.check=P(s.check,r,g,n)),a-=g,n+=g,s.length-=g),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(g=0;C=r[n+g++],s.head&&C&&s.length<65536&&(s.head.name+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=P(s.check,r,g,n)),a-=g,n+=g,C)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===a)break e;for(g=0;C=r[n+g++],s.head&&C&&s.length<65536&&(s.head.comment+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=P(s.check,r,g,n)),a-=g,n+=g,C)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=u=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===a)break e;a--,u+=r[n++]<<c,c+=8}e.adler=s.check=q(u),c=u=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,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)u>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:D=b=void 0;var D,b=s;if(B){for(x=new N.Buf32(512),V=new N.Buf32(32),D=0;D<144;)b.lens[D++]=8;for(;D<256;)b.lens[D++]=9;for(;D<280;)b.lens[D++]=7;for(;D<288;)b.lens[D++]=8;for(w(1,b.lens,0,288,x,0,b.work,{bits:9}),D=0;D<32;)b.lens[D++]=5;w(2,b.lens,0,32,V,0,b.work,{bits:5}),B=!1}if(b.lencode=x,b.lenbits=9,b.distcode=V,b.distbits=5,s.mode=20,6!==t)break;u>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}u>>>=2,c-=2}break;case 14:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if((65535&u)!=(u>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&u,c=u=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(g=s.length){if(0===(g=l<(g=a<g?a:g)?l:g))break e;N.arraySet(i,r,n,g,o),a-=g,n+=g,l-=g,o+=g,s.length-=g}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(s.nlen=257+(31&u),u>>>=5,c-=5,s.ndist=1+(31&u),u>>>=5,c-=5,s.ncode=4+(15&u),u>>>=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===a)break e;a--,u+=r[n++]<<c,c+=8}s.lens[R[s.have++]]=7&u,u>>>=3,c-=3}for(;s.have<19;)s.lens[R[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,y={bits:s.lenbits},M=w(0,s.lens,0,19,s.lencode,0,s.work,y),s.lenbits=y.bits,M){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(;v=(O=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&O,!((m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(f<16)u>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(A=m+2;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}C=s.lens[s.have-1],g=3+(3&u),u>>>=2,c-=2}else if(17===f){for(A=m+3;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}C=0,g=3+(7&(u>>>=m)),u>>>=3,c=c-m-3}else{for(A=m+7;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}C=0,g=11+(127&(u>>>=m)),u>>>=7,c=c-m-7}if(s.have+g>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;g--;)s.lens[s.have++]=C}}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,y={bits:s.lenbits},M=w(1,s.lens,0,s.nlen,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,y={bits:s.distbits},M=w(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,y),s.distbits=y.bits,M){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<=a&&258<=l){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,G(e,h),o=e.next_out,i=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(O=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&O,!((m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(v&&!(240&v)){for(I=m,S=v,E=f;v=(O=s.lencode[E+((u&(1<<I+S)-1)>>I)])>>>16&255,f=65535&O,!(I+(m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,s.length=f,0===v){s.mode=26;break}if(32&v){s.back=-1,s.mode=12;break}if(64&v){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&v,s.mode=22;case 22:if(s.extra){for(A=s.extra;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.length+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(O=s.distcode[u&(1<<s.distbits)-1])>>>16&255,f=65535&O,!((m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(!(240&v)){for(I=m,S=v,E=f;v=(O=s.distcode[E+((u&(1<<I+S)-1)>>I)])>>>16&255,f=65535&O,!(I+(m=O>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,64&v){e.msg="invalid distance code",s.mode=30;break}s.offset=f,s.extra=15&v,s.mode=24;case 24:if(s.extra){for(A=s.extra;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.offset+=u&(1<<s.extra)-1,u>>>=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===l)break e;if(s.offset>(g=h-l)){if((g=s.offset-g)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}p=g>s.wnext?(g-=s.wnext,s.wsize-g):s.wnext-g,g>s.length&&(g=s.length),_=s.window}else _=i,p=o-s.offset,g=s.length;for(l-=g=l<g?l:g,s.length-=g;i[o++]=_[p++],--g;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;i[o++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[n++]<<c,c+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?P:L)(s.check,i,h,o-h)),h=l,(s.flags?u:q(u))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=u=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}c=u=0}s.mode=29;case 29:M=1;break e;case 30:M=-3;break e;case 31:return-4;default:return k}return e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,(s.wsize||h!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&j(e,e.output,e.next_out,h-e.avail_out)?(s.mode=31,-4):(d-=e.avail_in,h-=e.avail_out,e.total_in+=d,e.total_out+=h,s.total+=h,s.wrap&&h&&(e.adler=s.check=(s.flags?P:L)(s.check,i,h,e.next_out-h)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),M=(0==d&&0===h||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&L(1,t,r,0)!==s.check?-3:j(e,t,r,r)?(s.mode=31,-4):(s.havedict=1,U)},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var G=e("../utils/common"),w=[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],U=[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],k=[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],F=[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,r,i,n,o,a){for(var l,u,c,d,h,g,p,_,m,v=a.bits,f=0,I=0,S=0,E=0,C=0,M=0,y=0,A=0,O=0,T=0,R=null,D=0,b=new G.Buf16(16),N=new G.Buf16(16),L=null,P=0,f=0;f<=15;f++)b[f]=0;for(I=0;I<r;I++)b[t[s+I]]++;for(C=v,E=15;1<=E&&0===b[E];E--);if(E<C&&(C=E),0===E)i[n++]=20971520,i[n++]=20971520,a.bits=1;else{for(S=1;S<E&&0===b[S];S++);for(C<S&&(C=S),f=A=1;f<=15;f++)if((A=(A<<1)-b[f])<0)return-1;if(0<A&&(0===e||1!==E))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+b[f];for(I=0;I<r;I++)0!==t[s+I]&&(o[N[t[s+I]]++]=I);if(g=0===e?(R=L=o,19):1===e?(R=w,D-=257,L=U,P-=257,256):(R=k,L=F,-1),f=S,h=n,y=I=T=0,c=-1,d=(O=1<<(M=C))-1,1===e&&852<O||2===e&&592<O)return 1;for(;;){for(m=o[I]<g?(_=0,o[I]):o[I]>g?(_=L[P+o[I]],R[D+o[I]]):(_=96,0),l=1<<(p=f-y),S=u=1<<M;i[h+(T>>y)+(u-=l)]=p<<24|_<<16|m,0!==u;);for(l=1<<f-1;T&l;)l>>=1;if(0!==l?T=(T&l-1)+l:T=0,I++,0==--b[f]){if(f===E)break;f=t[s+o[I]]}if(C<f&&(T&d)!==c){for(h+=S,A=1<<(M=f-(y=0===y?C:y));M+y<E&&!((A-=b[M+y])<=0);)M++,A<<=1;if(O+=1<<M,1===e&&852<O||2===e&&592<O)return 1;i[c=T&d]=C<<24|M<<16|h-n}}0!==T&&(i[h+T]=f-y<<24|64<<16),a.bits=C}return 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 d=e("./zlib/inflate"),h=e("./utils/common"),g=e("./utils/strings"),p=e("./zlib/constants"),r=e("./zlib/messages"),i=e("./zlib/zstream"),n=e("./zlib/gzheader"),_=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options,e=(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 i,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==p.Z_OK)throw new Error(r[e]);if(this.header=new n,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=g.string2buf(t.dictionary):"[object ArrayBuffer]"===_.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==p.Z_OK)throw new Error(r[e])}function a(e,t){t=new o(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}o.prototype.push=function(e,t){var s,r,i,n,o,a=this.strm,l=this.options.chunkSize,u=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?p.Z_FINISH:p.Z_NO_FLUSH,"string"==typeof e?a.input=g.binstring2buf(e):"[object ArrayBuffer]"===_.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new h.Buf8(l),a.next_out=0,a.avail_out=l),(s=(s=d.inflate(a,p.Z_NO_FLUSH))===p.Z_NEED_DICT&&u?d.inflateSetDictionary(this.strm,u):s)===p.Z_BUF_ERROR&&!0===c&&(s=p.Z_OK,c=!1),s!==p.Z_STREAM_END&&s!==p.Z_OK)return this.onEnd(s),!(this.ended=!0)}while(!a.next_out||0!==a.avail_out&&s!==p.Z_STREAM_END&&(0!==a.avail_in||r!==p.Z_FINISH&&r!==p.Z_SYNC_FLUSH)||("string"===this.options.to?(i=g.utf8border(a.output,a.next_out),n=a.next_out-i,o=g.buf2string(a.output,i),a.next_out=n,a.avail_out=l-n,n&&h.arraySet(a.output,a.output,i,n,0),this.onData(o)):this.onData(h.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(c=!0),(0<a.avail_in||0===a.avail_out)&&s!==p.Z_STREAM_END);return(r=s===p.Z_STREAM_END?p.Z_FINISH:r)===p.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===p.Z_OK):r!==p.Z_SYNC_FLUSH||(this.onEnd(p.Z_OK),!(a.avail_out=0))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===p.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=o,s.inflate=a,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,a(e,t)},s.ungzip=a},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")),Xt.exports),es=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=xt,this._currentConnectState=Ft,this._beforeSendInterceptors=[]}init(){ht.addTask({id:Ut,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:r}=Be.get("instance"),i=nt(t);let n="";return s?n=et.TEST[i].DEFAULT:r?(n=et.PRODUCTION[i].DEFAULT,rt=ot.DEFAULT):n=et.PRODUCTION[i].INITIAL.replace("*",""+t),ct(n,{isBinary:e})}(this._isBinarySupported),be.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),be.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:i=wt,canResend:n=!0}=t||{};if(ve(e))return Pt.warn("sendPacket",Gt+".sendPacket: packet is empty "),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===qt&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:jt});var o=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=Ee();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:i,canResend:n})}t=this._isBinarySupported?gt(o).buffer:o;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new je(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),t=Gt+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t})}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=Gt+".disconnect socketID:"+e;this._ssoLog({method:"disconnect",message:e}),this._removeEventListeners(),null!=(e=this._socketAdapter)&&e.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(Gt+".dispose"),ht.removeTask(Ut),ht.removeTask(kt),be.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),be.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=xt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(var t of this._beforeSendInterceptors){var{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){var e=this._currentConnectState===$t&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return de(this,void 0,void 0,function*(){var e=`${Gt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=ut(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Kt}),console.warn(Gt+".reconnect failed: ",e)}}})}_addEventListeners(){var e;null!=(e=this._socketAdapter)&&e.on("connect",this._onConnect,this),null!=(e=this._socketAdapter)&&e.on("message",this._onMessage,this),null!=(e=this._socketAdapter)&&e.on("close",this._onClose,this),null!=(e=this._socketAdapter)&&e.on("error",this._onError,this),null!=(e=this._socketAdapter)&&e.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e;null!=(e=this._socketAdapter)&&e.off("connect",this._onConnect,this),null!=(e=this._socketAdapter)&&e.off("message",this._onMessage,this),null!=(e=this._socketAdapter)&&e.off("close",this._onClose,this),null!=(e=this._socketAdapter)&&e.off("error",this._onError,this),null!=(e=this._socketAdapter)&&e.off("sendFail",this._onSendFail,this)}_onClose(e){var{socketId:e,event:t}=e||{},s=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,s=`${Gt}.onClose closeSocketID: ${e} currentSocketID: ${this._connectionId} connectionDuration: ${s} code: ${null==t?void 0:t.code} reason: `+(null==t?void 0:t.reason);this._ssoLog({method:"onClose",message:s}),e===this._connectionId&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Wt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=`${Gt}.onError sourceSocketID: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+JSON.stringify(t);this._ssoLog({method:"onError",message:t}),e===this._connectionId&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Ht}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=`${Gt}.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(t){let s,e;this._updateHeartbeatTime();try{s=this._isBinarySupported?(this._isCompressedData(t.data)?e=>{var t=new Uint8Array(e).slice(4);let s;try{s=Zt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var i=new Uint8Array(e);let n="",o=0;for(var a=i["length"];o<a;){let t=i[o],s=0,r=0;if(t<=127?(s=0,r=255&t):t<=223?(s=1,r=31&t):t<=239?(s=2,r=15&t):t<=244&&(s=3,r=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=i[o+e+1],r=r<<6|63&t;else r=65533,s=a-o;n+=String.fromCodePoint(r),o+=s+1}return n})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return void this._ssoLog({method:"jsonParseError",message:e})}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:i}=(null==e?void 0:e.body)||{},n=(null==(n=null==e?void 0:e.body)?void 0:n.ErrorCode)||r,r=(null==(r=null==e?void 0:e.body)?void 0:r.ErrorInfo)||i,i=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(i);this._pendingRequests.delete(i),n&&0!==n?(be.emitInnerEvent("error",{errorCode:n,errorInfo:r}),s({errorCode:n,errorInfo:r})):t(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),be.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;Pt.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:i,reject:n,timeout:o}=e;if(r){this._pendingRequests.set(t,{resolve:i,reject:n,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:r});let e=this._isBinarySupported?gt(s).buffer:s;null!=(i=this._socketAdapter)&&i.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=Gt+`.onConnect cost:${s} ms. socketID:${e} res:`+JSON.stringify(t);if(this._ssoLog({method:"onConnect",message:s}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){let e=Gt+".reconnect success";this._ssoLog({method:"reconnectSuccess",message:e}),be.emitInnerEvent(At.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ft,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=mt({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return de(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var e;return(null==(e=this._socketAdapter)?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return de(this,void 0,void 0,function*(){var e,t=mt({servcmd:"heartbeat.alive",data:{}});try{let e=""+t.head.seq+t.head.servcmd;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){var s=null==(e=Be.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=Gt+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return de(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=L?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=Gt+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),e);t&&"none"!==e?this._handleConnectStateChange({state:Ft,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Vt}):this._handleConnectStateChange({state:qt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Vt})}isPrivateNetWork(){var e=Be.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:r}=e,r=`${Gt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+r;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:r}),s&&(Pt.info("_handleConnectStateChange",` from ${this._currentConnectState} to `+e),be.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===qt)&&be.emitInnerEvent(At.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),ht.addTask({id:kt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}_handleActivityStatusChange(e){var t=null==(t=null==(t=this._socketAdapter)?void 0:t._ws)?void 0:t.readyState,e=`${Gt}.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),3===t&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Bt})}_resetReconnectDelay(){Pt.debug(Gt+"._resetReconnectDelay"),ht.removeTask(kt);var e=null==(e=Be.get("activityMonitor"))?void 0:e.isActive;this._intendedDelay=e?xt:1e3}_scheduleReconnectWithBackoff(){var e=null==(e=Be.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(xt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=Gt+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;Pt.debug(e),this.reconnect(),ht.updateTaskInterval(kt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Pt.info(e,t)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){de(this,void 0,void 0,function*(){var e=t.split("/")[2];if(e.startsWith("ws")){e=`https://${e}/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield me({method:"GET",url:e,data:{}})}catch(e){Pt.warn("diagnoseBySSO","diagnoseBySSO failed. error:"+e.message)}}})}(this._url),function(t){de(this,void 0,void 0,function*(){var e=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield me({method:"GET",url:e,data:{}})}catch(e){Pt.warn("diagnoseByCDN', 'diagnoseByCDN failed. error:"+e.message)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(var[e,t]of this._pendingRequests.entries()){var{reject:t,timestamp:s,timeout:r}=t;Date.now()-s>=r&&(this._pendingRequests.delete(e),3e4<=Date.now()-this._lastDiagnoseAt&&this._diagnose(),t({errorCode:ge,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=Be.get("instance"))&&e.devMode||(e=ue(),b)||y&&"windows"===e||L)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let ts={init:function(e){Be.set("instance",e),es.init()},destroy:function(){es.dispose(),Be.clear(),ht.dispose()},notificationCenter:be,channel:es,store:Be,ssoLog:Pt,utils:Ce,common:Ct,constants:C},ss=e=>"function"==typeof e;function ns(t,s,r){let i=r||[];var e,n;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!i.includes(e)),n=Object.keys(s).filter(e=>!i.includes(e)),e.length===n.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?ns(t[e],s[e],r):t[e]===s[e]))}!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"}(os=os||{});var is,rs=os;!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"}(is=is||{});var as,hs,ps,cs=is,us=(!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"}(as=as||{}),as);let ls=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),ds={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"},gs=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(hs=hs||{}),{modify:cs.MESSAGE_MODIFIED,delete:cs.MESSAGE_DELETED,revoke:cs.MESSAGE_REVOKED}),_s=(!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(ps=ps||{}),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ds),{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:hs,Direction:ps})),ms={[gs.modify]:cs.TOPIC_MESSAGE_MODIFIED,[gs.delete]:cs.TOPIC_MESSAGE_DELETED,[gs.revoke]:cs.TOPIC_MESSAGE_REVOKED},vs={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"},fs=Object.assign({},vs),Is={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Es=Object.assign(Object.assign(Object.assign(Object.assign({},Is),{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"}),Ss=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"}),Cs={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},Ms={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ys={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},Os=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Cs),{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:Ms,GROUP_TIPS_OPERATION_TYPE:ys}),As=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ls),_s),fs),Es),Ss),Os),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),Ts={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},Rs={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},Ds={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"},bs={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"},Ns={[Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:bs.USER_STATUS_UPDATE},{stepId:bs.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CONVERSATION_RECOVER},{stepId:bs.HISTORY_MESSAGE_RECOVER,dependency:bs.CONVERSATION_RECOVER},{stepId:bs.BLACKLIST_RECOVER},{stepId:bs.FRIEND_RECOVER},{stepId:bs.GROUP_REVOKED_NOTICE_RECOVER,dependency:bs.HISTORY_MESSAGE_RECOVER},{stepId:bs.GROUP_TIPS_RECOVER,dependency:bs.HISTORY_MESSAGE_RECOVER},{stepId:bs.TOPIC_REQUEST_INFO_RESET},{stepId:bs.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_RECOVER]},{stepId:bs.EMIT_C2C_MESSAGE_EVENT,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[Ds.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:bs.COMMERCIAL_CONFIG_UPDATE},{stepId:bs.CLOUD_CONFIG_SYNC},{stepId:bs.USER_PROFILE_SYNC},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.FRIEND_AND_BLACKLIST_SYNC},{stepId:bs.GROUP_LIST_SYNC},{stepId:bs.CONVERSATION_LIST_SYNC},{stepId:bs.SIGNALING_MESSAGE_RECOVER,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC]},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_LIST_SYNC]},{stepId:bs.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[bs.GROUP_LIST_SYNC,bs.CONVERSATION_LIST_SYNC]},{stepId:bs.CONVERSATION_GROUP_LIST_SYNC},{stepId:bs.CONVERSATION_GROUP_UPDATE,dependency:[bs.CONVERSATION_LIST_SYNC,bs.CONVERSATION_GROUP_LIST_SYNC]},{stepId:bs.QUALITY_REPORT}],[Ds.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:bs.HANDLE_C2C_NEW_MESSAGE},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_C2C_NEW_MESSAGE},{stepId:bs.EMIT_C2C_MESSAGE_EVENT,dependency:[bs.HANDLE_C2C_NEW_MESSAGE,bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC]}],[Ds.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.UPDATE_GROUP_NEXT_SEQUENCE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.EMIT_GROUP_MESSAGE_EVENT,dependency:[bs.HANDLE_GROUP_NEW_MESSAGE,bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Ds.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:bs.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_TIPS_NOTIFICATION}]},Ls={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Ps={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},ws=["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","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var Us,ks,Fs,Gs=Object.freeze({__proto__:null,ERROR_CODE:Ts,InnerEvent:cs,NEED_LOG_API:ws,OuterConstant:As,OuterEvent:rs,QUALITY_METRICS:Ls,SDK_EDITION:Rs,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Ps,SignalingEvent:us,WORKFLOW_DEFINITIONS:Ns,WORKFLOW_NAME:Ds,WORKFLOW_STEP:bs});!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Us=Us||{}),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(ks=ks||{}),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(Fs=Fs||{});let $s={[ks.multipleAccount]:"multipleAccount",[ks.multipleDevice]:"multipleDevice",[ks.restApi]:"REST_API_Kick",[Fs.multipleAccount]:"multipleAccount",[Fs.multipleDevice]:"multipleDevice",[Fs.restApi]:"REST_API_Kick",[Fs.usersigExpired]:"userSigExpired"},qs="login_online_presence_task",{ERROR:xs,DESTROY:Vs,FORCE_OFFLINE:Bs}=cs,{KICKED_OUT_MULT_ACCOUNT:js,KICKED_OUT_MULT_DEVICE:Ks,KICKED_OUT_REST_API:Hs,ACCOUNT_A2KEY_EXPIRED:Ws,MSG_A2KEY_EXPIRED:Ys}=Ts;class zs{init(){var e=ts["notificationCenter"];e.subscribeInnerEvent(Bs,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(xs,Ys,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Ws,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,js,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Ks,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Hs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Vs,this._dispose,this)}_handleForceOfflineFromServerPush(e){var{EventArray:e=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(e).forEach(e=>{var{KickType:e,NewInstInfo:t}=e["KickoutMsgNotify"];this._processKickedOutReasonInfo({kickedOutReasonCode:e,newInstanceInfo:t})})}_extractKickedOutMessages(e){return e.reduce((e,t)=>[...e,...t.C2cNotifyMsgArray||[]],[]).filter(e=>{return this._isKickedOut(null==(e=null==e?void 0:e.KickoutMsgNotify)?void 0:e.KickType)})}_handleForceOfflineFromResponse(e){e=e.errorCode;this._processKickedOutReasonInfo({kickedOutReasonCode:e})}_processKickedOutReasonInfo(r){return de(this,void 0,void 0,function*(){var e=r["kickedOutReasonCode"],{ssoLog:t,utils:{safeStringify:s}}=ts;try{this._logKickedOutEvent(r),yield ts.login.loginAction.logout(Us.KICKED_OUT)}catch(e){t.debug("_processKickedOutReasonInfo"," fail "+s(e))}finally{ts.notificationCenter.emitOuterEvent(rs.KICKED_OUT,{data:{type:$s[e]},name:rs.KICKED_OUT}),[ks.restApi,Ws,Ys].includes(e)&&ts.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,e=`type:${$s[e]} newInstanceInfo: `+JSON.stringify(t);ts.ssoLog.warn("kickedOut",e)}_isKickedOut(e){return[ks.multipleAccount,ks.multipleDevice,ks.restApi].includes(e)}_dispose(){var e=ts["notificationCenter"];e.unSubscribeInnerEvent(Bs,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(xs,Ws,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Ys,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,js,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Ks,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Hs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Vs,this._dispose,this)}}function Js(r){return de(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=ts.common.generateProtocolData({servcmd:e,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:r}}),s=""+t.head.seq+e,d=yield ts.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:i,PurchaseBits:n,A2Key:o,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:u,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:i,purchaseBits:n,a2Key:o,authKey:a,errorCode:l,errorInfo:u,actionStatus:c}}})}function Qs(t){var s;try{var r=Be.getStorage("errorMessage");if(!t||!r)return"";var i=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:n=!1,code:o,replacement1:a="",replacement2:l=""}=t;if(!o)return"";var u=n?o+"_en":o+"_cn";let e=i[i[u]?u:o]||"";return e=e&&(a&&(e=e.replace("$replacement1",a)),l)?e.replace("$replacement2",l):e}catch(t){return console.warn("Error parsing stored error messages:",t),""}}class Xs extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:i="",moreMessage:n=""}=e;let o=r;s&&!r&&(o=Qs(e));r=(s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`)+" "+n;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=i}}function Zs(e,t){if(e&&!0!==(null==(e=ts.store.get("login"))?void 0:e.isLoggedIn))throw new Xs({code:Ts.USER_NOT_LOGGED_IN,functionName:t})}function en(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)tn.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)tn.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function tn({required:e,rules:r,value:t,allowEmpty:i,name:n,key:o,customValidator:a}){if(void 0===t){if(e)throw new Xs({functionName:n,message:`[${n}] Missing required params: "${o}"`})}else{let s="";if(!r.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<r.length;t++){let e=r[t];e=e.replace(e[0],e[0].toUpperCase()),s+=e+"/"}let e=`[${o}] must be type of ${s=s.substring(0,s.length-1)}, received type: ${Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}.`;throw new Xs({functionName:n,message:e})}if(!1===i){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new Xs({functionName:n,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new Xs({functionName:n,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new Xs({functionName:n,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let sn=[],nn={},on={};function rn(e,t){var s;Zs(nn[e],e),en(on[e],t,e),s=e,sn.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function an(e,t){sn.push({interceptor:e,context:t})}function cn(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(on,e),t&&"object"==typeof t&&Object.assign(nn,t)}function un(e){return ts.store.get("commercialConfig").get(e)}class ln{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{var s=Date.now();t?(this._stepStartTimes.set(e+"-"+t,s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var{ssoLog:i,utils:{safeStringify:n}}=ts,o=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?o-t:0;this._stepStartTimes.delete(s+"-"+e),i.error("_executeWorkflowStep",`[Workflow ${s}] Step ${e} failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}else{let e=this._workflowStartTimes.get(s),t=e?o-e:0;this._workflowStartTimes.delete(s),i.error("_executeWorkflowStep",`[Workflow ${s}] failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}}}}static getInstance(){return ln._instance||(ln._instance=new ln),ln._instance}static setInstance(e){ln._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){var i;this._handlers.has(e)?Ns[e].find(e=>e.stepId===t)?(i=this._handlers.get(e)).has(t)||i.set(t,r?s.bind(r):s):ts.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`):ts.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return de(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){ts.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=Ns[o],n={cancelled:!1};this._activeWorkflows.set(o,{cancelToken:n});try{let t=new Map,i=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:o,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:n});yield new Promise((t,s)=>{let r=()=>{n.cancelled?t():this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).forEach(e=>{i.completedSteps.has(e)||i.runningSteps.has(e)||this._executeWorkflowStep(e,i,{onComplete:()=>{0===i.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).length&&0===i.runningSteps.size&&(ts.ssoLog.debug("executeWorkflow",`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),ts.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Completed execution at `+(new Date).toISOString())}catch(e){ts.ssoLog.error("executeWorkflow",`[Workflow ${o}] Failed execution at `+(new Date).toISOString(),{error:e})}finally{this._activeWorkflows.delete(o)}}})}_executeWorkflowStep(l,u,c){return de(this,void 0,void 0,function*(){let{workflowName:n,runningSteps:e,stepMap:r,stepResults:i,data:o}=u;e.add(l),this._logWorkflowExecution(n,l,"start");try{let e=r.get(l),s=null;null!=e&&e.dependency&&(t(e.dependency)?s=i[e.dependency]:Array.isArray(e.dependency)&&(s={},e.dependency.forEach(e=>{s[e]=i[e]})));var a=this._handlers.get(n).get(l);if(a){let e=yield Promise.resolve(a({data:o,result:s}));i[l]=e,this._logWorkflowExecution(n,l,"success")}u.completedSteps.add(l)}catch(e){let t=`[Workflow].${n}.`+l,{errorCode:s,errorInfo:r=t+" failed"}=e||{},i=new Xs({functionName:t,code:s,message:r});ts.ssoLog.error(t,r,{error:i}),this._logWorkflowExecution(n,l,"error",e),c.onError(e)}finally{e.delete(l),u.pendingSteps.delete(l),c.onStepComplete(),c.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ns).forEach(e=>{this._handlers.has(e)||this._handlers.set(e,new Map)})}_cancelWorkFlow(e){var t=this._activeWorkflows.get(e);t&&(t=t["cancelToken"],t.cancelled=!0,this._activeWorkflows.delete(e))}_cancelAllWorkflows(){Object.keys(Ns).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return!!Ns[e]&&!!this._handlers.get(e)}_getExecutableSteps(e){let{pendingSteps:s,completedSteps:r,stepMap:i,workflowName:o}=e;return Array.from(s).filter(e=>{var{dependency:s,skipIfDependencyMissing:e=!0}=i.get(e)||{};if(!s)return!0;if(t(s))return this._isStepRegistered({workflowName:o,stepId:s})?r.has(s):!e;if(n(s)){if(0<s.filter(e=>!this._isStepRegistered({workflowName:o,stepId:e})).length&&e)return!1;for(let e of s)if(!r.has(e))return!1;return!0}return!1})}_isStepRegistered(e){var{workflowName:e,stepId:t}=e;return null==(e=this._handlers.get(e))?void 0:e.has(t)}_logWorkflowExecution(e,t,s,r){this._logHandlers[s](e,t)}}let dn=new Map,hn=({type:e,groupID:t})=>e===As.GRP_COMMUNITY||(""+t).startsWith(Ms.COMMUNITY)&&!(""+t).includes(Ms.TOPIC),gn=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(Ms.COMMUNITY)&&(""+e).includes(Ms.TOPIC)},pn="openim",_n="million_group_open_http_svc";function mn(s){return de(this,void 0,void 0,function*(){var{servcmd:e,data:t}=vn(e=s.data)||fn(e)?function(e){let{servcmd:t,data:s}=e;var r,i,n;return fn(s)?({servcmd:e,data:r}=e,{GroupId:i=""}=r,[i]=(n=i).split(Ms.TOPIC),{servcmd:In(e),data:Object.assign(Object.assign({},r),{GroupId:i,TopicId:n})}):{servcmd:t=vn(s)?In(t):t,data:s}}(s):s,t=ts.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return ts.channel.sendPacket(t,{requestId:e})})}function vn(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return hn({type:e,groupID:t})}function fn(e){var{GroupId:e=""}=e;return gn(e)}function In(e){return e.includes(pn)?e:(e=e.split(".")[1],_n+"."+e)}function En(){var e;return null==(e=ts.store.get("login"))?void 0:e.userId}let Sn=e=>n(e)||o(e),Cn=(r,i,n,o)=>{if(!Sn(r)||!Sn(i))return 0;let a=0;var l,u=Object.keys(i);for(let t=0,s=u.length;t<s;t++)if(l=u[t],!(e(i[l])||n&&n.includes(l)))if(Sn(r[l])&&Sn(i[l]))a+=Cn(r[l],i[l],n,o);else{if(o&&o.includes(i[l]))continue;r[l]!==i[l]&&(r[l]=i[l],a+=1)}return a},Mn=(t,s)=>{if(e(s))return"";switch(t){case As.MSG_TEXT:return s.text||"";case As.MSG_IMAGE:return"[Image]";case As.MSG_LOCATION:return"[Location]";case As.MSG_AUDIO:return"[Voice]";case As.MSG_VIDEO:return"[Video]";case As.MSG_FILE:return"[File]";case As.MSG_CUSTOM:return"[Custom Messages]";case As.MSG_GRP_TIP:return"[Group Notification]";case As.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case As.MSG_FACE:return"[Animated Sticker]";case As.MSG_MERGER:return"[Chat Record]";default:return""}},yn=[{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}],On="im_sdk_config_mgr.fetch_config",An="im_sdk_config_mgr.push_configv2",Tn="cloud-config",Rn=2996,Dn=new class{init(e){this.core=e}};function bn(s){return de(this,void 0,void 0,function*(){var e=(Dn.core.store.get("instance")||{})["sdkAppId"],e=Dn.core.helper.generateProtocolData({servcmd:On,data:{uint32_sdkappid:e,uint64_version:s}}),t=""+e.head.seq+On;return Dn.core.channel.sendPacket(e,{requestId:t})})}var Nn=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){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i},channel:n}=this._core=e;e.subscribeInnerEvent(An,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(yn),n.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return de(this,void 0,void 0,function*(){var e,t={code:0,data:""};return s&&(t.data=(null==(e=this._core.store.get("cloudConfig"))?void 0:e[s])||""),t})}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:i}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:i+=1}),t<i)throw new this._core.helper.ChatError({code:Rn,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_handlePushedConfig(s){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.info("_handlePushedConfig",t(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return de(this,void 0,void 0,function*(){var e,{ssoLog:t,utils:{safeStringify:s}}=this._core;try{this._canFetch()&&(e=yield bn(this._version),t.info("_fetchCloudConfigIfLogin",s(e)),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:Tn,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){t.error("_fetchCloudConfigIfLogin",s(e))}})}_fetchCloudConfigIfReady(){return de(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._canFetch())try{var e=yield bn(this._version);t.info("_fetchCloudConfigIfReady",s(e)),yield this._updateCloudConfig(e)}catch(e){t.error("_fetchCloudConfigIfReady",s(e))}})}_updateCloudConfig(t){return de(this,void 0,void 0,function*(){var e=this._parseCloudConfig(t);e&&(this._core.store.set("cloudConfig",e),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:e}}))})}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:i}=e;let n=null;if(0===t){if(this._version!==i)try{n=JSON.parse(s),this._version=i}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return n}_parseCmdFreqLimit(){return de(this,void 0,void 0,function*(){var e,t=null==(e=yield this.getServerConfig("cmd_frequency_limit"))?void 0:e.data,s=this._core.utils["isEmpty"];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(Tn),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(yn),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(An,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(){var 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}}let Pn={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",Gn="commercial-config";var xn,Vn,Un=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){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i,InnerEvent:n}}=this._core=e;s.subscribeInnerEvent(n.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(n.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return de(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let i,n=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(i=(t<32?new Ln(0,2**t):new Ln(2**(t-32),0)).toString(),!this._featureMap.get(i))){n=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${wn}.isFeatureEnabled decimalNumber:${e} key:${i} ret:`+n),{code:0,data:{enabled:n}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return de(this,void 0,void 0,function*(){let s,{ssoLog:e,helper:r,utils:{safeStringify:t}}=this._core;try{this._isFetching=!0;let e=r.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null==(s=this._core.store.get("instance"))?void 0:s.sdkAppId}}),t=yield this._core.channel.sendPacket(e);null!=t&&t.body&&(this._parseCommercialConfig(t.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(s){e.error("_fetchAndParseCommercialConfig",t(s))}finally{this._isFetching=!1}})}_syncCommercialConfig(t){return de(this,void 0,void 0,function*(){var e=((null==t?void 0:t.data)||{})["purchaseBits"];e&&(this._parsePurchaseBits(e),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Gn,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var e=null==(e=this._core.store.get("login"))?void 0:e.isLoggedIn,t=Date.now()>=this._expirationTime;return e&&!this._isFetching&&t}_handlePushedConfig(e){null!=e&&e.body&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return de(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,i,n=this._core["ssoLog"];"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:i}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*i):void 0===t?(n.warn("_parseCommercialConfig",wn+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",wn+`._parseCommercialConfig errorCode:${t} errorMessage:`+s),this._expirationTime=Date.now()+12e4))}_isValidPurchaseBits(e){return e&&"string"==typeof e&&1<=e.length&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(s){var{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new Ln(0,2**t):new Ln(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(Pn,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(Pn,r);e&&this._methodKeyMap.set(e,!1)}}else e.warn("_parsePurchaseBits",wn+".parsePurchaseBits invalid purchases:"+t(s))}_getKeyByValue(e,t){e=Object.entries(e).find(([,e])=>e===t);return e?e[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(Gn),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},kn=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;var{notificationCenter:e,InnerEvent:t,channel:s}=this._core;e.subscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(this._serverOverloadInfoMap.has(e)){var{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){var{OverLoadServCmd:e,DelaySecs:t}=e;this._serverOverloadInfoMap.set(e,{overloadStartTimestamp:Date.now(),delaySeconds:t})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();var{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)}},Fn=new class{constructor(){this.name="ConfigCenter"}install(e){Dn.init(e),Nn.install(e),Un.install(e),kn.install(e)}},$n=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return de(this,void 0,void 0,function*(){if(this._core=e,this._canFetch()){let e=yield this._fetchErrorMessage();var t;e&&(t=this._parseResponse(e),this._saveErrorMessage(t))}})}_canFetch(){var 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 de(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){return!e||(e=e["errorMessageSavedTime"],e&&6048e5<=(new Date).getTime()-e)}_parseResponse(e){if("string"==typeof e){var s=e.split(";\n"),r={},i=new RegExp(/'/g);for(let t=0;t<s.length;t++){var n=s[t].indexOf(":"),o=s[t].slice(0,n);let e=s[t].slice(n+1);o.startsWith("//")||""!==e&&(e=e.replace(i,""),r[o]=e)}return r}}};function qn(i,l){return de(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=i,r="openim.getmsg",o=l.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+r;try{let e=yield l.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:i,revokedMessageList:n}=function(e,S){let r=[],i=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,To_Account:d,TinyId:h,MsgCheckResult:g,CloudCustomData:p,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:n,messageFlagBits:m,random:o,sequence:a,time:l,messageControlInfo:u,isSupportExtension:c,to:d,tinyID:h,checkResult:g,cloudCustomData:p,messageVersion:v,eventArray:f,elements:S.message.messageHelper.parseServerPushMessageElement(i)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))i.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=S.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:i}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:n,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}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"}(xn=xn||{}),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Vn=Vn||{});var Bn=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){var t=(this._core=e)["constants"];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.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(t){return de(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=xn.START_SYNC;for(var u=[],c=[],d=[],h=[];this._canContinueSync({cookie:this._cookie,syncFlag:l});){let e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:l,syncTriggerEvent:a?Vn.NEW_MESSAGE_RECEIVED:Vn.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:i,groupTipList:n}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",l=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:i,overflowUnreadCountList:r,conversationUpdateFieldList:u}),Array.isArray(n)&&c.push(...n),o){let e=this._handleNewMessageList(t)["messages"];h.push(...e)}}return o?{conversationUpdateFieldList:u,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c,messages:h}:{conversationUpdateFieldList:u,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c}})}_syncUnreadDBMessageAfterLogin(){return de(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return de(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:r}=e,{OuterConstant:{CONV_C2C:i,CONV_SYSTEM:n}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==n){let e=r.find(({conversationID:e})=>e===""+i+t);e?e.unreadCount=s:r.push({conversationID:""+i+t,unreadCount:s,type:i})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===n||r.find(({conversationID:e})=>e===""+i+t)||r.push({conversationID:""+i+t,type:i,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return de(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let i=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;n&&o?n===e&&o===t||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_handleNewMessageList(e){let t=(this._core.message||{})["messageDataHandler"],l=new Map,s=[];return e.forEach(a=>{this._updateMessageProfile(a);let e=1===a.isModified;if(t.isMessageSentByCurrentInstance(a)?a.isModified=e:e=!1,a.isOnlineMessage())a._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(a)||s.push(a);else if(!t.isInMessageList(a)){if(t.storeConversationMessage(a)){let{conversationID:e,conversationType:t,conversationSubType:s,flow:r,_isExcludedFromUnreadCount:i,_isExcludedFromLastMessage:n}=a,o=n?"":a;l.has(e)?(l.get(e).lastMessage=o,"in"!==r||i||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:i||"in"!==r?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:l}}_fetchUnreadDBMessage(c){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;try{e.debug("_fetchUnreadDBMessage","unread-message-synchronizer._fetchUnreadDBMessage options:"+t(c));var s,r,i,n,o,a,l,u=yield qn(c,this._core);return u?({syncFlag:s,unreadMessageList:r,revokedMessageList:i,cookie:n,unreadCountList:o,overflowUnreadCountList:a,groupTipList:l}=u,this._parseAndSaveUnreadMessageList(r),{syncFlag:s,cookie:n,unreadMessageList:r,revokedMessageList:i,unreadCountList:o,overflowUnreadCountList:a,groupTipList:l}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===xn.START_SYNC||t===xn.SYNCING&&!(null!=(t=this._core)&&t.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach(e=>{var t=e["ID"];this._unreadDBMessageMap.set(t,e)})}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},jn=new class{init(e){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!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t="visible"===document.visibilityState;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:t}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:t})}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},Kn=new class{init(e){this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var{MINI_APP_NAMESPACE:e,IN_TT_MINI_GAME:t,IN_WX_MINI_GAME:s}=(null==(e=this._core)?void 0:e.utils)||{};t||s?(null!=(t=null==e?void 0:e.onShow)&&t.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null!=(s=null==e?void 0:e.onHide)&&s.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!1}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):(null!=(t=null==e?void 0:e.onAppShow)&&t.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null!=(s=null==e?void 0:e.onAppHide)&&s.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!1}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},Hn=new class{init(e){var{IN_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Kn:jn).init(e)}};let Wn="none",Yn="online";var zn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return de(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,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Yn})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Wn})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Jn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return de(this,void 0,void 0,function*(){try{var{MINI_APP_NAMESPACE:e}=this._core["utils"];this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),e.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}})}_deactivateNetworkMonitoring(){var e;null!==this._mpNetworkStatusCallback&&({MINI_APP_NAMESPACE:e}=this._core["utils"],e.offNetworkStatusChange&&e.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Qn=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?Jn:zn).init(e)}},Xn=new class{constructor(){this.name="SystemStateMonitor"}install(e){Hn.init(e),Qn.init(e)}};let Zn=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.*"]),eo="tui_room_svr.*";var to=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Zn}install(e){var{notificationCenter:e,InnerEvent:t,helper:s}=this._core=e;e.subscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return de(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=eo}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(n,o){return de(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=eo,data:r}=n||{};let i={};try{i="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:i}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}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{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=Zn}_dispose(){var{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)}};let so=1,no=2,oo=3,io=4,ro=5,ao="TIMCustomElem",co="C2C",uo="GROUP",lo="invite",ho="accept",go="cancel",po="reject",_o="modifyInvitation",mo="signaling",vo=8010,fo="signaling-timeout";function Io(e){return e.filter(e=>{var t,s;return e.type===ao&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function Eo(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function So(e,t){return e.toString(16).padStart(t,"0")}function Co(e){if(e<0||53<e)throw new Error("Number of digits must be between 0 and 53");return e<=30?Math.floor(Math.random()*(1<<e)):(e=e-30,Math.floor(Math.random()*(1<<e))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var Mo=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){(this._core=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){var t=mo+".isInvitationValid",{inviteID:e,groupID:s,inviter:r}=e,r=r===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var i=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(t+` inviteID:${e} inviteeList:${i} groupID:`+s),s){if(r)return 0<i.length;let e=this._core.common.getCurrentUserID();return i.includes(e)}return!0}updateSignaling(e){let s=mo+".updateSignaling",{inviteID:r,inviter:t,inviteeList:i,groupID:n}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+n),n&&this.hasSignaling(r)){let e=i[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},yo=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:i}=e,s=s||(t?r[0]:i);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:i}=e,s=(null==(s=null==(s=Mo.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,i)}}_createMessageControlInfo(e,t){t=t===ro&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){var t=mo+"._createInviteSignalingData",{userID:s,timeout:r=0,groupID:i="",inviteeList:n=[]}=e,o=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:so,inviter:o,inviteeList:i?n:[s],timeout:r});return console.log(t+" signalingData:",e),e}_createAcceptSignalingData(e){var t=mo+"._createAcceptSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:i}=Mo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:oo,groupID:i,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createCancelSignalingData(e){var t=mo+"._createCancelSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviteeList:s,groupID:i}=Mo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:no,groupID:i,inviter:r,inviteeList:s});return console.log(t+" signalingData:",e),e}_createRejectSignalingData(e){var t=mo+"._createRejectSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:i}=Mo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:io,groupID:i,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createTimeoutSignalingData(e){var t=mo+"._createTimeoutSignalingData",{isInviter:s=!1,inviteID:r}=e,{inviteeList:r,inviter:i}=Mo.getSignaling(r),n=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ro,inviter:i,inviteeList:s?r:[n]});return console.log(t+" signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?uo:co,priority:"High",payload:{data:JSON.stringify(e)}};return null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t)}_generateInviteID(){return[So(Co(32),8),So(Co(16),4),So(16384|Co(12),4),So(32768|Co(14),4),So(Co(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Oo=new class{constructor(){this._isProcessingSignaling=!1}init(e){(this._core=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(t){return de(this,void 0,void 0,function*(){var s;try{this._validateBeforeInvite(t);var{signaling:r,signalingData:i,signalingExtensionOptions:e}=yo.createInviteSignaling(t),n=yield this._sendSignaling(r,e);if(0!==(null==n?void 0:n.code))return n;{let{inviteID:e,timeout:t}=i;return Mo.saveSignaling(e,Object.assign(Object.assign({},i),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:fo+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},n),{inviteID:e})}}catch(e){throw e}})}accept(n){return de(this,void 0,void 0,function*(){try{var e=n["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,yo.createAcceptSignaling(n)),i=yield this._sendSignaling(t,r);return 0===(null==i?void 0:i.code)?(Mo.updateSignaling(s),Object.assign(Object.assign({},i),{inviteID:e})):i}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(i){return de(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,yo.createCancelSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(Mo.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(i){return de(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,yo.createRejectSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(Mo.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return de(this,void 0,void 0,function*(){var r,i,{inviteID:n,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(n);let e=Mo.getSignaling(n),t=e["signaling"],s=le(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var l=yield null==(i=null==(r=this._core)?void 0:r.message.messageAction)?void 0:i.modifyMessage(t);return Mo.hasSignaling(n)&&Mo.saveSignaling(n,Object.assign(Object.assign({},s),{signaling:t})),l}catch(e){if(a){let e=Mo.getSignaling(n)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0!==Io([e]).length)return e={businessID:(e=Eo(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||so,timeout:e.timeout||0},t.debug(mo+" getSignalingInfo "+s(e)),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&Mo.setSignalingListenStatus(!0),null!=(r=this._core)&&r.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&Mo.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=Mo.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();t.has(e)&&(t=t.get(e).inviter===s,this._sendTimeoutNotice({inviteID:e,isInviter:t}))}_sendSignaling(t,s){return de(this,void 0,void 0,function*(){var e;return null==(e=null==(e=null==(e=this._core)?void 0:e.message)?void 0:e.messageSender)?void 0:e.sendMessage(t,s)})}_sendTimeoutNotice(s){return de(this,void 0,void 0,function*(){var i;this._core.ssoLog.debug("_sendTimeoutNotice",mo+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:n,inviteID:o}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=yo.createTimeoutSignaling(s),t=yield this._sendSignaling(a,e);if(0===(null==t?void 0:t.code)){let{data:e,groupID:t,inviteeList:s,inviter:r}=l;null!=(i=this._core)&&i.notificationCenter.emitOuterEvent(null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,{name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),n?Mo.removeSignaling(o):Mo.updateSignaling(l)}})}_validateInviteId(e,t){if(!Mo.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:vo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var t=lo,e=e["userID"],s=this._core.common.getCurrentUserID();if(e===s)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${s}, inviteeId:`+e})}_validateBeforeAccept(t){var s=ho;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=Mo.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t=go,s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=Mo.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s=po;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=Mo.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){var t=_o;this._validateInviteId(t,e)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Ao=new class{constructor(){this._actionProcessor=new Map([[so,this._onNewInvitationReceived.bind(this)],[io,this._onInviteeRejected.bind(this)],[oo,this._onInviteeAccepted.bind(this)],[no,this._onInvitationCancelled.bind(this)],[ro,this._onInvitationTimeout.bind(this)]])}init(e){(this._core=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=>{var t,s=Eo(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){Mo.getSignalingListenStatus()&&0!==(e=Io(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){Mo.getSignalingListenStatus()&&0<(e=Io(e.data)).length&&e.forEach(e=>{var t=Eo(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){var r=mo+"._onNewInvitationReceived",{inviteID:i,inviteeList:n,groupID:o}=t,a=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",r+` signalingData:${JSON.stringify(t)}}`),!o||n.includes(a)){let e=t["timeout"];var r=Date.now()/1e3-s.time,o=(0<e&&0<r&&e>r&&(e-=r),Mo.getSignaling(i));o!==t&&(o||Mo.saveSignaling(i,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(a=this._core)&&a.helper.taskScheduler.addOnceTask({id:fo+"-"+i,intervalMs:1e3*e,callback:Oo.handleInvitationExpiryTimer.bind(Oo,i)})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:n})}))}}_onInviteeRejected(e){var t=mo+"._onInviteeRejected",{inviteID:s,inviter:r,groupID:i,inviteeList:n}=e,o=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInviteeRejected",t+` inviteID:${s} hasInviteID:${o} inviter:${r} groupID:`+i),o&&(Mo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:n[0]})}))}_onInviteeAccepted(e){var t=mo+"._onInviteeAccepted",{inviteID:s,inviter:r,groupID:i,inviteeList:n}=e,o=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInviteeAccepted",t+` inviteID:${s} hasInviteID:${o} inviter:${r} groupID:`+i),o&&(Mo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:n[0]})}))}_onInvitationCancelled(e){var t=mo+"._onInvitationCancelled",{inviteID:s,inviter:r,groupID:i}=e,n=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInvitationCancelled",t+` inviteID:${s} hasInviteID:${n} inviter:${r} groupID:`+i),n&&(Mo.removeSignaling(s),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t=mo+"._onInvitationTimeout",{inviteID:s,inviteeList:r}=e,i=Mo.hasSignaling(s);this._core.ssoLog.debug("_onInvitationTimeout",t+` inviteID:${s} hasInviteID:${i} data:`+e.data),i&&(Mo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s=mo+"._onInvitationModified",{inviteID:r,data:i}=e,n=Mo.hasSignaling(r);this._core.ssoLog.debug("_onInvitationModified",s+` inviteID:${r} data:`+i),n&&(Mo.saveSignaling(r,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:r,data:i}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},To=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:i}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&Mo.getSignalingListenStatus()){e=Io([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();Ao.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=Eo(e);s&&(t=s["actionType"],t===so?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:i=0}=e,n=this._core.common.getCurrentUserID();r.includes(n)&&(r=Date.now()/1e3-t.time,0<i&&i<r&&0!==i||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let Ro={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}}},Do={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Lo,Po,Xo,bo=new class{constructor(){this.name="Signaling"}install(e){Oo.init(e),Ao.init(e),yo.init(e),Mo.init(e),To.init(e),e.helper.registerValidateConfig({auth:Do,params:Ro})}};let No=new class{init(e){this.core=e}},wo=(!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(Lo=Lo||{}),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(Po=Po||{}),"MSG_REACTION"),Go="MSG_EXT",Uo=0,ko=1,Fo={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",xo="16k_yue",Vo="16k_ja",Bo="16k_zh-PY",jo={[Fo.ZH_CN]:$o,[Fo.EN_US]:qo,[Fo.YUE_HK]:xo,[Fo.JA_JP]:Vo,[Fo.ZH_PY]:Bo},Ko=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Ho={READ:0,UNREAD:1},Wo=1,Yo=2,zo=3,Jo=1,Qo=2,Zo=(!function(e){e.IN="in",e.OUT="out"}(Xo=Xo||{}),16),ei=17,ti=2116,si=2500,ni="C2C",oi="GROUP",ii=20;function ri(d){return de(this,void 0,void 0,function*(){var t,{appStore:s,utils:{isEmpty:r},common:{getCurrentUserID:i},notificationCenter:e,OuterEvent:n}=No.core,{messageList:o,conversationID:a}=d,l=s.conversationStore.getConversationMap();let u=null==(t=l.get(a))?void 0:t.peerReadTime;if(!u){let e=a.replace(ni,""),t=yield function(t){return de(this,void 0,void 0,function*(){var e={To_Account:t};return No.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];u=null==e?void 0:e[0],l.has(a)&&(l.get(a).peerReadTime=u)}}if(l.has(a)){let e=null==(t=l.get(a))?void 0:t.lastMessage;r(e)||e.fromAccount===i()&&e.lastTime<=u&&!e.isPeerRead&&(e.isPeerRead=!0,s.conversationStore.updateConversation(a,{lastMessage:e}))}let c=[];o.forEach(e=>{e.time<=u&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),e.emitOuterEvent(n.MESSAGE_READ_BY_PEER,{name:n.MESSAGE_READ_BY_PEER,data:c})})}function ai(a){return de(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:i}}=No.core,n=r.conversationStore.getConversationMap();if(n.has(a)){let s=null==(e=n.get(a))?void 0:e.userProfile;if(s&&a.startsWith(i.CONV_C2C)){let{avatar:e,nick:t}=s;No.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!1})}}var o=((yield t.userProfile.getMyProfile())||{})["data"];if(o){let{avatar:e,nick:t}=o;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!0})}})}function ci(e){let t,s=No.core["message"],{conversationID:r,messageID:i}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===i))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===i)}function ui(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:i,nick:n,ID:o,clientSequence:a,clientTime:l,messageRandom:u,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:i,From_AccountNick:n,Id:o,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:l,MsgRandom:u,Random:u,MsgSeq:c,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function li(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:i,MsgClientTime:n,ClientSeq:o,To_Account:a,MsgTimeStamp:l,TinyId:u,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:n,time:l,tinyID:u,random:c,sequence:d,to:a,groupID:i,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return No.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var di=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:i}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,i,this._handleReactionSync,this)}addMessageReaction(d,h){return de(this,void 0,void 0,function*(){let{OuterConstant:e,helper:s}=this._core;this._validateMessageReactionBusinessCapability();var{conversationID:r,ID:i,conversationType:t,from:n,to:o,clientSequence:a,random:l,time:u,sequence:c}=d,r=`conversationID:${r} messageID:${i} reactionID:`+h;try{return this._recordMessageReactedByMe(i,h),t===e.CONV_C2C?yield function(o,a){return de(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:n,to:o,clientSequence:a,random:l,time:u,reactionID:h},this._core):t===e.CONV_GROUP&&(yield function(r,i){return de(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:o,reactionID:h,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){this._removeMyReactionRecord(i,h);let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"addMessageReaction",code:t,moreMessage:r})}})}removeMessageReaction(d,h){return de(this,void 0,void 0,function*(){var{OuterConstant:e,helper:s}=this._core,{conversationID:r,ID:t,conversationType:i,from:n,to:o,clientSequence:a,random:l,time:u,sequence:c}=(this._validateMessageReactionBusinessCapability(),d),r=`conversationID:${r} messageID:${t} reactionID:`+h;try{return this._removeMyReactionRecord(t,h),i===e.CONV_C2C?yield function(o,a){return de(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:n,to:o,clientSequence:a,random:l,time:u,reactionID:h},this._core):i===e.CONV_GROUP&&(yield function(r,i){return de(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},i)})}({to:o,reactionID:h,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:r})}})}getAllUserListOfMessageReaction(l){return de(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=l,s=100<l.count?100:l.count,i=e["conversationID"],{helper:n,constants:o}=this._core;try{var a;if(a=i.startsWith(o.OuterConstant.CONV_C2C)?yield function(l){return de(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=l,{from:e,to:i,clientSequence:n,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:i,MsgKey:n+`_${o}_`+a};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(n){return de(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=n,{sequence:e,to:i}=e,s={Reaction:s,NextSeq:t,GroupId:i,Count:r,MsgSeq:e};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s})){let{Reaction_Account:e,NextSeq:t}=a,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,userList:s}}}}catch(e){let t=(e||{})["errorCode"];throw new n.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(g){return de(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),g),r=t[0];let i=null,n=new Map,{from:o,to:a,conversationType:l}=r,u=this._generateMessageKeyList(t,n),{Results:c=[]}=(l===e.OuterConstant.CONV_C2C?i=yield function(i){return de(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=i,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:o,to:a,messageKeyList:u,maxUserCountPerReaction:s}):l===e.OuterConstant.CONV_GROUP&&(i=yield function(r){return de(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,e={GroupId:e,MsgSeqList:t,Count:s};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:u,maxUserCountPerReaction:s})),i||{}),d=this._extractUserIDsFromReactionResults(c),h=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:n}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:h}),reactedByMyself:1===r}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){let t=[];return null!=e&&e.forEach(e=>{var{ReactionList:e=[]}=e;e.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(s){return de(this,void 0,void 0,function*(){var e;try{var t=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:s});return t?t.data:[]}catch(e){return[]}})}_getUserProfileMap(e){return de(this,void 0,void 0,function*(){let r=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;r.set(s,{nick:e,avatar:t,userID:s})}),r})}_recordMessageReactedByMe(e,t){e=e+"-"+t;this._reactionsMap.has(e)?this._reactionsMap.get(e).reactedByMe=!0:this._reactionsMap.set(e,{reactedByMe:!0})}_removeMyReactionRecord(e,t){e=e+"-"+t;this._reactionsMap.has(e)&&(this._reactionsMap.get(e).reactedByMe=!1)}_recordMessageReactionInfo(e){var{messageID:e,reactionID:t,reactionInfo:s}=e,e=e+"-"+t,t=this._reactionsMap.get(e)||{};this._reactionsMap.set(e,Object.assign(Object.assign({},t),s))}_validateMessageReactionBusinessCapability(){var{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(wo))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){let t=e["MsgReactionNotifyList"],{notificationCenter:d,constants:h}=this._core;t.forEach(c=>de(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:i,MsgRandom:n}=Object.assign(Object.assign({},e),t),o=r+`-${i}-`+n,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),u=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:l}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(o+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:o,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(h.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:h.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:o,reactionList:u}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:i,OperateType:n}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+o,o=r+"-"+i;if(1===n?this._recordMessageReactedByMe(r,i):this._removeMyReactionRecord(r,i),null!=(e=this._reactionsMap.get(o))&&e.reactionID){let e=this._reactionsMap.get(o);e.reactedByMyself=1===n,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,i){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return i.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return i.set(t,e),t})),r}},hi=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:i}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return de(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new r.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(r){return de(this,void 0,void 0,function*(){var{common:e,constants:t}=No.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:i,clientTime:n}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:i,MsgClientTime:n}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return de(this,void 0,void 0,function*(){var{common:e,constants:t}=No.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:t})})}(s),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(i){return de(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=i[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(i);if(0<(null==s?void 0:s.length)){let e=yield function(s){return de(this,void 0,void 0,function*(){var{common:e,constants:t}=No.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:t})})}(s),t=(e||{})["GroupMsgReceiptList"];this._updateGroupMessagesReadReceiptInfo({messageList:i,readReceiptList:t})}}return{code:0,data:{messageList:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(n){return de(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:o=Ho.READ,cursor:s=""}=n,{conversationID:i,sequence:a,ID:l}=t,u=i.replace(e.OuterConstant.CONV_GROUP,""),c=100<=n.count?100:n.count;try{let n=yield function(n){return de(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:i}=n,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:i};return No.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:u,sequence:a,filter:o,cursor:s,count:c});if(n){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=n,i={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return o===Ho.READ?i.readUserIDList=r.map(e=>e.Read_Account):o===Ho.UNREAD&&(i.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let i=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:n,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(n)){let r=""+t.OuterConstant.CONV_C2C+a;null!=n&&n.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=ci({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,i.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(i)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:n}}=e,o=""+s.OuterConstant.CONV_GROUP+n;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:i}=e,e=e+`-${t}-`+s,t=ci({conversationID:o,messageID:e}),s={groupID:n,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof i&&(t.readReceiptInfo.unreadCount=i,s.unreadCount=i),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function gi(o,a,l){return de(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=No.core["common"],{from:t,to:s,clientSequence:r,random:i,time:n}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${i}_`+n,OperateType:l,ExtensionList:a}})})}function pi(r,i,n){return de(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=No.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:n,ExtensionList:i}})})}var _i=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,i,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(c,d){return de(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:s,conversationID:r,sequence:i,time:n,conversationType:o}=c,a=d;20<d.length&&(a=d.slice(0,20),t.warn("setMessageExtensions","the length of extensions cannot exceed 20"));var l=this._generateServerExtensions(c,a),u=`convID:${r} messageID:${s} sequence:${i} time:${n} count:`+a.length;try{let r;if(o===e.CONV_C2C?r=yield gi(c,l,Wo):o===e.CONV_GROUP&&(r=yield pi(c,l,Wo)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(c,r);return{code:0,data:{extensions:e},successLog:{message:u+` successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:u})}})}getMessageExtensions(o){return de(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:i}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),n=`convID:${e} messageID:${r} sequence:${t} time:`+i;try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),{code:0,data:{extensions:t},successLog:{message:n}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:n})}})}deleteMessageExtensions(d,h){return de(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t}}=this._core,{conversationType:s,conversationID:r,sequence:i,ID:n,time:o}=d,a=zo,l=[];e(h)||(a=Yo,null==h)||h.forEach(e=>{l.push({key:e,value:"",seq:0})});var u=`convID:${r} messageID:${n} sequence:${i} time:${o} operateType:`+a,c=this._generateServerExtensions(d,l);try{let r;if(s===t.CONV_C2C?r=yield gi(d,c,a):s===t.CONV_GROUP&&(r=yield pi(d,c,a)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return{code:0,data:{extensions:e},successLog:{message:u+`successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:u})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],i=t.ExtensionList||[],n=[],o=0,a=0,l=[];return i.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;n.push({code:e,key:t,value:s}),0===e?o++:a++,l.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<l.length&&this._updateLocalExtensions(e.ID,l),{resultList:n,successCount:o,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);let r=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=r&&r.set(e,{value:s,seq:t})})}_fetchMessageExtensions(l,s){return de(this,void 0,void 0,function*(){let{constants:{OuterConstant:e},utils:{isEmpty:o}}=this._core;try{let n;var{conversationType:t,ID:a}=l;if(t===e.CONV_C2C?n=yield function(e,t){var s=No.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:i,random:n,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:i+`_${n}_`+o,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(n=yield function(e,t){var s=No.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(l,s)),n){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=n,r=(n.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let i=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||i.push({key:t,value:e})})}return i}}catch(e){throw e}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(Go))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:r,TinyId:i,MsgLastSeq:n,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},i=i+`-${o}-`+a;this._extensionsLatestSequenceMap.set(i,n),r===Wo?this._handleMessageExtensionsUpdated({messageID:i,updateMessageExtensionsInfo:e}):r===Yo?this._handleMessageExtensionsDeleted({messageID:i,deleteMessageExtensionsInfo:t}):r===zo&&this._handleMessageExtensionsCleared({messageID:i,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:n}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:n}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:i,clearMessageExtensionsInfo:n=[]}=e,o=[];n.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(i)&&(this._messageExtensionsMap.get(i)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&o.push(t)}),this._clearLocationExtensions(i,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:i,keyList:o}})}};let mi={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=No.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},vi={setMessageExtensions:[mi,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[mi],deleteMessageExtensions:[mi]},fi=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,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var t="string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(t=null==e?void 0:e.text)?void 0:t.length))||"payload.text is invalid.";return!0!==t?t:!(null!=e&&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=>{var{isString:t,isNumber:s}=No.core["utils"];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||10<e)||"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}}}),vi),{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}]}),Ii=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});class Ei{constructor(e){this._core=e}deleteMessage(s){return de(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:t};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:e})})}revokeMessage(n){return de(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:i}=n;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:i,MsgTimeStamp:r}}})})}}class Si{constructor(e){this._core=e}deleteMessage(s){return de(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={GroupId:e,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:t};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:e})})}revokeMessage(s){return de(this,void 0,void 0,function*(){var{to:e,sequence:t}=s;return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:{GroupId:e,MsgSeqList:[{MsgSeq:t}]}})})}}class Ci{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:i,revokeReason:n,revoker:o}=e;let a={};var l=this._core.message["messageDataHandler"];return(a=l.revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}))||(a={conversationID:e,sequence:t},r&&i&&s&&(a.ID=r+`-${i}-`+s)),a.revoker=o,a.revokeReason=n,a.revokerInfo={userID:o,nick:"",avatar:""},a}updateRevokerInfo(t){return de(this,void 0,void 0,function*(){var e=t.map(e=>e.revoker);try{let s=yield this._fetchUserInfos(e);s&&t.forEach(e=>{var t=e["revoker"];s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(t){return de(this,void 0,void 0,function*(){var e=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t});return null!=e&&e.data?null==(e=e.data)?void 0:e.reduce((e,{userID:t,nick:s,avatar:r})=>(e[t]={nick:s||"",avatar:r||""},e),{}):null})}}var Mi=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Si(e),this._c2cMessageAction=new Ei(e),this._messageHelper=new Ci(e);e=e.helper;e.registerApi({apiName:"deleteMessage",context:this}),e.registerApi({apiName:"revokeMessage",context:this}),e.registerApi({apiName:"resendMessage",context:this}),e.registerApi({apiName:"findMessage",context:this})}deleteMessage(t){return de(this,void 0,void 0,function*(){let l=[],u=[],{conversationID:c,conversationType:d}=t[0],e=c.replace(d,"");if("@TIM#SYSTEM"===d)throw new this._core.helper.ChatError({code:ti});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:i,sequence:n,random:o,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!i){let e="C2C"===s?n+`_${o}_`+a:String(n);l.push(e)}u.push(e)}}),0===l.length)return this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}};30<l.length&&(l=l.slice(0,30),u=u.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:l}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:l}),this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(u){return de(this,void 0,void 0,function*(){var s;let{conversationType:e,isRevoked:t,ID:r,type:i,from:n,to:o}=u;var a,l=`type:${i} from:${n} to:${o} ID:`+r;if("@TIM#SYSTEM"===e)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(t)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:l});try{if(a="C2C"===e?yield this._c2cMessageAction.revokeMessage(u):yield this._groupMessageAction.revokeMessage(u)){let e=a["RecallRetList"],t=(null==(s=null==e?void 0:e[0])?void 0:s.RetCode)||0;if(0!==t)throw new this._core.helper.ChatError({code:t,moreMessage:l});return u.isRevoked=!0,yield this._handleRevokeMessageSuccess(u),{code:0,data:{message:u},successLog:{message:l}}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:l})}})}resendMessage(t,s){return de(this,void 0,void 0,function*(){var e;return t.isResend=!0,t.status="unSend",null==(e=null==(e=this._core)?void 0:e.apiMap)?void 0:e.sendMessage(t,s)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(i){if(0!==i.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;i.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:i=""}=i[0];e(i)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,i):t.emitInnerEvent(r.MESSAGE_DELETED,i)}}_handleRevokeMessageSuccess(i){return de(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:r}=i;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([i])})}};class yi{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new yi({index:e,data:t})}constructor(e){this.type=Lo.MSG_FACE;var{index:e,data:t}=e;this.content={index:e,data:t}}validateBeforeSend(){var e;return"number"==typeof(null==(e=this.content)?void 0:e.index)&&"string"==typeof(null==(e=this.content)?void 0:e.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{index:e,data:t}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Index:e,Data:t}}}}class Oi{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new Oi({description:e,longitude:t,latitude:s})}constructor(e){this.type=Lo.MSG_LOCATION;var{description:e,longitude:t,latitude:s}=e;this.content={description:e,longitude:t,latitude:s}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{description:e,longitude:t,latitude:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Desc:e,Longitude:t,Latitude:s}}}}var Ai=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(Lo.MSG_FACE,yi),e.message.messageFactory.registerElementClass(Lo.MSG_LOCATION,Oi),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){var t,s;return e?({index:t,data:s}=(null==e?void 0:e.payload)||{},t=new yi({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],i=this._core.apiMap.createTextMessage(e),n=this._core["OuterConstant"];if(!i)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==n.MSG_AT_ALL?(t.push({GroupAtAllFlag:Uo,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:ko}),s.push(n.MSG_AT_ALL))}),i._groupAtInfoList=t,i.atUserList=s}return i}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:i,payload:n,needReadReceipt:o,receiverList:a,cloudCustomData:l="",isSupportExtension:u=!1}=e;if(!Array.isArray(n._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(n.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:i,payload:n,needReadReceipt:o,isSupportExtension:u,cloudCustomData:l,receiverList:a});return t.setRelayFlag(!0),t.setElement(n._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new Oi({description:t,longitude:s,latitude:r}),s=this._core.common.getCurrentUserID(),(r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),r):null}};let Ti=class{init(e){this._messageHelper=new Ci(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return de(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return de(this,void 0,void 0,function*(){let a=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:l}}=this._core;s.forEach(e=>{var{MsgRand:t,MsgSeq:s,To_Account:r,From_Account:i,RevokerInfo:{Revoker_Account:n,Revoke_Reason:o}}=e,r=l()===i?"C2C"+r:"C2C"+i,e=(null==(i=null==e?void 0:e.RevokerInfo)?void 0:i.Reason)||o,i=this._messageHelper.generateRevokeMessage({conversationID:r,sequence:s,random:t,revoker:n,revokeReason:e});a.push(i)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return de(this,void 0,void 0,function*(){var e=t.result["revokedMessageList"];yield this._parseAndEmitC2CRevokedMessages(e)})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},Ri=class{init(e){this._messageHelper=new Ci(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){e=e.GroupTips;null!=e&&e.forEach(e=>{var t;Array.isArray(null==(t=null==e?void 0:e.MsgBody)?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(n){return de(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:u}=n,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:i}}=this._core,h=!1;u&&(h=i({groupID:u.GroupId})||!r(u.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:i,TopicId:n,RevokerInfo:{Revoker_Account:o=(null==l?void 0:l.Revoker_Account)||"",Reason:a=(null==l?void 0:l.Reason)||""}}=e,n=this._messageHelper.generateRevokeMessage({conversationID:n?"GROUP"+n:"GROUP"+s,sequence:t,random:e,tinyID:i,clientTime:r,revoker:o,revokeReason:a});(h?(n.revokerInfo.nick=u.From_AccountNick,n.revokerInfo.avatar=u.From_AccountHeadurl,c):d).push(n)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),c.push(...d)),0!==c.length&&t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:c})}catch(e){console.debug(e)}})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var Di=new class{constructor(){this._c2cMessageReceiver=new Ti,this._groupMessageReceiver=new Ri}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class bi{constructor(e){var t=(this._core=e)["constants"];this._messageHelper=new Ci(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return de(this,void 0,void 0,function*(){var e;try{var t=yield function(n){return de(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=No.core,i=e.groupStore.getGroupMap(),t={NotifyReqList:n.map(e=>{var t=i.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*No.core.common.timeManager.getServerTimeMs()}})||[]};return r.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:t})})}(s);if(t){let s=[];null!=(e=null==t?void 0:t.NotifyRspList)&&e.forEach(e=>{var{GroupId:e,NotifyMsgList:t}=e,e=this._parseServerRevokeMessageList({groupID:e,serverRevokeMessageList:t});s.push(...e)}),0!==s.length&&(yield this._emitMessageRevokedEvent(s))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){let{serverRevokeMessageList:t,groupID:o}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:i=""}}=e,n="GROUP"+o,n=this._messageHelper.generateRevokeMessage({conversationID:n,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:i});a.push(n)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return de(this,void 0,void 0,function*(){var{notificationCenter:e,OuterEvent:t}=this._core;yield this._messageHelper.updateRevokerInfo(s),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:s})})}}class Ni{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new Ci(e)}getRoamingMessagesByAnchor(p){return de(this,void 0,void 0,function*(){var i;try{var{conversationID:n,count:e,messageID:r,time:o,direction:a}=p;let t=o,s="";if(!o){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(n)){let e=this._historyMessageListFetchAnchors.get(n);t=e.lastMessageTime,s=e.messageKey}}var l=n.replace(ni,""),u=yield function(n){return de(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:i}=n,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:i};return No.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:l,direction:a});if(u){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=u;this._historyMessageListFetchAnchors.set(n,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],h=this._parseMessage(d);c.push(h)}var g=this._core.message.messageHelper.filterValidMessages(c);return{messageList:g,nextReqMessageIDFromServer:null==(i=g[0])?void 0:i.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){var t=ni,e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}}var Li=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new bi(e),this._c2cMessageHistory=new Ni(e),this._messageHelper=new Ci(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 de(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e,r=ii;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var i=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:i,targetCount:r})){let e=null;if(t.startsWith(oi)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:r,direction:Po.FORWARD}):t.startsWith(ni)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:r,direction:Po.FORWARD})),e){var{nextReqMessageIDFromServer:n,hasNoMoreHistoryMessage:o,messageList:a}=e,l=this._core.message.messageDataHandler.prependLocalMessageList({messageList:a,conversationID:t}),u=t,{appStore:c,message:d,OuterConstant:h}=No.core,c=c.conversationStore.getConversation(u),g=d.messageDataHandler.getLocalMessageList(u);if(c&&0!==g.length&&u!==h.CONV_SYSTEM){var p=[];for(let e=0;e<g.length;e++)"in"!==g[e].flow?"out"!==g[e].flow||g[e].isRead||g[e].setIsRead(!0):p.push(g[e]);let t=0;if(c.type===h.CONV_C2C){let e=p.slice(-c.unreadCount).filter(e=>e.isRevoked).length;t=p.length-c.unreadCount-e}else t=p.length-c.unreadCount;for(let e=0;e<t&&!p[e].isRead;e++)p[e].setIsRead(!0)}yield ai(t),t.startsWith(ni)&&(yield ri({messageList:a,conversationID:t}));var _=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,l.length+i),m=_.filter(e=>e.isRevoked),v=(yield this._messageHelper.updateRevokerInfo(m),o&&this._fetchedCompleteConversations.add(t),{nextReqMessageID:o?"":String(n),messageList:_,isCompleted:o}),f=_.map(e=>e.sequence);return{code:0,data:v,successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${i} sequenceList: `+JSON.stringify(f)}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:r}),successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${i}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(r){return de(this,void 0,void 0,function*(){var n,o;let{conversationID:e,sequence:a,time:t,direction:l=Po.FORWARD}=r,u=this._core.helper["isEmpty"];if(![Po.BACKWARD,Po.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=ii}=r,c=(s=s>ii?ii:s,null);if(e.startsWith(oi)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:i}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),l===Po.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==Po.BACKWARD)return{code:0,data:c};{if(u(r)&&u(i))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(n=null==r?void 0:r[r.length-1])?void 0:n.sequence)||0,t=(null==(o=null==i?void 0:i[i.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:r.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(ni)&&(c=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:e,count:s+1,time:t,direction:l}))){let{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=c;return s||(l===Po.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(d){return de(this,void 0,void 0,function*(){let t,{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:i,CONV_GROUP:n},message:o,apiMap:a}=this._core,l=e.conversationStore.getConversation(d);if(!l)throw new s({code:si});var u={fromAccount:r()},c=l["type"];c===i?(u.type=Jo,u.toAccount=d.replace(i,"")):c===n&&(u.type=Qo,u.toGroupID=d.replace(n,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:d});let e=yield function(i){return de(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=i,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return No.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(u);return e&&(o.messageDataHandler.deleteConversationMessageList(d),this._clearedConversations.add(d),this._fetchedCompleteConversations.delete(d),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(d),this._updateConversationLastMessage(d)),{code:0,data:{conversationID:d},successLog:{message:"convID:"+d}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:e,moreMessage:"convID:"+d})}})}_updateConversationLastMessage(e){var t=this._core["appStore"];t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e),r=s["length"];if(!t)return r;let i=-1;return null!=e&&e.startsWith(ni)?i=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(oi)&&(i=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===i?0:i}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return de(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),i=r.length;let n=i,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=i;return s?(l=r.findIndex(e=>t.startsWith(ni)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,n=l):a=e<i?i-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=r.slice(a,l),o.isCompleted=n<=e,t.startsWith(ni)&&(yield ai(t),yield ri({messageList:o.messageList,conversationID:t})),o})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){var 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}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}},Pi=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(i){return de(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=i,r=yield function(n,o){return de(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=n,{store:r,common:i}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=r.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=r.get("instance"))?void 0:e.sdkAppId},s=yield i.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},wi=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return de(this,void 0,void 0,function*(){let{message:e,language:t=Fo.ZH_PY}=s,r=(e.payload||{})["url"];var i=this._core.common.getCurrentUserID(),i=(e.from===i&&"out"===e.flow&&(r=e.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(n=Ko.exec(r))?void 0:n[1])||"mp3"),n=jo[t]||Bo;try{let s=yield function(e){var{store:t,common:s}=No.core,{url:e,format:r,serverLanguageType:i}=e,i={BytesUrl:e,BytesEngServiceType:i,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:i})}({url:r,format:i,serverLanguageType:n});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!Ko.test(e))throw new this._core.common.ChatError({code:2119})}};class Gi{constructor(e){var{constants:t,common:s,utils:r}=No.core,{CONV_C2C:t,CONV_GROUP:i}=t.OuterConstant,{ID:e,tinyID:n,from:o,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:l,sequence:u,cloudCustomData:c="",nick:d="",avatar:h="",clientSequence:g,conversationType:p,groupID:_,_elements:m,time:v}=e,n=(this.ID=e||n+`-${s}-`+l,this.messageRandom=l,this.from=o,this.messageSender=o,this.time=v,this.messageSequence=u,this.clientSequence=g||u,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=h,this.nick=d,r.deepCopyWithMethods(m));n.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=n,e?p.startsWith(t)?this.receiverUserID=a:p.startsWith(i)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ui{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:i,JsonMsgKey:n}=e||{},e=e.map(e=>li(e));return new Ui({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:i,downloadKey:n})}constructor(e){this.type=No.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:i,pbDownloadKey:n="",downloadKey:o="",version:a=0,layersOverLimit:l=!1}=e,u=[];t.forEach(e=>{e&&(e=new Gi(e),u.push(e))}),this.content={messageList:u,title:s,abstractList:r,compatibleText:i,version:a,downloadKey:o,pbDownloadKey:n,layersOverLimit:l}}validateBeforeSend(){var e=No.core.helper["isEmpty"];return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{abstractList:e,compatibleText:t,downloadKey:s,layersOverLimit:r,pbDownloadKey:i,title:n,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:i,Title:n,Version:o,MsgList:ui(a)}}}}var ki=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Ui),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===r.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){var t,s=this._core["common"];return e?(t=new Ui(e.payload),s=s.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setRelayFlag(!0),e.setElement(t),e):null}sendMessage(a,l){return de(this,void 0,void 0,function*(){var e,t,s;try{var n=function(t){let e="utf-8";No.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,i;if(i=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,i=null;if(11264<n){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return de(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:ui(e)};return No.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];i=new Ui(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(i)}catch(e){console.error(e)}}var{message:o}=(yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,l))["data"];return i&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(o){return de(this,void 0,void 0,function*(){let r=this._core["ssoLog"],e=o.payload,{downloadKey:i,pbDownload:t,type:s}=e,n=le(e,["downloadKey","pbDownload","type","messageList"]);try{let e=yield function(e){return de(this,void 0,void 0,function*(){return No.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(i),t=(e||{})["MsgList"],s=null==t?void 0:t.map(e=>{e=li(e);return new Gi(e)});return"function"==typeof o.isOnlineMessage?o.setElement({type:o.type,content:Object.assign({messageList:s},n)}):(o.payload.messageList=s,o.payload.downloadKey="",o.payload.pbDownloadKey=""),r.info("downloadMergerMessage"," success downloadKey:"+i),o}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:i})}})}},Fi=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return de(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:r}}=this._core,{GroupId:i,To_Account:n}=a,o=(a.From_Account=a.From_Account||s(),null);if(i){o=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:i}));let e=t.userStore.getUserProfile(s());o.level=(null==e?void 0:e.level)||0,r(n)&&0<n.length&&(o._receiverList=n)}else n&&(o=this._generateC2CMessage(a));return e.messageSender.sendMessage(o,a)})}_generateC2CMessage(e){var{message:t,OuterConstant:{CONV_C2C:s}}=this._core,e=t.messageHelper.parseServerPushMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Xo.OUT})),s=e["elements"];return t.setElement(s),t}_generateGroupMessage(e){var{message:t,OuterConstant:{CONV_GROUP:s}}=this._core,e=t.messageHelper.parseServerGroupMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Xo.OUT})),s=e["elements"];return t.setElement(s),t}},$i=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_PINNED:r}}=this._core=e;t.subscribeInnerEvent(s,r,this._handleGroupMessagePinned,this),e.registerApi({apiName:"pinGroupMessage",context:this}),e.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(o){return de(this,void 0,void 0,function*(){let{ssoLog:e,common:{isTopic:t},OuterConstant:{},helper:{ChatError:r}}=this._core;var{groupID:s,message:i,isPinned:n}=o,i=i["sequence"];try{return yield function(o){return de(this,void 0,void 0,function*(){var{buildAndSendPacket:e,getCurrentUserID:t}=No.core["common"],{groupID:s,sequence:r,isPinned:i}=o,t=t(),n=i?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",s={GroupId:s,MsgSeq:r};return i?s.Pinner_Account=t:s.UnPinner_Account=t,e({servcmd:n,data:s})})}({groupID:s,sequence:i,isPinned:n}),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};throw new r({code:t,message:s})}})}getPinnedGroupMessageList(r){return de(this,void 0,void 0,function*(){let e=[];try{var t,s=yield function(s){return de(this,void 0,void 0,function*(){var e=s["groupID"],{buildAndSendPacket:t}=No.core["common"];return t({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:e}})})}({groupID:r});return s&&({PinnedMsgList:t=[]}=s,e=yield this._updatePinnedMessageInfo({serverPinnedMessageList:t,groupID:r})),{code:0,data:{messageList:e}}}catch(e){throw e}})}_handleGroupMessagePinned(e){let{message:{messageHelper:u,messageFactory:c},notificationCenter:d,OuterEvent:h,OuterConstant:g}=this._core;e.GroupTips.forEach(e=>{var{ToGroupId:e,MsgBody:{PinnedMsg:t,OpType:s,MsgOperatorMemberExtraInfo:r,SdkGroupMessageId:n}}=e,{UserId:r,NickName:i="",ImageUrl:o=""}=r;let a=null,l=!1;if(s===Zo){l=!0;let e=u.parseServerGroupMessage(t);(a=c.createMessage(Object.assign(Object.assign({},e),{conversationType:g.CONV_GROUP,flow:"in"}))).setElement(e.elements),a.pinnerInfo={userID:r,nick:i,avatar:o}}else if(s===ei){let{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:r,MsgSeq:i}=n;a={ID:`${s}-${e}-`+t,sequence:i,random:t,time:r,clientTime:e}}a&&d.emitOuterEvent(h.PINNED_GROUP_MESSAGE_UPDATED,{name:h.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:e,message:a,isPinned:l,operatorInfo:{userID:r,nick:i,avatar:o}}})})}_findMessageBySequence(e,t){var{messageDataHandler:s}=this._core["message"];return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return de(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:e}){let{OuterConstant:{CONV_GROUP:t},utils:{isEmpty:s}}=this._core,o=[],a=[],l=[],u=new Map,c=""+t+e;for(let i=0;i<n.length;i++){let e=n[i],{Pinner_Account:t,MsgSeq:s}=e,r=this._findMessageBySequence(c,s);a.push(t),u.set(s,t),r?o.push(r):l.push(s)}let r=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:l,pinnerIDList:a});if(r){let{pinnerInfoMap:s,messageList:e}=r;return o.push(...e),o.forEach(e=>{var t=e["sequence"],t=u.get(t),t=s[t]||{userID:t,nick:"",avatar:""};e.pinnerInfo=t}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(n){return de(this,void 0,void 0,function*(){var{message:{},user:{userProfile:e},utils:{isArray:t}}=this._core,{conversationID:s,messageSequenceList:i,pinnerIDList:r}=n,s=yield Promise.all([this._fetchMessageBySequence({conversationID:s,messageSequenceList:i}),null==e?void 0:e.getUserProfile({userIDList:r})]);if(t(s)){let r={};return((null==(i=s[1])?void 0:i.data)||[]).forEach(e=>{var{userID:e,nick:t="",avatar:s=""}=e;r[e]={userID:e,nick:t,avatar:s}}),{messageList:(null==(e=s[0])?void 0:e.messageList)||[],pinnerInfoMap:r}}})}_fetchMessageBySequence(i){return de(this,void 0,void 0,function*(){var{utils:{isEmpty:e},message:{messageHistory:t}}=this._core,{conversationID:s,messageSequenceList:r}=i;return e(r)?[]:t.getGroupRoamingMessagesByAnchor({conversationID:s,messageSequenceList:r,getType:3})})}},qi=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,No.init(e),Mi.init(e),Ai.init(e),Di.init(e),Li.init(e),di.init(e),Pi.init(e),wi.init(e),hi.init(e),ki.init(e),_i.init(e),Fi.init(e),$i.init(e),e.helper.registerValidateConfig({auth:Ii,params:fi}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),Di.dispose(),Li.dispose(),hi.dispose(),_i.dispose()}_reset(){Li.reset()}},xi=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(p,_){return de(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:i,qs:n,headers:o={},resources:a,dataType:l="text",uploadByIP:u,uploadIP:c}=p,d=i;if(n){let e=this._queryString(n);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(r.toUpperCase(),d,!0),h.responseType=l;var g=Object.assign({},o);if(u&&c&&(g.host=c),!t(g))for(let e in g)g.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&h.setRequestHeader(e,g[e]);return h.onload=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e);if(200===h.status)_(null,e);else{if(c&&!d.includes(c))return p.url=this._domainName2IP(d,c),p.uploadByIP=!0,this.request(p,_);_({code:h.status,message:JSON.stringify(h.responseText)},e)}},h.onerror=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e),t={code:h.status,message:0===h.status?"CORS blocked or network error":JSON.stringify(h.responseText)};_(t,e)},p.onProgress&&h.upload&&(h.upload.onprogress=e=>{var{total:e,loaded:t}=e,s=Math.min(Math.floor(100*t/e),100);p.onProgress({total:e,loaded:t,percent:s/100})}),h.send(a),h})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{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(s,r="&",i="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+i;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let Vi=["unknown","image","video","audio","log"];var ar,Bi=new class{init(e){this._core=e}request(s,r){let{MINI_APP_NAMESPACE:e,IN_ALIPAY_MINI_APP:i,isUniIOSApp:n}=null==(h=this._core)?void 0:h.utils,{resources:o="",headers:a={},url:l,downloadUrl:u=""}=s,c=l,d=null;var h=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(h){var h=decodeURIComponent(h[3]),h=h.includes("?")?h.split("?")[0]:h||"",h={key:s.fileKey||h,success_action_status:200,"Content-Type":""},g={};if(n()){let[e,t]=l.split("?sign=");t&&(c=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:c,header:a,name:"file",filePath:o,formData:Object.assign(Object.assign({},h),g),timeout:s.timeout||3e5};if(i){let{}=t,e=le(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?Vi[s.fileType]:"image"})}return(d=e.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})}}))).onProgressUpdate&&d.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),d}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var i=+t.statusCode;200==i?s(null,{statusCode:i,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:i,message:JSON.stringify(t.data)},{statusCode:i,headers:r,data:void 0})}};function ji(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Ki(e){e=e||99999999;return Math.round(Math.random()*e)}function Hi(e,t=!0,s=!0){var r=Date.now();return t?s?r-e+" ms":Math.round((r-e)/1e3)+" s":s?r-e:Math.round((r-e)/1e3)}function Wi(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Yi(e,t){return Math.round(Number(e)*10**t)/10**t}function zi(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function Ji(e){return e<=1048576?Yi(e/1024,1)+"KB/s":Yi(e/1048576,1)+"MB/s"}let Qi="TIMImageElem",Xi="TIMSoundElem",Zi="TIMFileElem",er="TIMVideoFileElem",tr="RichMediaMessagePlugin",sr=["rich.my-imcloud.com","imrich.qcloud.com"],nr=1,or=2,ir=3,rr=255,cr=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(ar=ar||{}),{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\/)/}),ur=Symbol("isCustomUpload");var lr,dr=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(s){{var[s,r]=s.split("?");if(!r)return s;let t=r.split("&").reduce((e,t)=>{var[t,s]=t.split("=");return t&&"authKey"!==t&&(e[t]=s||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?s+"?"+e:s}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(cr).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return ji(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(s){return de(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(s):e?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=sr;var s=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==s)try{JSON.parse(s).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=sr}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),i=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,i));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}generateURL(e,t){var{needAddAuthToUrl:t=!0}=t||{};return t?this.addAuthToUrl(e):e}_probeImageDimensionsMiniApp(e){let t,s=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;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{IN_RN_APP:e,IS_IE:t,IE_VERSION:s,IN_WX_MINI_GAME:r}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===s||r}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,s=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),s()},t.onerror=()=>{e({width:0,height:0}),s()},t.src=r})}},hr={exports:{}},gr=(lr||(lr=1,hr.exports=function(){var r=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function l(e,t){var s=e[0],r=e[1],i=e[2],n=e[3],r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[0]-680876936|0)<<7|s>>>25)+r|0)&r|~s&i)+t[1]-389564586|0)<<12|n>>>20)+s|0)&s|~n&r)+t[2]+606105819|0)<<17|i>>>15)+n|0)&n|~i&s)+t[3]-1044525330|0)<<22|r>>>10)+i|0;r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[4]-176418897|0)<<7|s>>>25)+r|0)&r|~s&i)+t[5]+1200080426|0)<<12|n>>>20)+s|0)&s|~n&r)+t[6]-1473231341|0)<<17|i>>>15)+n|0)&n|~i&s)+t[7]-45705983|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[8]+1770035416|0)<<7|s>>>25)+r|0)&r|~s&i)+t[9]-1958414417|0)<<12|n>>>20)+s|0)&s|~n&r)+t[10]-42063|0)<<17|i>>>15)+n|0)&n|~i&s)+t[11]-1990404162|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[12]+1804603682|0)<<7|s>>>25)+r|0)&r|~s&i)+t[13]-40341101|0)<<12|n>>>20)+s|0)&s|~n&r)+t[14]-1502002290|0)<<17|i>>>15)+n|0)&n|~i&s)+t[15]+1236535329|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[1]-165796510|0)<<5|s>>>27)+r|0)&i|r&~i)+t[6]-1069501632|0)<<9|n>>>23)+s|0)&r|s&~r)+t[11]+643717713|0)<<14|i>>>18)+n|0)&s|n&~s)+t[0]-373897302|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[5]-701558691|0)<<5|s>>>27)+r|0)&i|r&~i)+t[10]+38016083|0)<<9|n>>>23)+s|0)&r|s&~r)+t[15]-660478335|0)<<14|i>>>18)+n|0)&s|n&~s)+t[4]-405537848|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[9]+568446438|0)<<5|s>>>27)+r|0)&i|r&~i)+t[14]-1019803690|0)<<9|n>>>23)+s|0)&r|s&~r)+t[3]-187363961|0)<<14|i>>>18)+n|0)&s|n&~s)+t[8]+1163531501|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[13]-1444681467|0)<<5|s>>>27)+r|0)&i|r&~i)+t[2]-51403784|0)<<9|n>>>23)+s|0)&r|s&~r)+t[7]+1735328473|0)<<14|i>>>18)+n|0)&s|n&~s)+t[12]-1926607734|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[5]-378558|0)<<4|s>>>28)+r|0)^r^i)+t[8]-2022574463|0)<<11|n>>>21)+s|0)^s^r)+t[11]+1839030562|0)<<16|i>>>16)+n|0)^n^s)+t[14]-35309556|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[1]-1530992060|0)<<4|s>>>28)+r|0)^r^i)+t[4]+1272893353|0)<<11|n>>>21)+s|0)^s^r)+t[7]-155497632|0)<<16|i>>>16)+n|0)^n^s)+t[10]-1094730640|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[13]+681279174|0)<<4|s>>>28)+r|0)^r^i)+t[0]-358537222|0)<<11|n>>>21)+s|0)^s^r)+t[3]-722521979|0)<<16|i>>>16)+n|0)^n^s)+t[6]+76029189|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[9]-640364487|0)<<4|s>>>28)+r|0)^r^i)+t[12]-421815835|0)<<11|n>>>21)+s|0)^s^r)+t[15]+530742520|0)<<16|i>>>16)+n|0)^n^s)+t[2]-995338651|0)<<23|r>>>9)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[0]-198630844|0)<<6|s>>>26)+r|0)|~i))+t[7]+1126891415|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[14]-1416354905|0)<<15|i>>>17)+n|0)|~s))+t[5]-57434055|0)<<21|r>>>11)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[12]+1700485571|0)<<6|s>>>26)+r|0)|~i))+t[3]-1894986606|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[10]-1051523|0)<<15|i>>>17)+n|0)|~s))+t[1]-2054922799|0)<<21|r>>>11)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[8]+1873313359|0)<<6|s>>>26)+r|0)|~i))+t[15]-30611744|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[6]-1560198380|0)<<15|i>>>17)+n|0)|~s))+t[13]+1309151649|0)<<21|r>>>11)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[4]-145523070|0)<<6|s>>>26)+r|0)|~i))+t[11]-1120210379|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[2]+718787259|0)<<15|i>>>17)+n|0)|~s))+t[9]-343485551|0)<<21|r>>>11)+i|0,e[0]=s+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=n+e[3]|0}function u(e){for(var t=[],s=0;s<64;s+=4)t[s>>2]=e.charCodeAt(s)+(e.charCodeAt(s+1)<<8)+(e.charCodeAt(s+2)<<16)+(e.charCodeAt(s+3)<<24);return t}function c(e){for(var t=[],s=0;s<64;s+=4)t[s>>2]=e[s]+(e[s+1]<<8)+(e[s+2]<<16)+(e[s+3]<<24);return t}function s(e){for(var t,s,r,i,n=e.length,o=[1732584193,-271733879,-1732584194,271733878],a=64;a<=n;a+=64)l(o,u(e.substring(a-64,a)));for(t=(e=e.substring(a-64)).length,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0;a<t;a+=1)s[a>>2]|=e.charCodeAt(a)<<(a%4<<3);if(s[a>>2]|=128<<(a%4<<3),55<a)for(l(o,s),a=0;a<16;a+=1)s[a]=0;return i=(i=8*n).toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(i[2],16),i=parseInt(i[1],16)||0,s[14]=r,s[15]=i,l(o,s),o}function o(e){for(var t=0;t<e.length;t+=1)e[t]=function(e){for(var t="",s=0;s<4;s+=1)t+=r[e>>8*s+4&15]+r[e>>8*s&15];return t}(e[t]);return e.join("")}function i(e){return e=/[\u0080-\uFFFF]/.test(e)?unescape(encodeURIComponent(e)):e}function a(e){for(var t=[],s=e.length,r=0;r<s-1;r+=2)t.push(parseInt(e.substr(r,2),16));return String.fromCharCode.apply(String,t)}function n(){this.reset()}return o(s("hello")),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||(ArrayBuffer.prototype.slice=function(e,t){var s=this.byteLength,e=d(e,s),r=s;return(r=void 0!==t?d(t,s):r)<e?new ArrayBuffer(0):(t=r-e,s=new ArrayBuffer(t),r=new Uint8Array(s),e=new Uint8Array(this,e,t),r.set(e),s)}),n.prototype.append=function(e){return this.appendBinary(i(e)),this},n.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;for(var t=this._buff.length,s=64;s<=t;s+=64)l(this._hash,u(this._buff.substring(s-64,s)));return this._buff=this._buff.substring(s-64),this},n.prototype.end=function(e){for(var t,s=this._buff,r=s.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<r;n+=1)i[n>>2]|=s.charCodeAt(n)<<(n%4<<3);return this._finish(i,r),t=o(this._hash),e&&(t=a(t)),this.reset(),t},n.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},n.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},n.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},n.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},n.prototype._finish=function(e,t){var s,r=t;if(e[r>>2]|=128<<(r%4<<3),55<r)for(l(this._hash,e),r=0;r<16;r+=1)e[r]=0;t=(t=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(t[2],16),t=parseInt(t[1],16)||0,e[14]=s,e[15]=t,l(this._hash,e)},n.hash=function(e,t){return n.hashBinary(i(e),t)},n.hashBinary=function(e,t){e=o(s(e));return t?a(e):e},(n.ArrayBuffer=function(){this.reset()}).prototype.append=function(e){s=this._buff.buffer,r=e,(i=new Uint8Array(s.byteLength+r.byteLength)).set(new Uint8Array(s)),i.set(new Uint8Array(r),s.byteLength);var t,s,r,i,n=i,o=n.length;for(this._length+=e.byteLength,t=64;t<=o;t+=64)l(this._hash,c(n.subarray(t-64,t)));return this._buff=t-64<o?new Uint8Array(n.buffer.slice(t-64)):new Uint8Array(0),this},n.ArrayBuffer.prototype.end=function(e){for(var t,s=this._buff,r=s.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<r;n+=1)i[n>>2]|=s[n]<<(n%4<<3);return this._finish(i,r),t=o(this._hash),e&&(t=a(t)),this.reset(),t},n.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},n.ArrayBuffer.prototype.getState=function(){var e,t=n.prototype.getState.call(this);return t.buff=(e=t.buff,String.fromCharCode.apply(null,new Uint8Array(e))),t},n.ArrayBuffer.prototype.setState=function(e){return e.buff=function(e,t){for(var s=e.length,r=new ArrayBuffer(s),i=new Uint8Array(r),n=0;n<s;n+=1)i[n]=e.charCodeAt(n);return t?i:r}(e.buff,!0),n.prototype.setState.call(this,e)},n.ArrayBuffer.prototype.destroy=n.prototype.destroy,n.ArrayBuffer.prototype._finish=n.prototype._finish,n.ArrayBuffer.hash=function(e,t){e=o(function(e){for(var t,s,r,i,n=e.length,o=[1732584193,-271733879,-1732584194,271733878],a=64;a<=n;a+=64)l(o,c(e.subarray(a-64,a)));for(t=(e=a-64<n?e.subarray(a-64):new Uint8Array(0)).length,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0;a<t;a+=1)s[a>>2]|=e[a]<<(a%4<<3);if(s[a>>2]|=128<<(a%4<<3),55<a)for(l(o,s),a=0;a<16;a+=1)s[a]=0;return i=(i=8*n).toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(i[2],16),i=parseInt(i[1],16)||0,s[14]=r,s[15]=i,l(o,s),o}(new Uint8Array(e)));return t?a(e):e},n;function d(e,t){return(e=0|e||0)<0?Math.max(e+t,0):Math.min(e,t)}}()),hr.exports),pr=Yt(gr),_r=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).utils["IN_MINI_APP"];this.httpRequest=t?Bi:xi,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(u){return de(this,void 0,void 0,function*(){let r=tr+" uploadToCOS",{ssoLog:i,utils:{safeStringify:t}}=this._core,n=u["file"];this.uploadFileType=u.uploadFileType,i.debug("uploadToCOS",r+" options:"+t(u));try{let e=Date.now(),t=yield this._createCosOptions(u),s=t.fileExistsInCOS?{data:{location:t.downloadUrl}}:yield this._uploadFile(t);this._handleUploadError(s,u);var o=this._createUploadResult(n,s),a=Date.now()-e,l=`size:${zi(n.size)} time:${a}ms speed:`+Ji(1e3*n.size/a);return i.debug("uploadToCOS",r+` ok. name:${n.name} `+l),{uploadOptions:t,response:o}}catch(e){throw i.warn("uploadToCOS",r+" failed, error:"+t(e)),e}})}_handleUploadError(e,t){var s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(403===e.statusCode)throw t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new s({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:Hi(Date.now(),!1),uploadSpeed:Ji(1e3*e.size/Hi(Date.now(),!1))}}_createCosOptions(g){return de(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:s}=yield this._prepareUploadParams(g),r=this._isC2CConversation(g.message.conversationID)?1:2;try{var i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:g.message.from,conversationType:r}),{uploadUrl:n,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,existFlag:d}=i,h=!dr.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,uploadIP:h||"",fileExistsInCOS:1===d,onProgress:e=>this._handleUploadProgress(e,g)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(o){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t,isEmpty:s}}=this._core,e=(e.debug("_prepareUploadParams"," prepareUploadParams:"+t(o)),o)["file"],{IN_MINI_APP:t,IN_RN_APP:r}=dr.getPlatformFlags(),t=t||r,r=t&&o.message.type!==Zi,i=e["name"],i=i.slice(i.lastIndexOf(".")),n=""+Ki(999999)+i,r=r?e.name:n,n=yield this._generateHashFileName(e);return{fileName:s(n)?Wi(r):""+n+i,resources:t?e.url:e,uploadMethod:t?1:0}})}_generateHashFileName(a){return de(this,void 0,void 0,function*(){var{utils:{IN_MINI_APP:e,IN_BROWSER:t,IN_UNI_NATIVE_APP:s,isArray:r},ssoLog:i}=this._core,n=Date.now();let o="";return t&&(o=yield this._generateHashFileNameInWeb(a)),e&&(r(a.tempFiles)&&(a=a.tempFiles[0]),s||(o=yield this._generateFileNameInMiniProgram(a)),s)&&(o=yield this._generateFileNameInUNINativeApp(a)),i.info("_generateHashFileName",`hashFileName:${o} costTime:`+(Date.now()-n)),o})}_generateHashFileNameInWeb(h){return de(this,void 0,void 0,function*(){let{ssoLog:d,utils:{safeStringify:t}}=this._core,e="";try{e=yield new Promise((t,s)=>{let r=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice,i=(r||(d.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),t("")),10485760),n=Math.ceil(h.size/i),o=0,a=new pr.ArrayBuffer,l=new FileReader,u=setTimeout(()=>{l.abort(),d.warn("_generateHashFileNameInWeb","File hash generation timeout"),t("")},2e3);function c(){var e=o*i,t=e+i>=h.size?h.size:e+i;l.readAsArrayBuffer(r.call(h,e,t))}l.onload=e=>{d.debug("_generateHashFileNameInWeb",`read chunk nr ${o+1} of `+n),a.append(e.target.result),++o<n?c():(d.debug("_generateHashFileNameInWeb","finished loading"),clearTimeout(u),t(a.end()))},l.onerror=e=>{clearTimeout(u),s(e)},c()})}catch(e){d.warn("_generateHashFileNameInWeb",t(e))}return e})}_generateFileNameInMiniProgram(n){return de(this,void 0,void 0,function*(){let{utils:{MINI_APP_NAMESPACE:e,safeStringify:t,isEmpty:s},ssoLog:r}=this._core,i="";if(s(n.url))r.warn("_generateFileNameInMiniProgram","file.url is empty");else if("function"!=typeof(null==e?void 0:e.getFileSystemManager))r.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function");else try{i=yield new Promise((t,s)=>{e.getFileSystemManager().getFileInfo({filePath:n.url,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){r.warn("_generateFileNameInMiniProgram",t(e))}return i})}_generateFileNameInUNINativeApp(i){return de(this,void 0,void 0,function*(){var{utils:{safeStringify:t,isEmpty:e},ssoLog:s}=this._core;let r="";if(e(i.url))s.warn("_generateFileNameInUNINativeApp","file.url is empty");else if("function"!=typeof(null==(e=null===plus||void 0===plus?void 0:plus.io)?void 0:e.getFileInfo))s.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function");else try{r=yield new Promise((t,s)=>{plus.io.getFileInfo({filePath:i.url,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){s.warn("_generateFileNameInMiniProgram",t(e))}return r})}_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 de(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core,r=dr.isSimpleCos(),i=this._prepareCosRequestData(e),n=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(i,n,o){return de(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:i,data:n}),r=s.head.seq+i;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(n,i,this._core);this.fetchCosTryCount=0;var o=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+s(o)),o||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;let s=dr.isSimpleCos(),l=s?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(s){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:r,str_download_url:i,str_upload_url:n,str_snapshot_url:o,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:i,uploadUrl:n,requestSnapshotUrl:o,fileKey:a}}let{upload_url:r,download_url:i,snapshot_url:n,thumb_url:o,large_url:a,file_key:u}=l;return{uploadUrl:r,downloadUrl:i,requestSnapshotUrl:n,thumbUrl:o,largeUrl:a,fileKey:u}}_prepareCosRequestData(e){return dr.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:dr.getPlatform(),uint32_sdkappid:dr.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(i){return de(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(i,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(i).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}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{var r=null==(t=e.error)?void 0:t.Code,i=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=dr.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let mr=2108,vr=2251,fr=2252,Ir=["jpg","jpeg","gif","png","bmp","image","webp"],Er=20971520,Sr={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Cr{constructor(e,t){this.instanceID=Ki(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=dr.addAuthToUrl(e.imageUrl||e.url||""),this.url=dr.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=dr.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Mr(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,i=parseInt(e)||0,s=parseInt(s)||0,n={url:void 0,width:0,height:0};if((i<=s?i:s)<=r)n.url=t,n.width=i,n.height=s;else{s<=i?(n.width=Math.ceil(i*r/s),n.height=r):(n.width=r,n.height=Math.ceil(s*r/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";n.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}if(void 0!==t)return n;return le(n,["url"])}class yr{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Qi;var{uuid:e,file:t,imageFormat:s,imageInfoArray:r=[],isCustomUpload:i=!1}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:s,uuid:e,imageInfoArray:[]},this[ur]=i,this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:s,ImageInfoArray:r,UUID:i}=t,n=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new yr({imageFormat:s,imageInfoArray:n,uuid:i})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:i}=dr.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),i)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new Cr(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,s;e.url&&""!==e.imageUrl&&([t,...s]=e.imageUrl.split("://"),s=s.join("://"),r.includes(t)||e.setImageUrl("https://"+s))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=Sr[e.toUpperCase()]||Sr.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var s,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)s=this.content.imageInfoArray[e],t[e].size&&(s.size=t[e].size),t[e].url&&s.setImageUrl(t[e].url),t[e].width&&(s.width=t[e].width),t[e].height&&(s.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,s=t[2];t[2]=t[1],t[1]=s;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],Mr({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var e;return this[ur]?(delete this[ur],{isValid:!0}):([e]=this.content.imageInfoArray,{isValid:e=!!e&&""!==e.imageUrl&&0!==e.size,error:e?null:{message:"content can not be empty"}})}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(s),UUID:e}}}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:dr.removeAuthToUrl(e.imageUrl)}))}}var Or=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),t.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Qi,yr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,r;try{var i=null==(t=this._core.store.get("login"))?void 0:t.userId,n=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),o=this._processImage(e),a=(e.payload.file=o,{imageFormat:Sr.UNKNOWN,uuid:dr.generateUUID(o),file:o,imageInfoArray:[]}),l=new yr(a);return n.setElement(l),this._messageOptionsMap.set(n.clientSequence,e),n}catch(e){throw e}}createCustomUploadImageMessage(e){var{store:t,utils:{isEmpty:s}}=this._core,t=null==(t=t.get("login"))?void 0:t.userId,r=null==(r=null==(r=this._core)?void 0:r.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:t})),{largeImageUuid:t,largeFileSize:i,largeImageWidth:n,largeImageHeight:o,largeImageUrl:a,originImageUuid:l,originFileSize:u,originImageWidth:c,originImageHeight:d,originImageUrl:h,thumbImageUuid:g,thumbFileSize:p,thumbImageWidth:_,thumbImageHeight:m,thumbImageUrl:v}=(null==(t=null==e?void 0:e.payload)?void 0:t.file)||{};if(s(h)||s(l))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");s=new yr({imageFormat:Sr.UNKNOWN,uuid:l,imageInfoArray:[{instanceID:l,size:u,width:c,height:d,imageUrl:h,url:h},{instanceID:t,size:i,width:n,height:o,imageUrl:a,url:a},{instanceID:g,size:p,width:_,height:m,imageUrl:v,url:v}],isCustomUpload:!0});return r.setElement(s),this._messageOptionsMap.set(r.clientSequence,e),r._skipUpload=!0,r}upload(r){return de(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,i,s){return de(this,void 0,void 0,function*(){var e=i["to"],e={uploadFileType:nr,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{uploadOptions:e,response:t}=yield _r.uploadToCOS(e);return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:s,height:r,smallImageUrl:i,smallImageWidth:n,smallImageHeight:o,largeImageUrl:a,largeImageWidth:l,largeImageHeight:u,imageInfoArray:c}=e,e=dr.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):i&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:i,smallImageWidth:n,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return Mr({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,i;for(var n of e)1===n.type?(r=n,r.size=t):2===n.type?(i=n,i.size=t):(s=n,s.size=t);return[Object.assign({},s),Object.assign({},i),Object.assign({},r)]}_parseResponse(r,i){return de(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,i,"thumb"),yield this._getImageInfoByUrl(t,i,"large")),dr.isSimpleCos()&&!dr.isPrivateNetWork()&&(yield this._getImageInfoArray(s,i),null!=i)&&i.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,i))}return i}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,i,n){return de(this,void 0,void 0,function*(){var t;try{let e=dr.addAuthToUrl(r),{width:t=0,height:s=0}=yield dr.probeImageWidthHeight(e);i.width=t,i.height=s,"thumb"===n?(i.smallImageUrl=r,i.smallImageWidth=t,i.smallImageHeight=s):(i.largeImageUrl=r,i.largeImageWidth=t,i.largeImageHeight=s)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${n} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:vr});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var s=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return s?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){ji(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var 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=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=dr.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,i){return de(this,void 0,void 0,function*(){var e=tr+" getDownloadIP domainName: "+r;try{var t,s=yield function(o,a){return de(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=i.location.split("/"))[0]=s.str_final_ip,i.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,s){return de(this,void 0,void 0,function*(){try{var e=yield function(o,a){return de(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return s.imageInfoArray=this._processImageInfoResponse(e),s}catch(e){throw s.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.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){var{utils:t,helper:s}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),Ir.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:fr})}_checkImageSize(e){var{utils:t,helper:s}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new s.ChatError({code:mr});if(r>=Er)throw new s.ChatError({message:"File size exceeds limit: "+zi(Er)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Ar=2108,Tr=2401,Rr="2.5.0",Dr="1.18.0",br=104857600;function Nr(e,t){let r=e.split("."),i=t.split("."),n=Math.max(r.length,i.length);for(;r.length<n;)r.push("0");for(;i.length<n;)i.push("0");for(let s=0;s<n;s++){let e=parseInt(r[s]),t=parseInt(i[s]);if(e>t)return 1;if(e<t)return-1}return 0}let Lr=new class{init(e){this.core=e}};class wr{constructor(e){this.type=Zi,this.uploadProgress=0,this[Pr]=!1;var t=this._getFileInfo(e);this[ur]=e.isCustomUpload||!1,this.content={downloadFlag:2,fileUrl:dr.generateURL(e.url||e.fileUrl,{needAddAuthToUrl:!this[ur]})||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:s,FileSize:r,UUID:i}=e;return new wr({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e;return this[ur]?{isValid:!0}:{isValid:e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:s,fileName:r,fileSize:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:dr.removeAuthToUrl(s),FileName:r,FileSize:i,UUID:e}}}_getFileInfo(e){var t=Lr.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=Ki(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)}}var Pr=ur,Gr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),t.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Zi,wr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,r;try{this._checkVersion();var i=this._processFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={uuid:dr.generateUUID(i),file:i},l=new wr(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}createCustomUploadFileMessage(e){var t,s,r;try{var{store:i,message:n,utils:{isEmpty:o}}=this._core,a=null==(t=i.get("login"))?void 0:t.userId,{url:l,uuid:u,fileSize:c,fileName:d=""}=(null==(s=null==e?void 0:e.payload)?void 0:s.file)||{};if(o(l))throw new Error("url is required");var h=null==(r=n.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:a})),g=new wr({url:l,uuid:u,file:{size:c,name:d},isCustomUpload:!0});return h.setElement(g),h}catch(e){throw e}}upload(s){return de(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),s.getElements()[0]),e=yield this._performFileUpload(t,s,e),e=dr.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),s})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:Tr});if(e.size>br)throw new t({message:"File size exceeds limit: "+zi(br)});if(0===e.size)throw new t({code:Ar})}_performFileUpload(r,i,t){return de(this,void 0,void 0,function*(){var e=i["to"],e={uploadFileType:rr,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield _r.uploadToCOS(e))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e||n){let e=dr.extractFileFromInput(t);if(e)return e;throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||i){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils,n=(null==(n=this._core)?void 0:n.helper)["ChatError"];if(e){if(!(s||r||i))throw new n({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&Nr(e,Rr)<0)throw new n({message:`WXChooseMessageFile requires SDK version ${Rr} or higher`});if(r&&Nr(e,Dr)<0)throw new n({message:`QQChooseMessageFile requires SDK version ${Dr} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Ur=2108,kr=2352,Fr=["mp4","quicktime","mov"],$r=104857600;class xr{constructor(e){this.type=er,this.uploadProgress=0,this[qr]=!1;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this[ur]=e.isCustomUpload||!1,this.content={remoteVideoUrl:dr.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:dr.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:dr.addAuthToUrl(e.thumbUrl),snapshotUrl:dr.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:_,SnapshotUrl:m}=e;return new xr({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s}=e;dr.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),dr.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),dr.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){var e;return this[ur]?{isValid:!0}:{isValid:e=""!==this.content.remoteVideoUrl,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:dr.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:dr.removeAuthToUrl(_),SnapshotUrl:dr.removeAuthToUrl(m)}}}}var Vr,qr=ur,Br=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),t.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(er,xr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,r;try{var i=this._processVideo(e),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={videoFormat:i.videoFile.type,videoSecond:Yi(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:dr.generateUUID(i.videoFile),thumbUUID:dr.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},l=new xr(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}createCustomUploadVideoMessage(e){var t,s,r;try{var{store:i,message:n}=this._core,o=(this._validateCustomUploadVideoMessage(e),null==(t=i.get("login"))?void 0:t.userId),{videoUrl:a,videoUuid:l,duration:u,snapshotUrl:c,snapshotUuid:d,videoFileSize:h,videoType:g,snapshotWidth:p,snapshotHeight:_,snapshotFileSize:m,snapshotType:v="jpg"}=(null==(s=null==e?void 0:e.payload)?void 0:s.file)||{},f=null==(r=n.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),I=new xr({videoFormat:g,videoSecond:u||0,videoSize:h,remoteVideoUrl:a,videoUrl:a,videoUUID:l,thumbUUID:d,thumbWidth:p||200,thumbHeight:_||200,thumbUrl:c,thumbSize:m,thumbFormat:v,isCustomUpload:!0});return f.setElement(I),this._messageOptionsMap.set(f.clientSequence,e),f}catch(e){throw e}}upload(r){return de(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:s}=t,t=dr.addAuthToUrl(t);return e.updateVideoUrl(t),dr.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>$r)throw new t({message:"File size exceeds limit: "+zi($r)});if(0===e.videoFile.size)throw new t({code:Ur});if(-1===Fr.indexOf(e.videoFile.type))throw new t({code:kr})}_validateCustomUploadVideoMessage(e){var{isEmpty:t,isNumber:s}=this._core["utils"],{videoUrl:e,videoUuid:r,duration:i,snapshotUrl:n,snapshotUuid:o}=(null==(e=null==e?void 0:e.payload)?void 0:e.file)||{};if(t(e)||t(r)||!s(i)||t(n)||t(o))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(r,i,s){return de(this,void 0,void 0,function*(){var e=i["to"],e={uploadFileType:or,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{response:e,uploadOptions:t}=yield _r.uploadToCOS(e);return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,i;try{var n=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(i=this._core)?void 0:i.utils;let t=e.payload["file"],s={};if(o&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url,t.type=s.type),a){let e=dr.extractFileFromInput(t);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,s=this._processWebVideoFile(t)}return t.videoFile=s,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(tr+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:s}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(ji(e))throw new r({message:"FileUnsupportedInMiniApp"});let i=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(i=e.fileType||i),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:i}}_processWebVideoFile(e){var{name:t,size:s=1,duration:r=0,type:i}=e,i=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:i}}_getSnapshotInfoByUrl(n){return de(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",tr+" _getSnapshotInfoByUrl url:"+n);var t,s,r,i=((yield function(n,o){return de(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,r=t.generateCosSpecifiedData({servcmd:e,data:n}),i=r.head.seq+e;return yield s.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:dr.getPlatform(),cover_name:Wi(Ki(99999)),snapshot_url:n},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",tr+" _getSnapshotInfoByUrl OK snapshotUrl:"+i),dr.isEmpty(i))?{}:(t=dr.addAuthToUrl(i),{width:s=0,height:r=0}=yield dr.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:s,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class jr{constructor(e){this.uploadProgress=0,this.type=Xi,this[Vr]=!1,this[ur]=e.isCustomUpload||!1,this.content={downloadFlag:2,second:e.second,size:e.size,url:dr.generateURL(e.url,{needAddAuthToUrl:!this[ur]}),remoteAudioUrl:dr.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:i}=e;return new jr({url:e,downloadFlag:t,second:s,size:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e;return this[ur]?{isValid:!0}:{isValid:e=""!==this.content.remoteAudioUrl,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:s,size:r,second:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:dr.removeAuthToUrl(s),Download_Flag:t,Second:i,Size:r,UUID:e}}}}Vr=ur;let Kr=2108,Hr=2300,Wr=20971520;var Yr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),t.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Xi,jr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,r;try{var i=e.payload["file"],i=this._processAudioFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:dr.generateUUID(i)},l=new jr(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}createCustomUploadAudioMessage(e){var t,s,r;try{this._validateCustomUploadOptions(e);var{store:i,message:n}=this._core,o=null==(t=i.get("login"))?void 0:t.userId,{url:a,uuid:l,duration:u,fileSize:c}=(null==(s=null==e?void 0:e.payload)?void 0:s.file)||{},d=null==(r=n.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),h=new jr({second:u,size:c||1,url:a,uuid:l,isCustomUpload:!0});return d.setElement(h),this._messageOptionsMap.set(d.clientSequence,e),d}catch(e){throw e}}upload(s){return de(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",tr+" uploadAudio message:"+t(s)),this._messageOptionsMap.get(s.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),s.getElements()[0]),e=yield this._performAudioUpload(t,s,e),e=dr.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),s})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:Hr});if(e.size>Wr)throw new t({message:"File size exceeds limit: "+zi(Wr)});if(0===e.size)throw new t({code:Kr})}_performAudioUpload(r,i,t){return de(this,void 0,void 0,function*(){var e=i["to"],e={uploadFileType:ir,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield _r.uploadToCOS(e))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:s}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):s?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){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_validateCustomUploadOptions(e){var t=this._core["utils"]["isEmpty"],{url:e,uuid:s,duration:r}=(null==(e=null==e?void 0:e.payload)?void 0:e.file)||{};if(t(e)||t(s)||t(r))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let zr={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}},Jr={createImageMessage:zr,createAudioMessage:zr,createVideoMessage:zr,createFileMessage:zr},Qr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Xr={[Qi]:Or,[Zi]:Gr,[er]:Br,[Xi]:Yr};var ua,la,da,Zr=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:i}}=(this._core=e)["constants"];Lr.init(e),Or.init(e),Gr.init(e),Br.init(e),Yr.init(e),_r.init(e),dr.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,i].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Qr,params:Jr})}sendMessage(r,i){return de(this,void 0,void 0,function*(){var e,t,s;try{return this._isCustomUpload(r)||(yield this._upload(r)),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,i)}catch(e){throw e}})}_upload(s){return de(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(s)),!0!==s._relayFlag)try{let e=Xr[s.type];e&&(yield e.upload(s),t.info("_upload"," type:"+s.type))}catch(t){throw s.status=ar.FAIL,t instanceof Error&&(t.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),t}})}_isCustomUpload(e){return!0===(null==(e=null==(e=e._elements)?void 0:e[0])?void 0:e[ur])}};let ea=new class{init(e){this.core=e}},ta=e=>{var{OuterConstant:t,utils:{isString:s}}=ea["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},sa=e=>{var{OuterConstant:t,utils:{isString:s}}=ea["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},na=e=>{var{OuterConstant:t,utils:{isString:s}}=ea["core"];return s(e)&&e===t.CONV_SYSTEM},oa=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:ea.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 ia(e){var t=ea.core["OuterConstant"];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 ra(e){var t=ea.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}function aa(e,t){var s=ea.core["helper"],s=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:",s),s}class ca{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=oa(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{OuterConstant:e,utils:{isUndefined:t}}=ea["core"];t(this.userProfile)&&this.type===e.CONV_C2C?this.userProfile={}:t(this.groupProfile)&&this.type===e.CONV_GROUP&&(this.groupProfile={}),this.subType&&this.type===e.CONV_GROUP&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){var{OuterConstant:t,utils:{isUndefined:s}}=ea["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:i}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=oa(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=ea["core"]["OuterConstant"],{sequence:e,time:s}=e;return this.type===t.CONV_C2C&&e===this.lastMessage.lastSequence&&s===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&e===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=ea["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(ua=ua||{}),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(la=la||{}),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"}(da=da||{});let ha=0,ga=1;var pa=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:t,notificationCenter:s,appStore:{conversationStore:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n},InnerEvent:{SYNC_CONVERSATION_LIST:o,MESSAGE_PUSH:a,NEW_MESSAGE:l,MESSAGE_DELETED:u,MESSAGE_REVOKED:c,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:h,LOGOUT:g,DESTROY:p},InnerEventSubType:{C2C_MESSAGE_PEER_READ:_}}=this._core=e,r=(this._conversationStore=r,t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_TIPS_NOTIFICATION,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s)["InnerEventSubType"]["GROUP_AT_TIPS"];s.subscribeInnerEvent(o,this._handleConversationSynced,this),s.subscribeInnerEvent(l,this._handleNewMessage,this),s.subscribeInnerEvent(a,r,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(h,this._handleConversationUpdated,this),s.subscribeInnerEvent(a,_,this._handleMessageRead,this),s.subscribeInnerEvent(g,this._reset,this),s.subscribeInnerEvent(p,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){let{WORKFLOW_STEP:t}=this._core["constants"],{conversationUpdateFieldList:s=[],groupTipList:r=[],isUnreadC2CMessage:i}=e.result[t.UNREAD_MESSAGE_SYNC]||{},n=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:i}),n=!0)}),n&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,i=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:n}=this._core.OuterConstant,o=!1;for(let s=0;s<i.length;s++){let e=i[s],t=""+n+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:i=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:i}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:i}=e;let n={};t?n=this._convertGroupAtTipsKey(t):s?n=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(n=Object.assign({},e)),n.__random=r,n.__sequence=i,this._groupAtTipsList.push(n)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,i=e.getCurrentUserID(),n=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==i){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:i}=this._core,n=(null==r?void 0:r.getLocalMessageList(t))||[];let o={};for(let e=(n.length||0)-1;0<=e;e--)if(!n[e].isDeleted){o=n[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===o.sequence&&r.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),r.updateLastMessage(o),e=!0),t.startsWith(i.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:i=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(i&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:i}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let 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){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),this._core.ssoLog.debug("updateLocalConversationList"," newConversationList: "+e.length)}_getTmpConversationListMapping(e){let n=this._core["OuterConstant"],{conversationUpdateFieldList:o,isFromGetConversations:a,isInstantMessage:l,isUnreadC2CMessage:u=!1,updateUnreadCount:c}=e,d=[],t=null==o?void 0:o.length;for(let i=0;i<t;i++){let t=new ca(o[i]),{conversationID:s,type:r}=t;if(!ra(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===n.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===n.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[i].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:o[i].lastMessage,isInstantMessage:l}),!0===c&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:u}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:i}=e,e=this.getLocalConversation(e),n=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:o},common:{deepMerge:a}}=(!1===i&&n.push("lastMessage"),r&&n.push("isPinned"),this._core);r(i)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),o(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,n,[null,void 0,"",0,NaN])}_patchLastMessage(e){let i=this._core["OuterConstant"],{conversationID:t,lastMessage:n,isInstantMessage:o}=e,a=this.getLocalConversation(t);if(a&&n){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=n;o&&(e&&(a.lastMessage.payload=e),a.type===i.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],i=[],n=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?n:i).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(i.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:i,CONV_C2C:n}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===n){let e=t.replace(n,"");s.push(e)}else if(e===i){let e=t.replace(i,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:i},appStore:{userStore:n},user:s}=this._core,o=!1;null!=(t=s.userProfile)&&t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(t=>{var s=t["userID"],r=this.getLocalConversation(""+i+s);if(r){let e=(null==(s=n.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,i=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,i=!0)}),i&&this.emitConversationListUpdate()}_handleMessageRead(e){let{CONV_C2C:r}=this._core["OuterConstant"],{C2cNotifyMsgArray:t=[]}=e||{};t.forEach(e=>{let{To_Account:s,UinPairReadArray:t=[]}=(null==e?void 0:e.C2cReadedReceipt)||{};null!=t&&t.forEach(e=>{var e=e["LastReadTime"],t=""+r+s;this._updateConversationReadInfo({conversationID:t,peerReadTime:e}),this._updateMessageListPeerRead({conversationID:t,peerReadTime:e})})})}_updateConversationReadInfo(e){var{appStore:t,utils:{isEmpty:s},common:{getCurrentUserID:r}}=this._core,{conversationID:i,peerReadTime:n}=e,o=t.conversationStore.getConversationMap();if(o.has(i)){let e=o.get(i);e.peerReadTime=n;o=null==e?void 0:e.lastMessage;s(o)||o.fromAccount===r()&&o.lastTime<=n&&!o.isPeerRead&&(o.isPeerRead=!0,t.conversationStore.updateConversation(i,{lastMessage:o}))}}_updateMessageListPeerRead(e){let{notificationCenter:t,OuterEvent:s,message:r}=this._core,{conversationID:i,peerReadTime:n}=e,o=r.messageDataHandler.getLocalMessageList(i),a=r.messageDataHandler.getSparseMessageList(i),l=[];o.forEach(e=>{e.time<=n&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,l.push(e))}),a.forEach(e=>{e.time<=n&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,l.push(e))}),t.emitOuterEvent(s.MESSAGE_READ_BY_PEER,{name:s.MESSAGE_READ_BY_PEER,data:l})}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:r},utils:{isUndefined:i}}=this._core,e=this.getLocalConversation(e);return!(!i(e)&&(i=e.type===t&&(null==(i=e.groupProfile)?void 0:i.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===r,i||t))}updateUnreadCount(e,t=!0){let s,r,i=!1;var n,o=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return o&&(n=o.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${n} newUnreadCount:`+a),n!==a)&&(o.unreadCount=a,(i=!0)===t)&&this.emitConversationListUpdate(),i}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,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.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){let{OuterConstant:t,utils:{isEmpty:s}}=this._core,e=this.getLocalConversationList(),r=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(r+=e.unreadCount)}),r}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(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:i=0,lastReadSequence:n=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let r=e-1;0<=r;r--){let e=o[r],t=i&&e.time>i,s=n&&e.sequence>n;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var 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(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:i,CONVERSATION_UPDATED:n,LOGOUT:o,DESTROY:a,SYNC_CONVERSATION_LIST:l}}=this._core,{GROUP_AT_TIPS:u}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(i,this._handleMessageModified,this),e.unSubscribeInnerEvent(n,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(l,this._handleConversationSynced,this),e.unSubscribeInnerEvent(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},_a=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return de(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(o){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(o))return pa.getLocalConversationList();if(t(o))return 0===o.length?[]:pa.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:r,hasUnreadCount:i,hasGroupAtInfo:n}=o;return pa.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,i)&&this._filterGroupAtInfo(e,n))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},ma=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return de(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return de(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:r},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=ia(t);pa.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},va=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return de(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:t=[]}=e||{};t.forEach(e=>{var{GroupId:e,MemberList:t}=e,t=(null==(t=t[0])?void 0:t.MsgFlag)||"",e=""+this._core.OuterConstant.CONV_GROUP+e;pa.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},fa=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return de(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:i},appStore:{groupStore:n},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=pa.getLocalConversation(u);if(na(u))o.data.conversation=a;else{let t=!1;var l=ta(u)?s:r;if(e(a)&&(t=!0,a=new ca({conversationID:u,type:l})),console.log(this._name+`.getConversationProfile conversationID:${u} isNewConversation:`+t),null==(o.data.conversation=a)||!a.getProfileCompleted()){if(l===s){let e=u.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield ma.get([e]))}if(l===r){let e=u.replace(r,"");if(!n.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==i&&(yield va.get([e]))}}}return o})}_handleC2CConversation(o,a){return de(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:i}}=this._core,n=o["conversationID"],e=yield null==(e=e.userProfile)?void 0:e.getUserProfile({userIDList:[a]});if(0===(null==e?void 0:e.data.length))throw new t.ChatError({code:da.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=i.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),i=pa.hasLocalConversation(n);console.log(this._name+`._handleC2CConversation conversationID:${n} hasLocalConversation: `+i),i?r.updateConversation(n,o):pa.appendToPinnedConversation(o)})}_handleGroupConversation(r,i){return de(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:i}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),pa.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):pa.appendToPinnedConversation(r)})}},Ia=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return pa.getTotalUnreadMessageCount()}},Ea=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:i},InnerEventSubType:{ALL_MESSAGE_READ:n}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(i,n,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),pa.markMessageAsRead({conversationID:e,lastReadTime:t}),pa.updateUnreadCount(e)})}})}handleGroupMessageReadSync(e){let{OuterConstant:s,utils:{isUndefined:t}}=this._core;e.forEach(e=>{e=e.MsgBody.GroupReadInfoArray;t(e)||e.forEach(e=>{var{GroupId:e,LastReadMsgSeq:t}=e,e=""+s.CONV_GROUP+e;console.log(this._name+`.handleGroupMessageReadSync conversationID:${e} lastReadSequence:`+t),pa.markMessageAsRead({conversationID:e,lastReadSequence:t}),pa.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(l){return de(this,void 0,void 0,function*(){var e,t=this._core["OuterConstant"],s=l["conversationID"],r={code:0,data:{}},i=pa.getLocalConversation(s);let n=this._name+`.setMessageRead conversationID:${s} unreadCount:`+((null==i?void 0:i.unreadCount)||0);if(r.successLog={message:n},!i)return r;var o=!(null!=(e=null==(o=this._core)?void 0:o.helper)&&e.isEmpty(i.groupAtInfoList));if(i.type===t.CONV_GROUP&&o&&this._deleteGroupAtTips(s),0===i.unreadCount)return r;var a=this._core["helper"]["ChatError"];try{if(i.type===t.CONV_C2C){let e=this._getLocalMessageMaxTime(i);yield this._setC2CMessageRead(s,e),n+="lastMessageTime:"+e}if(i.type===t.CONV_GROUP){let e=this._getLocalMessageMaxSequence(i);yield this._setGroupMessageRead(s,e),n+="lastMessageSequence:"+e}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new a({functionName:"setMessageRead",code:t,message:s,moreMessage:n})}return i.type===t.CONV_SYSTEM&&(i.unreadCount=0),pa.emitConversationListUpdate(),Object.assign(Object.assign({},r),{successLog:{message:n}})})}setAllMessageRead(){return de(this,arguments,void 0,function*(t={}){let{OuterConstant:{READ_ALL_MSG:e},utils:{safeStringify:i}}=this._core,n="scope:"+t.scope,s=(t.scope||(t.scope=e),t)["scope"],o=this._generateSetAllMessageReadRequestData(s);if(o.allC2CMessageReadStatus===ha&&0===o.groupMessageReadInfoList.length)return{code:0};try{let r=yield function(s){return de(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return ea.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(o);if(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&pa.emitConversationListUpdate(),n+="failureGroupInfoList:"+i(s)}return{code:0,successLog:{message:n}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e,moreMessage:n})}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&pa.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:i},appStore:t}=this._core,n=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of n)if(1<=t.unreadCount){if(o===ga&&t.type===r){let e=this._getLocalMessageMaxTime(t);pa.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===i){let t=s.replace(i,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);pa.markMessageAsRead({conversationID:s,lastReadSequence:e})}}pa.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:i,CONV_GROUP:n,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:ha,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===i&&a.allC2CMessageReadStatus===ha){if(a.allC2CMessageReadStatus=ga,r===o)break}else if(e===n){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:i}=this._core["utils"],n=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;i(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&n.push(e+`-${t}-`+s))}),n}_deleteGroupAtTips(o){return de(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=pa.getLocalConversation(o);if(e){var n=(null==e?void 0:e.groupAtInfoList)||[];if(0!==n.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,i=[...n];e({groupID:o.replace(s,"")})&&0===(i=n.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return de(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:i.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+n.length),this._clearGroupAtInfoList(o))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=pa.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&pa.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.time));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastTime)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${s} to `+t),s=t),s}_getLocalMessageMaxSequence(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.sequence));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastSequence)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${s} to `+t),s=t),s}_setC2CMessageRead(e,t){return de(this,void 0,void 0,function*(){try{yield function(e,t){return de(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),pa.markMessageAsRead({conversationID:e,lastReadTime:t}),pa.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return de(this,void 0,void 0,function*(){try{yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:{GroupId:e,MsgReadedSeq:t}})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(this._name+"._setGroupMessageRead ok, lastReadSequence:"+t),pa.markMessageAsRead({conversationID:e,lastReadSequence:t}),pa.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:i,READ_ALL_GROUP_MSG:n}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![r,i].includes(o))&&(e!==s||![r,n].includes(o)))}},Sa=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,o){var{isArray:t}=this._core["utils"];if(t(e)){let i=this._core["OuterConstant"],n=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=pa.getLocalConversation(""+i.CONV_C2C+t):2===e&&(r=pa.getLocalConversation(""+i.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+o),o&&!r.isPinned&&(r.isPinned=!0,n=!0),!o)&&r.isPinned&&(r.isPinned=!1,n=!0)}),n&&pa.emitConversationListUpdate(!0)}}pinConversation(e){return de(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,helper:{ChatError:i}}=this._core,{conversationID:n,isPinned:o}=e,a={code:0,data:{conversationID:n}},l=pa.getLocalConversation(n);if(l&&l.isPinned===o)return a;if(na(n))return l&&(l.isPinned=o),pa.emitConversationListUpdate(!0),a;var u=`conversationID:${n} isPinned:`+o;try{let e=null,t=(ta(n)?e={Type:1,To_Account:n.replace(s.CONV_C2C,"")}:sa(n)&&(e={Type:2,GroupId:n.replace(s.CONV_GROUP,"")}),yield function(r,i){return de(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(t){if(l)l.isPinned!==o&&(l.isPinned=o);else{let e=new ca({conversationID:n,type:ta(n)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});pa.setLocalConversation(n,e)}pa.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},a),{successLog:{message:u}})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"pinConversation",code:t,message:s,moreMessage:u})}})}},Ca=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],i=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&i.push(""+r.CONV_C2C+t),2===e&&i.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+i),this._deleteLocalConversationList(i)}}deleteConversation(t){return de(this,void 0,void 0,function*(){var e=this._core["utils"]["isString"];e(t)?yield this._deleteConversation({conversationIDList:[t],flag:la.ONLY_CONVERSATIONID}):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return de(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:i=0}=e,{ChatError:n}=this._core["helper"],o=`conversationIDList:${s} clearHistoryMessage:`+r;try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:da.CONV_NOT_FOUND});return{code:0,data:i===la.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t},successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n({code:t,message:s,moreMessage:o})}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!pa.hasLocalConversation(e)&&((t=null==(t=pa.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,n){return de(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,i={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(t.forEach(e=>{var t,s;pa.hasLocalConversation(e)&&(t=(null==(t=pa.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?i.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&i.conversationList.push({ToGroupid:s,Type:2}))}),0!==i.conversationList.length){var s=yield function(r,i){return de(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(i,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.Type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{pa.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&pa.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=pa.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(pa.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&pa.emitConversationListUpdate()}_hasLocalGroup(e){var{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,e=e.replace(t,"");return!!s.getGroup(e)}_deleteConversationLocalMessage(e){console.log(this._name+"._deleteConversationLocalMessage conversationID:"+e),this._core.message.messageDataHandler.deleteConversationMessageList(e)}},Ma=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return de(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),pa.hasLocalConversation(e))return null!=(e=pa.getLocalConversation(e))&&e.setDraftText(t),pa.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:da.CONV_NOT_FOUND})})}},ya=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return de(this,void 0,void 0,function*(){30<a.length&&(console.warn(`${this._name}.set userIDList length:${a.length} exceeds limit 30`),a.splice(30));let e=function(){var{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=ea.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[l],t=yield function(s,r){return de(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:{Peer_Account:e,Mute_Notifications:t}})})}({userIDList:a,receiveMessageOption:e},this._core),{ErrorList:s=[]}=t||{},r=[],i=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),n=[],o=this._core["OuterConstant"];return a.forEach(e=>{n.push(""+o.CONV_C2C+e),i.push({userID:e})}),pa.patchMessageRemindType(n,l),{code:0,data:{successUserIDList:i,failureUserIDList:r}}})}},Oa=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,i){return de(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:i},this._core),!t(r)){let e=""+s.CONV_GROUP+r;pa.patchMessageRemindType([e],i)}return{code:0,data:{groupID:r,messageRemindType:i}}})}},Aa=new class{constructor(){this._name="SetMessageRemindType"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){let{helper:{isEmpty:t},OuterConstant:n,ssoLog:o}=this._core;e.forEach(e=>{var i=e["MuteNotificationsSync"];if(!t(i)){let{To_Account:e,MuteNotifications:t}=i,s=e.map(e=>""+n.CONV_C2C+e),r=ia(t);o.debug(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),pa.patchMessageRemindType(s,r)}})}setMessageRemindType(a){return de(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=a,{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;try{if(!n(e))return o.debug(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield Oa.set(e,r);if(n(t))throw new i.ChatError({functionName:s,message:"userIDList or groupID is required"});return o.debug(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield ya.set(t,r)}catch(e){let t=new i.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},Ta=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,_a.init(e),fa.init(e),Ia.init(e),Ea.init(e),Sa.init(e),Ca.init(e),Ma.init(e),Aa.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];Ca.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];Sa.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];Sa.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;Ea.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;Aa.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;Ea.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Ra=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return de(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=o,{startTime:r=0,endTime:i=0}=this._calcStartAndEndTime(o),n=yield function(n){return de(this,void 0,void 0,function*(){var e=ea.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:i}=n;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:i}})})}({messageRemindType:this._getType(t),startTime:r,endTime:i,isRepeated:s?ua.ON:ua.OFF});return{code:0,data:{errorCode:n.ErrorCode,errorInfo:n.ErrorInfo}}}catch(e){aa("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:i=!0}=e,n=new Date,n=new Date(n.getFullYear(),n.getMonth(),n.getDate(),e,t,s),e=Math.round(n.getTime()/1e3);let o=i&&86400<=r?e+86400:e+r;return{startTime:e,endTime:o}}_getType(e){var t=this._core["OuterConstant"];return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}},Da=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:s}=this._core=e;e.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),t.subscribeInnerEvent(s.MESSAGE_PUSH,t.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){var e=this._handleResult(e),{notificationCenter:t,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:e})}getAllReceiveMessageOpt(){return de(this,void 0,void 0,function*(){try{var e=yield function(){return de(this,void 0,void 0,function*(){var e=ea.core["common"],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){aa("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:i,EndTime:n,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:i,endTime:n,isRepeated:o===ua.ON}}},ba=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,ya.init(e),Oa.init(e),ma.init(e),va.init(e),Ra.init(e),Da.init(e)}};let Na=e=>!ta(e)&&!sa(e)&&!na(e),La={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Na(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Na(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Na(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{var{utils:{isArray:t,isObject:s,isString:r}}=ea["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&Na(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(Na(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=>!(!ta(e)&&!sa(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}}},Pa={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){ea.init(e),Ta.init(e),ba.init(e),pa.init(e),e.helper.registerValidateConfig({auth:Pa,params:La})}};let Ga=new class{init(e){this.core=e}},Ua="AVChatRoom",ka="AV_HISTORY_MSG",Fa="GRP_COUNTER",$a="Set",qa="Increase",xa="Decrease",Va=0,Ba=1,ja=2,Ka=["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"],Wa=["Role","JoinTime","MsgFlag","MsgSeq"],Ya=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],za=0,Ja=1,Qa="notStart",Xa="resolved",Za="rejected",ec=10018,tc=11e3,sc=2,nc=["Owner","Admin","Member"],oc=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ic=0,rc=1,ac=2,cc=4,uc=1,lc=2,dc=3,hc=4,gc=5,pc=1,_c=0,mc=4,vc=6,fc=400,Ic=300,Ec={from:!0,groupID:!0,groupName:!0,to:!0},Sc={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Cc=2,Mc=4,yc=5,Oc=7,Ac=8,Tc=15,Rc=20,Dc=21,bc=2600,Nc=2602,Lc=2603,Pc=2620,wc=2621,Gc=2623,Uc=2660,kc=2661,Fc=2681,$c=2683,qc=2684,xc=2685,Vc=2687,Bc=3122,jc=10018,Kc=e=>e===Ga.core.OuterConstant.GRP_PUBLIC,Hc=e=>e===Ga.core.OuterConstant.GRP_AVCHATROOM,Wc=(r,e)=>{var t=Ga.core.utils["isArray"];if(!t(r)||!t(e))return!1;let i=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,i=!0):(r.push({key:t,value:e}),i=!0)}),i},Yc=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:i,Value:n}=s[e];r.push({key:i,value:n})}return r},zc=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:i,value:n}=s[e];r.push({Key:i,Value:n})}return r};function Jc(e,t){var s=Ga.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:Bc,replacement1:e})}function Qc(e,t){var s=Ga.core["helper"],s=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:",s),s}let 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){var t,{isString:s}=Ga.core["utils"];for(t in e)Xc.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:i},common:{deepMerge:n}}=Ga.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),i(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&Wc(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),n(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&n(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n}=e,o=Ga.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var eu=new class{constructor(){this._name="GroupDataHandler"}init(e){var e=(this._core=e)["appStore"]["groupStore"];this._groupMap=e.getGroupMap()}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){var{getCurrentUserID:t}=this._core["common"];let s;e.forEach(e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null!=(t=this.getLocalGroup(s))&&t.updateGroup(e):this._groupMap.set(s,new Zc(e))});var r=t();for(let[,e]of this._groupMap)e.selfInfo.userID=r,"Owner"===e.selfInfo.role&&(e.ownerID=r)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){let{GRP_ROOM:t,GRP_LIVE:s}=this._core["OuterConstant"];return[...this._groupMap.values()].filter(e=>{e=e.type;return e!==t&&e!==s})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){var e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(t){let{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:e}}=this._core,r=""+e+t;if(s.getConversation(r)){let e=this.getLocalGroup(t);s.updateConversation(r,{groupProfile:e})}}reset(){this.clearLocalGroup()}};function tu(o,a){return de(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:i,responseFilter:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:i,ResponseFilter:n,SupportTopic:r,NeedAppDefineData:1}})})}let su=function(e,t){return{code:0,data:e||{},successLog:t}};var nu=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Qa,this.PAGING_GRP_COUNT_LIMIT=200}init(e){var{helper:e,constants:{WORKFLOW_NAME:t,WORKFLOW_STEP:s}}=this._core=e;e.registerApi({apiName:"getGroupList",context:this}),e.registerWorkflowStep(t.SYNC_SERVER_INFO_AFTER_LOGIN,s.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return de(this,arguments,void 0,function*(e=!1){if(e){let e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),eu.updateLocalGroup(e),eu.getLocalGroupList()}return this._core.ssoLog.debug("getGroupList",this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===Za||this._pagingStatus===Qa?this._syncGroupList().then(()=>{var e=eu.getLocalGroupList();return su({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e}):(e=eu.getLocalGroupList(),su({groupList:e,isSyncCompleted:this._isSyncCompleted()},{message:"return group count:"+e.length}))})}_syncGroupList(){return de(this,void 0,void 0,function*(){this._pagingStatus===Qa&&eu.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Xa,this._groupListTreeShaking(t),eu.updateLocalGroup(t);var s=eu.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",this._name+"._syncGroupList ok, count:"+s.length),eu.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Za,e}})}_pagingGetGroupList(e){return de(this,void 0,void 0,function*(){var i=this._core["ssoLog"],{isCommunityRelay:n=!1,groupList:o}=e;let a,{limit:l,offset:u}=e;var c=[...Ka];n&&(a=this._core.OuterConstant.GRP_COMMUNITY,c.push("AtInfoList"));try{let e=yield tu({type:a,limit:l,offset:u,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:c,SelfInfoFilter:[...Wa]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);var d=u+l,h=!(d<s),g=`offset:${u} limit:${l} total:${s} isCompleted:${h} current:${o.length} isCommunityRelay:`+n;return i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. "+g),n?h?o:(u=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:l,offset:u,groupList:o})):h?(i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList start to get community list"),u=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:l,offset:u,groupList:o})):(u=d,this._pagingGetGroupList({limit:l,offset:u,groupList:o}))}catch(e){if(e.ErrorCode===ec)return i.warn("_pagingGetGroupList",this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+l),this._pagingGetGroupList({isCommunityRelay:n,limit:50,offset:u,groupList:o});if(n)return e.code===tc&&i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. community unavailable"),o;throw e}})}_pagingGetJoinedCommunityList(e){return de(this,void 0,void 0,function*(){var{common:{getCurrentUserID:i},OuterConstant:n,ssoLog:o}=this._core,a=e["groupList"];let{limit:l,offset:u}=e;try{let e=yield tu({limit:l,offset:u,type:n.GRP_COMMUNITY,memberAccount:i(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...Ka],SelfInfoFilter:[...Wa]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);a.push(...r);var c=u+l,d=!(c<s),h=`offset:${u} limit:${l} total:${s} isCompleted:${d} current:`+a.length;return o.debug("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList ok. "+h),d?a:(u=c,this._pagingGetJoinedCommunityList({limit:l,offset:u,groupList:a}))}catch(e){if(e.code===jc)return o.warn("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+l),this._pagingGetJoinedCommunityList({limit:50,offset:u,groupList:a});throw e}})}_groupListTreeShaking(s){var r=new Map([...eu.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var i=[...r.keys()];for(let e=0,t=i.length;e<t;e++)eu.deleteLocalGroup(i[e])}_isSyncCompleted(){return this._pagingStatus===Xa}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:l,Introduction:u,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:h,MemberNum:g,MaxMemberNum:p,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:S,LastRecallTime:E,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],i=Yc(i),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:l,introduction:u,inviteOption:c,lastInfoTime:d,lastMsgTime:h,memberCount:g,maxMemberCount:p,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:S,selfInfo:C,_lastRevokedTime:E,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:i}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:i}}_convertAtInfoList(r,e){if(0===e.length)return[];let i=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;i.push({groupID:r,groupAtType:e,sequence:t,from:s})}),i}},ou=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(l){return de(this,void 0,void 0,function*(){var o;this._preCheckParams(l);let e=this._core["helper"]["ChatError"];try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(g,p){return de(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:i,avatar:n,maxMemberNum:o,joinOption:a,inviteOption:l,memberList:u,groupCustomField:c,isSupportTopic:d}=g;let h;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:i,FaceUrl:n,MaxMemberCount:o,ApplyJoinOption:a,InviteJoinOption:l,MemberList:h=u?u.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?zc(t):void 0}}):h,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return p.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},l),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:i=[]}=s||{},n=`${this._name}.createGroup ok, type:${l.type} groupID:${r} overLimitUserIDList:`+i;e(l.memberList)||e(i)||(l.memberList=null==(o=l.memberList)?void 0:o.filter(e=>i.includes(e.userID))),eu.updateLocalGroup([Object.assign(Object.assign({},l),{groupID:r})]);var a=eu.getLocalGroup(r);return this._notNeedSendCustomMessage(l)||(this._sendCustomMessage(r,l.type),eu.emitGroupListUpdate()),su({group:a},{message:n})}catch(o){var{errorCode:a,errorInfo:t}=o;throw new e({functionName:"createGroup",code:a,message:t,moreMessage:" groupID:"+l.groupID})}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:i},common:{isCommunity:n}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:i}=Ga.core.OuterConstant;return[e,t,s,r,i]})().includes(t))throw new this._core.helper.ChatError({code:bc});if(!n({type:t})){if(r&&n({groupID:s}))throw new this._core.helper.ChatError({code:Nc});i(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||i(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||i(e.joinOption)||(e.joinOption=void 0),n({type:t})){if(r&&!n({groupID:s}))throw new this._core.helper.ChatError({code:Nc});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Hc(e)}_canIUseJoinOption(e){return Kc(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",i=za;t===s.GRP_COMMUNITY&&(r="Create Community",i=Ja);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:i,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},iu=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){var{helper:e,constants:t}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){var e=e["elements"]["newGroupProfile"],{isEmpty:t,isUndefined:s}=this._core["utils"];return!s(e)&&!t(e.groupAttributeOption)}handleGroupAttributesUpdated(e){var{groupID:e,groupAttributeOption:t}=e,{serverMainSequence:t,groupAttributeList:s=[],operation:r}=t,i=(this._core.ssoLog.debug("handleGroupAttributesUpdated",this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];i(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",this._name+`.initGroupAttributesCache. groupID:${e} avChatRoomKey:`+t)}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){var{groupID:s,serverMainSequence:r,groupAttributeList:i,operation:n}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];n!==gc&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:i,operation:n})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),this._core.ssoLog.debug("refreshGroupAttributesCache",this._name+`.refreshGroupAttributesCache. operation:${n} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;s!==dc?s!==hc?(s===uc&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:i=[]}=e,n={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===i.length)for(let e of t.keys())n[e]=(null==(s=t.get(e))?void 0:s.value)||"";else i.forEach(e=>{t.has(e)&&(n[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:i}=this._computeValuesChangedData(s);this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+i.length),0===r.length&&0===i.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:i}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],i=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&i.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:i}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},ru=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ua)})}dismissGroup(i){return de(this,void 0,void 0,function*(){let{ChatError:t}=this._core["helper"];try{yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(i,this._core);let e=eu.getLocalGroup(i)["type"];return eu.deleteLocalGroup(i),eu.emitGroupListUpdate(),iu.deleteGroupAttributesCache(i),su({groupID:i,type:e},{message:i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"dismissGroup",code:s,message:r})}})}},au=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return de(this,void 0,void 0,function*(){let{groupID:i,groupCustomFieldFilter:e}=t,n={groupIDList:[i],responseFilter:{GroupBaseInfoFilter:[...Ka],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...Ya]}},{ChatError:r}=this._core["helper"];try{let e=yield this.getGroupProfileAdvance(n),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!eu.hasLocalGroup(i)&&Hc(t[0].type)?new Zc(t[0]):(eu.updateLocalGroup(t),eu.getLocalGroup(i))).isSupportTopic||eu.updateConversationGroupProfile(i),su({group:r},{message:"groupID:"+i})}catch(e){let{code:t,message:s}=e;throw new r({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(a){return de(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),r=e.filter(e=>t({groupID:e})),i=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),n=[],o=[];return i.forEach(e=>{n.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:n,failureGroupList:o}})}_getGroupProfileAdvance(e){return de(this,void 0,void 0,function*(){let{ssoLog:n,utils:{isUndefined:o}}=this._core,{isCommunityProfile:t=!1}=e,a=le(e,["isCommunityProfile"]);if(0===a.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(a,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),r=s.filter(e=>o(e.errorCode)||0===e.errorCode),i=s.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return n.debug("_getGroupProfileAdvance",this._name+"._getGroupProfileAdvance ok, groupID:"+a.groupIDList.join(",")),{successGroupList:r,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:l,InfoSeq:u,Introduction:c,InviteJoinOption:d,LastInfoTime:h,LastMsgTime:g,MaxMemberNum:p,MemberNum:_,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:I,Owner_Account:S,ShutUpAllMember:E,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:A,ErrorInfo:O}=s[e],i=Yc(i),y=this._convertMembers(y);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:l,infoSequence:u,introduction:c,inviteOption:d,lastInfoTime:h,lastMsgTime:g,maxMemberCount:p,memberCount:_,muteAllMembers:m,name:v,nextMessageSeq:f,notification:I,ownerID:S,shutUpAllMember:E,muteUntil:C,type:M,members:y,errorCode:A,errorInfo:O})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,MsgFlag:a,MsgSeq:l,NameCard:u,Role:c}=s[e],i=Yc(i);r.push({memberCustomField:i,joinTime:n,userID:o,messageRemindType:a,sequence:l,nameCard:u,role:c})}return r}},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){var{groupID:r,counterList:i=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<n&&n<t||(i.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:i,counters:t,avChatRoomKey:e})}}setGroupCounters(t,i){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(i).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},uu=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ua)})}joinGroup(s){return de(this,void 0,void 0,function*(){let r=s["groupID"],{helper:{ChatError:i},OuterConstant:e,ssoLog:t}=this._core;try{if(eu.hasLocalGroup(r))try{return yield au.getGroupProfile({groupID:r}),su({status:e.JOIN_STATUS_ALREADY_IN_GROUP,group:eu.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:`+e.JOIN_STATUS_ALREADY_IN_GROUP})}catch(i){t.warn("joinGroup",this._name+`.joinGroup ${r} was unjoined, start to join!`),eu.deleteLocalGroup(r)}return yield this._applyJoinGroup(s)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"joinGroup",code:t,message:s,moreMessage:"groupID:"+r})}})}_applyJoinGroup(h){return de(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t,ssoLog:s}=this._core,r=h["groupID"],i=Object.assign({},h),t=t.checkBusinessCapabilityBits(ka),i=(t&&(i.historyMessageFlag=1),yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(i,this._core)),{Type:i,JoinedStatus:n,LongPollingKey:o,StartSeq:a,HugeGroupFlag:l,AVChatRoomKey:u,RspMsgList:c=[]}=i||{},t=`groupID:${r} joinedStatus:${n} longPollingKey:${o} startSeq:${a} avChatRoomFlag:${l} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+c.length;s.debug("_applyJoinGroup",this._name+"._applyJoinGroup ok, "+t);let d=new Zc({groupID:r,type:i});if(n===e.JOIN_STATUS_WAIT_APPROVAL)return su({status:e.JOIN_STATUS_WAIT_APPROVAL,group:d});if(n!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:Uc});try{d=(yield au.getGroupProfile({groupID:r})).data.group}catch(e){s.warn("_applyJoinGroup",this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${r}, errorCode:`+(null==e?void 0:e.code))}return this._handleJoinResult({group:d,avChatRoomFlag:l,longPollingKey:o,startSequence:a,avChatRoomKey:u,historyMessageList:c})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(iu.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),cu.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),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){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ua)})}quitGroup(i){return de(this,void 0,void 0,function*(){if(!eu.hasLocalGroup(i))throw new this._core.helper.ChatError({code:Gc});let{ChatError:t}=this._core["helper"];try{yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(i,this._core);let e=eu.getLocalGroup(i)["type"];return eu.deleteLocalGroup(i),eu.emitGroupListUpdate(),iu.deleteGroupAttributesCache(i),su({groupID:i,type:e},{message:"groupID:"+i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"quitGroup",code:s,message:r,moreMessage:"groupID:"+i})}})}},du=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return de(this,void 0,void 0,function*(){try{var t=yield function(t,s){return de(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...Ha]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:e=[],ApplyJoinOption:r,CreateTime:i,FaceUrl:n,Introduction:o,InviteJoinOption:a,MaxMemberNum:l,MemberNum:u,Name:c,Owner_Account:d,Type:h,ErrorCode:g,ErrorInfo:p}=s[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:p});var _=Yc(e),m=new Zc({groupID:v,name:c,avatar:n,introduction:o,joinOption:r,inviteOption:a,maxMemberCount:l,memberCount:u,type:h,ownerID:d,createTime:i,groupCustomField:_});return su({group:m})}catch(e){var{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){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(o){return de(this,void 0,void 0,function*(){let r=o["groupID"],{utils:{isUndefined:t},ssoLog:s,helper:i}=this._core,n=eu.getLocalGroup(r);if(n){let e=n["type"];this._canIUseJoinOption(e)||t(o.joinOption)||(s.warn("updateGroupProfile",this._name+`.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),o.joinOption=void 0)}t(o.muteAllMembers)||(o.muteAllMembers=!0===o.muteAllMembers?"On":"Off");try{return yield function(u,c){return de(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:i,muteAllMembers:n,joinOption:o,inviteOption:a,groupCustomField:l}=u,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:i,ShutUpAllMember:n,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:l?zc(l):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(o,this._core),n?(n.updateGroup(o),eu.emitGroupListUpdate()):n=new Zc(o),su({group:n},{message:"groupID:"+r})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i.ChatError({code:t,message:s,moreMessage:"groupID:"+r})}})}_canIUseJoinOption(e){return Kc(e)||this._core.common.isCommunity({type:e})}},gu=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(o){return de(this,void 0,void 0,function*(){var t="changeGroupOwner",{groupID:e,newOwnerID:s}=o,e=eu.getLocalGroup(e),{helper:r,OuterConstant:i,common:{getCurrentUserID:n}}=this._core;if((null==e?void 0:e.type)===i.GRP_AVCHATROOM)throw new r.ChatError({functionName:t,code:Pc});if(s===n())throw new r.ChatError({functionName:t,code:wc});try{return yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(o,this._core),e.ownerID=s,eu.emitGroupListUpdate(),su({group:e})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},pu=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ua)})}getGroupOnlineMemberCount(n){return de(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount";if(!eu.hasLocalGroup(n))return su({memberCount:0});let r=Date.now();if(this._onlineMemberCountMap.has(n)){let e=this._onlineMemberCountMap.get(n),{lastReqTime:t=0,memberCount:s=0}=e||{};if(r-t<=6e4)return su({memberCount:s})}try{let e=yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0}=e||{};this._onlineMemberCountMap.set(n,{lastReqTime:Date.now(),memberCount:t});var i=`${this._name}.${s} ok. groupID:${n} memberCount:`+t;return su({memberCount:t},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:s,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),gu.init(e),pu.init(e,t)}dismissGroup(e){return ru.dismissGroup(e)}joinGroup(e){return uu.joinGroup(e)}quitGroup(e){return lu.quitGroup(e)}getGroupOnlineMemberCount(e){return pu.getGroupOnlineMemberCount(e)}},mu=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return de(this,void 0,void 0,function*(){var t="getGroupApplicationList";try{var e=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]),s=(this._core.ssoLog.debug("getGroupApplicationList",this._name+`.${t} ok.`),this._handleGroupApplicationResult([...e[0],...e[1]]));return su({applicationList:s})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_getGroupApplicationList(n){return de(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=n||{},r=this._core["common"];let i;try{i=yield function(i,n){return de(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}var{NextStartTime:e=0,PendencyList:t=[]}=i||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},n),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=le(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:i,From_Account:n,GroupId:o,GroupName:a,PendencyType:l,To_Account:u}=e;return{handled:e,messageKey:t,applicant:n,applicantNick:i,groupID:o,groupName:a,authentication:r,applicationType:l,userID:u,note:s}}},vu=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return de(this,void 0,void 0,function*(){var t=e["application"],s=this._handleParams(e);try{(null==t?void 0:t.applicationType)===sc?yield function(o,a){return de(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,invitee:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,Invited_Account:n}})})}(s,this._core):yield function(o,a){return de(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,messageKey:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,MsgKey:n}})})}(s,this._core);let 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{handleAction:e,handleMessage:t,message:s,application:r}=e;let i,n,o,a,l;if(s){let e=(s||{})["payload"];i=e.operatorID,n=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else i=(null==r?void 0:r.applicant)||"",n=(null==r?void 0:r.groupID)||"",o=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return(null==r?void 0:r.applicationType)===sc&&(l=r.userID),{handleAction:e,handleMessage:t,applicant:i,invitee:l,groupID:n,authentication:o,messageKey:a}}},fu=new class{init(e){e.ssoLog.debug("GroupApplication.init"),mu.init(e),vu.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){var{utils:{isUndefined:t},common:{deepMerge:s}}=Ga["core"],t=(t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus),[null,void 0,"",0,NaN]);e.memberCustomField&&Wc(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function Eu(a,l){return de(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:i,memberCustomField:n}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:i,AppMemberDefinedData:o=n?zc(n):o};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var Su=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ua)})}getGroupMemberList(r){return de(this,void 0,void 0,function*(){let u="getGroupMemberList",{groupID:c,offset:d=0,count:e=100,role:t="",filter:s=""}=r,h=eu.getLocalGroup(c),g=100<e?100:e,p={groupID:c,offset:d,limit:g,memberRoleFilter:nc.includes(t)?[t]:void 0,memberInfoFilter:oc};try{let e=yield function(o,a){return de(this,void 0,void 0,function*(){var e=a.common["isCommunity"],{groupID:t,offset:s,limit:r,memberRoleFilter:i,memberInfoFilter:n}=o,r={GroupId:t,Limit:r,MemberRoleFilter:i,MemberInfoFilter:n};return e({groupID:t})?r.Next=String(s):r.Offset=s,a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:r})})}(p,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{},i=`${this._name}.${u} ok, totalMemberCount:${s} next:`+r,{utils:{isArray:n,isEmpty:o},common:{isCommunity:a}}=this._core;if(h&&(h.memberCount=s),!n(t)||0===t.length)return su({memberList:[],offset:0},{message:i});let l=d+g;a({groupID:c})&&(l=o(r)?0:r),t.length<g&&(l=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),m=this._generateGroupMember(_);return su({memberList:m,offset:l},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:u,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u,NameCard:c}=s[e],i=Yc(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:l,muteUntil:u,memberCustomField:i,nameCard:c})}return r}_patchAvatarAndNick(n){return de(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Iu(s[e]);r.push(i)}return r}},Cu=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(c){return de(this,void 0,void 0,function*(){let t="getGroupMemberProfile",{groupID:r,userIDList:i,memberCustomFieldFilter:n}=c,e=eu.getLocalGroup(r),{helper:s,utils:{isArray:o},ssoLog:a}=this._core;if(e&&Hc(e.type))throw new s.ChatError({functionName:t,replacement1:t,code:Vc});50<i.length&&(a.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${i.length} exceeds limit 50`),i.splice(50));var l=`userIDList length:${i.length} groupID:`+r;try{let e=yield function(i,n){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:i,memberCustomFieldFilter:n,memberInfoFilter:[...oc]},this._core),t=(e||{})["MemberList"];if(!o(t)||0===t.length)return su({memberList:[]});var u=this._convertMemberInfo(t),u=yield this._getMemberAvatarAndNick(u);let s=this._generateGroupMember(u);return su({memberList:s},{message:l})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:l})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u,NameCard:c}=s[e],i=Yc(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:l,muteUntil:u,memberCustomField:i,nameCard:c})}return r}_getMemberAvatarAndNick(n){return de(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Iu(s[e]);r.push(i)}return r}},Mu=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(r){return de(this,void 0,void 0,function*(){let t="addGroupMember",{groupID:o,userIDList:e}=r,a=eu.getLocalGroup(o),s=this._core["helper"];if(a&&Hc(a.type))throw new s.ChatError({functionName:t,code:kc});var l=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:o,userIDList:l},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}=this._handleResult(t);return su({failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n,group:a},{message:` groupID:${o} successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${i} overLimitUserIDList:`+n})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){let s=[],r=[],i=[],n=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;e===ic?s.push(t):e===rc?r.push(t):e===ac?i.push(t):e===cc&&n.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}}},yu=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ua)})}deleteGroupMember(a){return de(this,void 0,void 0,function*(){var t="deleteGroupMember",{groupID:e,userIDList:s}=a,r=eu.getLocalGroup(e),{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;if(n(r))throw new i.ChatError({functionName:t,code:Lc});20<s.length&&(o.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${s.length} exceeds limit 20`),s.splice(20));try{return yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:s},this._core),su({group:r,userIDList:s},{message:`groupID:${e} userIDList length:`+s.length})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ou=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return de(this,void 0,void 0,function*(){let t=this._core["helper"],{groupID:s,userID:r,muteTime:i}=o,n=` groupID:${s} userID:${r} muteTime:`+i;this._preCheckSettingMuteParams(o);try{yield Eu(o,this._core);let e=eu.getLocalGroup(s),t=new Iu({userID:r,muteTime:i});return su({group:e,member:t},{message:n})}catch(e){throw new t.ChatError({functionName:"setGroupMemberMuteTime",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:n})}})}_preCheckSettingMuteParams(e){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:xc})}},Au=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(a){return de(this,void 0,void 0,function*(){let t="setGroupMemberRole",s=this._core["helper"],{groupID:r,userID:i,role:n}=a,o=`${this._name}.${t} ok, groupID:${r} userID:${i} role:`+n;this._preCheckSettingRoleParams(a);try{yield Eu(a,this._core);let e=eu.getLocalGroup(r),t=new Iu({userID:i,role:n});return su({group:e,member:t},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:i,OuterConstant:n,common:{isCommunity:o}}=this._core,a=eu.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==n.GRP_MBR_ROLE_OWNER)throw new i.ChatError({functionName:"setGroupMemberRole",code:Fc});if(t===r.get("login").userId)throw new i.ChatError({functionName:"setGroupMemberRole",code:qc});a=[...nc];if(o({groupID:e})&&a.push(n.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new i.ChatError({functionName:"setGroupMemberRole",code:$c})}},Tu=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(u){return de(this,void 0,void 0,function*(){let i="setGroupMemberNameCard",{helper:t,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(u);try{let{groupID:e,userID:t=n(),nameCard:s}=u,r={groupID:e,userID:t,nameCard:s};yield Eu(r,this._core);var o=`${this._name}.${i} ok, groupID:${e} userID:${t} nameCard:`+s,a=eu.getLocalGroup(e),l=new Iu({userID:t,nameCard:s});return su({group:a,member:l},{message:o})}catch(e){throw new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:logText})}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=eu.getLocalGroup(e);if(Hc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:Vc})}},Ru=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(a){return de(this,void 0,void 0,function*(){let t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:e}}=this._core;this._preCheckSettingCustomFiledParams(a);var{groupID:r,userID:i=e(),memberCustomField:n}=a,o=`${this._name}.${t} ok, groupID:${r}userID:${i} memberCustomField:`+JSON.stringify(n);try{let e={groupID:r,userID:i,memberCustomField:n},t=(yield Eu(e,this._core),eu.getLocalGroup(r)),s=new Iu({userID:i,memberCustomField:n});return su({group:t,member:s},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=eu.getLocalGroup(e);if(Hc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:Vc})}},Du=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),Su.init(e,t),Cu.init(e),Mu.init(e),yu.init(e,t),Ou.init(e),Au.init(e),Tu.init(e),Ru.init(e)}getGroupMemberList(e){return Su.getGroupMemberList(e)}deleteGroupMember(e){return yu.deleteGroupMember(e)}},bu=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return de(this,void 0,void 0,function*(){var t="getGroupCounters";try{Jc(t,Fa);var e,s,r,{groupID:i,keyList:n=[]}=l,{avChatRoomKey:o,lastUpdateTime:a}=cu.getLocalGroupCounters(i);return Date.now()-a>=this._getExpireTime()&&(e=yield function(i){return de(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=i,r=Ga.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:i,keyList:n,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:r}=e,cu.updateLocalGroupCounters({groupID:i,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:cu.getLocalCounters(i,n)}}}catch(e){Qc(t,e)}})}_getExpireTime(){var{store:e,utils:{isUndefined:t}}=this._core,e=(e.get("cloudConfig")||{})["grp_counter_expire_time"];return t(e)?3e4:Number(e)}},Nu=new class{init(e){e=e.helper;e.registerApi({apiName:"setGroupCounters",context:this}),e.registerApi({apiName:"increaseGroupCounter",context:this}),e.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation($a,e)})}increaseGroupCounter(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(qa,e)})}decreaseGroupCounter(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(xa,e)})}_handleCounterOperation(a,l){return de(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{Jc(t,Fa);var{groupID:e,key:s,value:r=0}=l,i=cu.getLocalGroupCounters(e)["avChatRoomKey"],n=a===$a?this._convertObjectToList(l.counters):[{Key:s,Value:r}],o=yield this._updateGroupCounters({groupID:e,counterList:n,avChatRoomKey:i,mode:a});return cu.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){Qc(t,e)}})}_updateGroupCounters(n){return de(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=n,i=Ga.core["common"];return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},Lu=new class{init(e){this._core=e,bu.init(e),Nu.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;e!==Va&&e!==ja||this._processAndNotifyCounterUpdate(r,t,s),e===Ba&&cu.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:i}=this._core;cu.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{i.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){cu.reset()}},Pu=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return de(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a}=iu.getGroupAttributesCache(i),l=iu.convertKeyValueMapToList(n);try{let e=yield function(i,n){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return iu.saveGroupAttributesCacheValuesCopy(i),iu.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:uc}),iu.emitGroupAttributesUpdated(i),su({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},wu=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return de(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a,values:r}=iu.getGroupAttributesCache(i),l=iu.convertKeyValueMapToList(n).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=r.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(i,n){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return iu.saveGroupAttributesCacheValuesCopy(i),iu.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:lc}),iu.emitGroupAttributesUpdated(i),su({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Gu=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(l){return de(this,void 0,void 0,function*(){var t="deleteGroupAttributes",{groupID:e,keyList:s=[]}=l;try{var{resultList:r,serverMainSequence:i,operation:n,groupAttributeList:o}=(0===s.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,s))||{},a=this._name+`.${t} ok. groupID:${e} operation: `+n;return iu.saveGroupAttributesCacheValuesCopy(e),iu.refreshGroupAttributesCache({groupID:e,serverMainSequence:i,groupAttributeList:o,operation:n}),iu.emitGroupAttributesUpdated(e),su({keyList:r},{message:a})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_deleteGroupAttributes(o,a){return de(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=iu.getGroupAttributesCache(o),r=[],i=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},i.push({key:e,seq:t}),r.push(e))});var n=((yield function(i,n){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:i,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:n,groupAttributeList:i,operation:hc}})}_clearGroupAttributes(r){return de(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=iu.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:dc}})}},Uu=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(l){return de(this,void 0,void 0,function*(){let r=l["groupID"],{avChatRoomKey:i,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=iu.getGroupAttributesCache(r),{ChatError:n}=this._core["helper"],o=`groupID:${r} localMainSequence:${t} serverMainSequence:${s} keyList:`+l.keyList;if(3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:r,avChatRoomKey:i}),t=iu.getGroupAttributesCacheValues(l),{serverGroupAttributeList:s=[]}=e||{};return su({groupAttributes:t},{message:o,moreMessage:"from server, count:"+s.length})}catch(e){throw new n({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}var a=iu.getGroupAttributesCacheValues(l);return su({groupAttributes:a},{message:o,moreMessage:"from cache"})})}getGroupAttributesFromServer(i){return de(this,void 0,void 0,function*(){var{utils:{isUndefined:e},ssoLog:t}=this._core,{groupID:s,avChatRoomKey:r}=i,{AttrMainSeq:e=0,GroupAttrAry:r}=(yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:s,avChatRoomKey:r,groupType:e(r)?_c:pc},this._core))||{},t=(t.debug("getGroupAttributesFromServer",this._name+`._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:`+e),r.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return iu.refreshGroupAttributesCache({groupID:s,serverMainSequence:e,groupAttributeList:t,operation:gc}),{serverGroupAttributeList:r}})}},ku=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),Pu.init(e),wu.init(e),Gu.init(e),Uu.init(e),iu.init(e)}isGroupAttributesUpdated(e){return iu.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:i,withChangedAttributeInfo:n}=r,o=iu.getGroupAttributesCache(t)["localMainSequence"],a=i-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${n} diffSequence:`+a),0!=a)if(iu.saveGroupAttributesCacheValuesCopy(t),1!==n||1!=a){if(iu.hasGroupAttributesCache(t)){let e=iu.getGroupAttributesCache(t)["avChatRoomKey"];Uu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{iu.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else iu.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){iu.reset()}};function Fu(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:i,MsgPriority:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,TinyId:u,ToGroupId:c,GroupInfo:d,MsgBody:h}=e,g=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:i,From_Account:n,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:i,from:n,to:o}}();return{clientSequence:s,from:r,clientTime:i,priority:n,random:o,sequence:a,time:l,tinyID:u,to:c,groupProfile:g,elements:("tips"===t?$u:xu)(h)}}function $u(r){let t={};return Object.keys(r).forEach(s=>{var e;switch(s){case"MemberNum":t.memberCount=r[s];break;case"OpType":t.operationType=r[s];break;case"Operator_Account":t.operatorID=r[s];break;case"List_Account":t.userIDList=r[s];break;case"MsgMemberExtraInfo":t.memberInfoList=null==(e=r[s])?void 0:e.map(e=>qu(e));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=qu(r[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(o){let e={};return Object.keys(o).forEach(n=>{switch(n){case"GroupIntroduction":e.introduction=o[n];break;case"GroupName":e.groupName=o[n];break;case"GroupFaceUrl":e.avatar=o[n];break;case"GroupNotification":e.notification=o[n];break;case"ApplyJoinOption":e.joinOption=o[n];break;case"InviteJoinOption":e.inviteOption=o[n];break;case"ShutupAll":e.muteAllMembers=o[n];break;case"Owner_Account":e.ownerID=o[n];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:i}=o[n];return{changedKeyList:e,groupAttributeList:i.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":t.msgMemberInfo=null==(e=r[s])?void 0:e.map(e=>{var{ShutupTime:e,User_Account:t}=e;return{muteTime:e,userID:t}});break;case"OnlineMemberInfo":t.onlineMemberInfo=function(){var{ExpireTime:e,OnlineMemberNum:t}=r[s];return{expireTime:e,onlineMemberNum:t}}();break;case"GroupCounterInfo":t.groupCounterInfo=r[s].map(e=>{var{GroupCounterSeq:e,GroupCounter:t,Type:s}=e;return{type:s,groupCounterSeq:e,counterList:t}})}}),t}function qu(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function xu(t){let s={};return Object.keys(t).forEach(e=>{switch(e){case"MsgKey":s.messageKey=t[e];break;case"Operator_Account":s.operatorID=t[e];break;case"ReportType":s.operationType=t[e];break;case"Authentication":s.authentication=t[e];break;case"MsgFlag":s.messageRemindType=t[e];break;case"UserDefinedField":s.userDefinedField=t[e];break;case"RemarkInfo":s.remarkInfo=t[e];break;case"BanDuration":s.duration=t[e];break;case"MuteTime":s.muteTime=t[e]}}),s}class Vu{constructor(e){this.type=Ga.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=$u(e);return new Vu(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"groupProfile":this._initGroupProfile(t[e]);break;case"operatorInfo":this._initOperatorInfo(t[e]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(t[e]);break;case"newGroupProfile":this._initNewGroupProfile(t[e]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[e]=t[e]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];Ec[r]&&(this.content.groupProfile[r]=t[r])}}_initOperatorInfo(t){this.content.operatorInfo={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];this.content.operatorInfo[r]=t[r]}}_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(t){this.content.newGroupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];"muteAllMembers"!==r?this.content.newGroupProfile[r]=t[r]:this.content.newGroupProfile.muteAllMembers=1===t.muteAllMembers}}}var Bu=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:i}=e;null!=e&&e.registerElementClass(i.MSG_GRP_TIP,Vu),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,r.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this)}onNewGroupTips(e){let t=(e||{})["data"],{messageList:s,conversationUpdateFieldList:r}=this._handleGroupTips(t),{notificationCenter:i,OuterEvent:n,appStore:{conversationStore:o}}=this._core;return null!=r&&r.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:r=0}=o.getConversation(e)||{};o.updateConversation(e,{lastMessage:t,unreadCount:s+r})}),0<s.length&&(i.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s}),this._handleGroupTipMessage(s)),{conversationUpdateFieldList:r}}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:i}=e,n=new Map,t=[],o=[];for(let t=0,e=i.length;t<e;t++){let e=Fu(i[t],"tips");if(r===vc){if(ku.isGroupAttributesUpdated(e)){ku.handleGroupAttributesUpdated(e);continue}if(Lu.isGroupCounterUpdated(e)){Lu.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(eu.hasLocalGroup(a)){a=this._assembleMessage(e);if(r===vc&&(a._onlineOnlyFlag=!0,o.push(a)),r===mc){if(!this._core.message.messageDataHandler.storeConversationMessage(a)&&s)continue;o.push(a)}this._handleConversationOptions(n,a)}}return t.push(...n.values()),{conversationUpdateFieldList:t,messageList:o}}_assembleMessage(e){var{OuterConstant:t,message:{messageFactory:s}}=this._core,t=(e.flow="in",e.conversationType=t.CONV_GROUP,s.createMessage(e)),s=(this._patchNickAndAvatar(e.elements,t),new Vu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:i,memberInfoList:n,operatorInfo:o}=e,a={};if(t(n)?t(o)||(a=o):i!==r.JOINED&&i!==r.KICKED&&i!==r.ADMIN_SET&&i!==r.ADMIN_CANCELED||(a=Object.assign({},n[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:i,conversationType:n}=t;let o;if(e.has(i))o=e.get(i),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=n,o.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:i,unreadCount:e,type:n,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(i,o)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:i}=e.payload,n=r.groupID,o=eu.getLocalGroup(n);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(n,s);break;case"groupName":o.name=s[e];break;default:o[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(i)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==i.userID||Object.keys(i).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:i[e]}),"role"===e&&this._updateSelfRole(o,i[e])}),eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(n)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=eu.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;t===fc?r=s.GRP_MBR_ROLE_OWNER:t===Ic&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=eu.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(t))}_handleGroupTipsRecover(e){var t=this._core["utils"]["isArray"],e=((null==e?void 0:e.result)||{})["groupTipList"];t(e)&&e.forEach(e=>{e=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1).messageList;this._handleGroupTipMessage(e)})}};class ju{constructor(e){this.type=Ga.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=xu(e);return new ju(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"remarkInfo":this.content.handleMessage=t[e];break;case"groupProfile":this._initGroupProfile(t[e]);break;case"memberInfoList":break;default:this.content[e]=t[e]}})}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];Sc[r]&&(this.content.groupProfile[r]=t[r])}}}var Ku=new class{constructor(){this._name="GroupSystemNotification"}init(e){var{message:{messageFactory:e},OuterConstant:{MSG_GRP_SYS_NOTICE:t}}=this._core=e;null!=e&&e.registerElementClass(t,ju)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:r,OuterEvent:i}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let i={};for(let e=0;e<t.length;e++){var n=Fu(t[e],"system"),o=n["elements"]["operationType"];o!==Tc&&(o=this._assembleMessage(n),this._core.message.messageDataHandler.storeConversationMessage(o))&&(r.push(o),i=this._handleConversationOptions(o,s))}return i.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[i]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new ju(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})),e=(s.setElement(t),s.isSystemMessage=!0,1===s.sequence&&1===s.random),t=2===s.sequence&&2===s.random;return(e||t)&&(s.sequence=r(),s.random=r(),s.generateMessageID()),s}_handleConversationOptions(e,t){var s=this._core["OuterConstant"],s={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&s.unreadCount++,s}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{var t=e.payload["operationType"];switch(t){case Cc:this._handleGroupJoinResult(e);break;case Mc:this._handleMemberKicked(e);break;case yc:this._handleGroupDismissed(e);break;case Oc:this._handleGroupInvitedResult(e);break;case Ac:this._handleGroupQuitResult(e);break;case Rc:this._handleMessageRemindTypeSynced(e);break;case Dc:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=eu.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${t} type:${s} hasLocalGroup:`+r),r||Hc(s)||(eu.updateLocalGroup([Object.assign({},e)]),eu.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];eu.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];eu.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=eu.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${e} hasLocalGroup:`+t),t||au.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];eu.updateLocalGroup([Object.assign({},e)]),eu.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=eu.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${e} type:${t} hasLocalGroup:`+s),s&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleMessageRemindTypeSynced(e){var{groupProfile:{groupID:e},messageRemindType:t}=e.payload;this._updateConversationProfile(e,{messageRemindType:t})}_handleAVChatRoomMemberBanned(e){var{groupID:e,type:t}=e.payload["groupProfile"];this._deleteLocalGroup(e,t)}_deleteLocalGroup(s,e){if(Hc(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}eu.deleteLocalGroup(s),eu.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},Hu=new class{init(e){(this._core=e).ssoLog.debug("GroupNotificationHandler.init"),Bu.init(e),Ku.init(e);var{notificationCenter:e,InnerEvent:t}=e,s=e["InnerEventSubType"];e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){Ku.onNewGroupSystemNotification(e)}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core,s=e["InnerEventSubType"];e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};let 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.name="Group"}install(e,t=[]){this._core=e,Ga.init(e),eu.init(e),_u.init(e,this),Du.init(e,this),fu.init(e),Lu.init(e),ku.init(e),Hu.init(e),e.helper.registerValidateConfig({auth:Xu,params:Qu}),this._installSubPlugins(t);var{notificationCenter:t,InnerEvent:e}=e;t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){var{isArray:t}=this._core["utils"];e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){eu.reset(),ku.reset(),Lu.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let 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){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:i,onFail:n}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=i,this._onFail=n}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getCurrentPollingInterval(this._groupID))}isRunning(){return this._isRunning}_request(){return de(this,void 0,void 0,function*(){try{var e=yield function(i,n){return de(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getCurrentPollingInterval(this._groupID));this._runNextPolling(t)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(-1<this._timeoutID&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(this._name+".stop timerID:"+this._timeoutID),-1<this._timeoutID&&(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){let e=(null==(t=this._map.entries().next().value)?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()}}let hl=e=>e===nl.GROUP_TIPS_HAS_NO_ROAMING||e===nl.GROUP_TIPS_HAS_ROAMING,gl=e=>e===nl.GROUP_SYSTEM_MESSAGE;function pl(g){var e,t,s,r,i,n,o,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:i,GId:n,MS:o,CCD:a,F_Account:l,IsSys:u,GInf:c,MsgBody:d}=g,h=le(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:i,ToGroupId:n,MsgSeq:o,CloudCustomData:a,From_Account:l,IsSystemMsg:u,GroupInfo:_l(c),MsgBody:ml(d)},h)}(),l=a,u=l["Event"];if((hl(u)||gl(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===nl.BROADCAST_MESSAGE||u===nl.NORMAL_MESSAGE){var c=l;let e=el["core"]["OuterConstant"];c.CloudCustomData=c.CloudCustomData||"",c.MsgBody=c.MsgBody.map(t=>{if(t.MsgType===e.MSG_CUSTOM){let{content:e={}}=t;t.content=Object.assign({Data:"",Desc:"",Ext:""},e)}return t})}return hl(u)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:i,OpType:n}=(c=l).MsgBody||{},"number"==typeof e||1!==n&&2!==n||(c.MsgBody.GroupJoinType=2===n?0:1),s||(c.MsgBody.MsgMemberExtraInfo=null==i?void 0:i.map(e=>({UserId:e}))),1!==n||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),gl(u)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:i}=(o=l).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:i,ImageUrl:"",NickName:""},e),o.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*o.MsgTimeStamp},o.MsgBody),o.MsgBody=Object.keys(o.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:o.MsgBody[t]}),{})),a}function _l(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:i,F_Ll:n}=e,e=le(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),i&&(t.From_AccountNick=i),n&&(t.From_AccountLevel=n),t}function ml(e){let t=e;var s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:i,UDF:n,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:l}=e,e=le(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:i,UserDefinedField:n},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=le(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=null==l?void 0:l.map(e=>{var{Img:t,NN:s}=e,e=le(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},e)})),a&&(t.OnlineMemberInfo=function(){var{ET:e,Num:t}=a;return{ExpireTime:e,OnlineMemberNum:t}}()),t});return Array.isArray(e)?s:s[0]}var vl=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(i,e,n=!1){this._sortServerMessageList({groupID:i,serverMessageList:e,isHistoryMessage:n});var o=this._handleMessageList(i,e);if(0!==o.length){if(!n){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=el["core"];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}})(o[o.length-1]);e.updateConversation(""+t+i,{lastMessage:s})}this._checkMessageStacked(o);let e=o.filter(e=>!0===e.isModified),t=o.filter(e=>!1===e.isModified),{MESSAGE_RECEIVED:s,MESSAGE_MODIFIED:r}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:r,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let r=[];r=this._avChatRoomHandler.isPollingSimplifiedMessage()&&!s?(t.sort((e,t)=>e.MS-t.MS),t.map(e=>e.MS)):(t.sort((e,t)=>e.MsgSeq-t.MsgSeq),t.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${e} count:${r.length} sequenceList:`+r),r.length=0}_handleMessageList(s,r){var i,n,{messageDataHandler:o,messageHelper:a}=this._core["message"],l=this._avChatRoomHandler.isPollingSimplifiedMessage(),u=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(l&&(e=pl(e)),gl(e.Event)&&Object.values(ol).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),i=a.parseServerGroupMessage(e),(n=this._createMessage(i)).level=e.GroupInfo.From_AccountLevel,hl(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(i)?this._avChatRoomHandler.handleGroupAttributesUpdated(i):null===this._filterDuplicateMessage(n)||o.isMessageSentByCurrentInstance(n)||(1===i.isModified&&(n.isModified=!0),hl(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(n)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];hl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),gl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(nl).includes(t)?t===nl.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===nl.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===nl.MESSAGE_REACTION?null:e:(console.warn(this._name+".onMessageReceived unknown event:"+t),null)}_createMessage(e){var{message:{messageFactory:t},OuterConstant:s}=this._core;let r=s.CONV_GROUP;e.event===nl.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:i,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:o,Reason:a=""}}=e,l=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+i.CONV_GROUP+n,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:r};l.push(e)}),0!==l.length&&this._emitEvent({name:t,data:l})}_onLiveCustomData(e){var t=this._core["OuterEvent"]["ROOM_CUSTOM_DATA_RECEIVED"],{ToGroupId:e,MsgSeq:s,MsgTimeStamp:r,MsgBody:i}=e,i=(null==i?void 0:i.Content)||(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:i}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+i)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let 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(s){var{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,i=this._avChatRoomHandler.isPollingSimplifiedMessage(),n=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];i&&(e=pl(e));var a=r.parseServerGroupMessage(e);Object.values(nl).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(n.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<n.length&&this._emitEvent({name:e,data:n})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:i=il}=r,n=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:n,memberCount:r,expireTime:i}:(e.latestUpdateTime=n,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let fl=e=>{var{store:t}=el["core"];return(t.get("cloudConfig")||{})[e]},Il=e=>{var{utils:{isUndefined:t}}=el["core"];return!t(e)},El=()=>{var e=fl("polling_interval");return Il(e)?parseInt(e,10):300},Sl=()=>{var e=fl("polling_simplified_msg");return Il(e)?parseInt(e,10):0};var Cl=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,vl.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:r,GroupInfo:{GroupId:i,GroupType:n}}=s[e],r=Object.values(ol).includes(r.ReportType);n===t&&r&&this.reset(i)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||El()}isPollingSimplifiedMessage(){return 0!==Sl()}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}updateLocalOnlineMemberCount(e,t){this._onlineMemberCountMap.set(e,t)}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){let{GRP_LIVE:t}=this._core["OuterConstant"],e=[];return e=0<this._joinedGroupMap.size?[...this._joinedGroupMap.values()].filter(e=>e.type===t):e}handleJoinGroupResult(l){return de(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:i,group:n,historyMessageList:o=[]}=l,a=n["groupID"];return yield this._preCheck(n),this._joinedGroupMap.set(a,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<o.length&&vl.onMessageReceived(a,o,!0),e(i)?{code:0,data:{status:r.JOIN_STATUS_SUCCESS,group:n}}:{code:0,data:this.startMessageLongPolling(l)}})}_preCheck(n){return de(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:r},ssoLog:i}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=fl("polling_count_limit"),Il(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:cl,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&n.type!==e.GRP_LIVE){var[t,s]=this._joinedGroupMap.entries().next().value;if(s.selfInfo.role===e.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(t);else try{yield r(t)}catch(e){i.debug("quitGroup",this._name+`._preCheck quitGroup failed, groupID:${t} info:`,e)}this.reset(t)}})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,i=r["groupID"];return this._pollingRequestInfoMap.set(i,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(i,El()),this._startPolling(i),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:r}}_startPolling(t){if(this._core.ssoLog.debug("_startPolling",this._name+"._startPolling groupID:"+t),this._pollingInstanceMap.has(t)){let e=this._pollingInstanceMap.get(t);void((null==e?void 0:e.isRunning())||null==e||e.start())}else{let e=new ll({core:this._core,manager:this,groupID:t,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});e.start(),this._pollingInstanceMap.set(t,e)}}_handleRequestParams(e){var{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:Sl()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Sl()}}_handleSuccess(s,e){var r=e["ErrorCode"];if(0!==r){let{longPollingKey:e,startSequence:t}=this._pollingRequestInfoMap.get(s)||{};void console.warn(`${this._name}._handleSuccess groupID:${s} key:${e} startSeq:${t} errorCode:`+r)}else this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,e)}_handleResponseData(t,e){var{Key:e,NextSeq:s,NextBroadcastSeq:r,RspMsgList:i=[],RspBroadcastMsgList:n=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<i.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,El())),vl.onMessageReceived(t,i);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=fl("polling_no_msg_count"),Il(s)?parseInt(s,10):20)){let e=El()+(r=fl("polling_interval_plus"),Il(r)?parseInt(r,10):2e3);this._pollingIntervalMap.set(t,e)}}0<n.length&&vl.onBroadcastMessageReceived(n)}_handleFailure(e,t){var{ssoLog:s,utils:{safeStringify:r}}=this._core;s.warn("polling",this._name+`._handleFailure groupID:${e} error: `+r(t))}_joinedAVChatRoomCount(){let t=this._core["OuterConstant"],e=[];return(e=0<this._joinedGroupMap.size?this.getJoinedGroups().filter(e=>e.type===t.GRP_AVCHATROOM):e).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){vl.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,r,i;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:r,count:i}=(()=>{var e=fl("av_members_freq_limit");if(Il(e)){var{interval:e,count:t}=JSON.parse(e);if(0<t&&0<e)return{interval:e,count:t}}return{interval:30,count:4}})(),Date.now()-t>1e3*r)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),i<s)}_stopPolling(e){var t,s;if(this._core.ssoLog.debug("_stopPolling",this._name+"._stopPolling groupID:"+e),e)({appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:t}}=this._core),s.deleteConversation(""+t+e),null!=(s=this._pollingInstanceMap.get(e))&&s.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),this._membersReqInfoMap.delete(e);else{for(let 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(){var o=this._joinedGroupMap.size;if(1<o){let{common:e,OuterConstant:s,ssoLog:t}=this._core,r=e.isUnlimitedAVChatRoom()?1:0,i=[],n=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?n:i).push(e)}),t.info("longPollingCount",String(o),{moreMessage:`av:${i.join(",")} live:${n.join(",")} code: `+r,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,vl.reset()}},Ml=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(i){return de(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(i),{status:s,group:{type:r}}=t["data"];return r!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:Cl.handleJoinGroupResult(t.data)})}},yl=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}quitGroup(r){return de(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Cl.reset(r),t})}},Ol=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}dismissGroup(r){return de(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Cl.reset(r),t})}},Al=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(i){return de(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=i["groupID"],e=e.getGroup(r);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits(tl)){if(Cl.isOverFrequencyLimit(r))throw{code:2996,message:"Over frequency limit: get_members-"+r};return this._getGroupMemberList(i)}return this._parentPlugin.groupMember.getGroupMemberList(i)})}_getGroupMemberList(n){return de(this,void 0,void 0,function*(){let i="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return de(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(n,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${i} ok, groupID:${n.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${i} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:i=0,Marks:n=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:i,marks:n,isOnline:!0}})}},Tl=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupOnlineMemberCount(s){return de(this,void 0,void 0,function*(){var{appStore:{groupStore:e},OuterConstant:t}=this._core,e=e.getGroup(s);return e?e.type===t.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(r){return de(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=Cl.getLocalOnlineMemberCount(r);if(e(s)||this._isExpired(r)){let{memberCount:e=0}=yield this._getOnlineMemberCountFromServer(r);return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${e} from server.`),{code:0,data:{memberCount:e}}}return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${s.memberCount} from local.`),{code:0,data:{memberCount:s.memberCount}}})}_isExpired(e){var e=Cl.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(n){return de(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0,ExpireTime:s=il}=e||{},r=Date.now(),i={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return Cl.updateLocalOnlineMemberCount(n,i),{memberCount:t}}catch(e){var 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}})}},Rl=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}deleteGroupMember(o){return de(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:i}=this._core,n=o["groupID"],t=t.getGroup(n);if(s(t))throw new r.ChatError({functionName:e,code:rl});if(t.type!==i.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(r.checkBusinessCapabilityBits(sl))return this._deleteGroupMember(o);throw new r.ChatError({functionName:e,code:ul})})}_deleteGroupMember(a){return de(this,void 0,void 0,function*(){var t="_deleteGroupMember",{appStore:{groupStore:e},helper:s,ssoLog:r}=this._core,{groupID:i,duration:n=0,userIDList:o}=a;if(0===n)throw new s.ChatError({functionName:t,code:al});try{return yield function(i,n){return de(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(a,this._core),r.debug(t,this._name+`.${t} ok, groupID:`+i),{code:0,data:{group:e.getGroup(i),userIDList:o}}}catch(e){throw new s.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){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return de(this,void 0,void 0,function*(){var i="markGroupMemberList",{groupID:n,markType:o,enableMark:a,userIDList:l=[]}=e,u=this._generateRequestData(e);try{let e=yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(u,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,l);return{code:0,data:{successUserIDList:s,failureUserIDList:r},successLog:{message:`${this._name}.${i} ok, groupID:${n} markType:${o} enableMark:${a} success:${s.length} fail:`+r.length}}}catch(e){throw new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:i=[]}=e,n=!0===r?1:2,o=[...i];return 500<o.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:n,memberList:o.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){let s=[],r=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:r).push(t)}),{successUserIDList:s,failureUserIDList:r}}},bl=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),Ml.init(e,t),yl.init(e,t),Ol.init(e,t),Al.init(e,t),Tl.init(e,t),Rl.init(e,t),Dl.init(e)}},Nl=new class{constructor(){this._name="LiveHandler"}init(e){var{helper:e,ssoLog:t}=this._core=e;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),t.debug("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:r,ssoLog:i}=this._core,{groupID:e,longPollingKey:n,longPollingSequence:o=1}=e;if(s(n))return i.warn("startMessageLongPolling",this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});Cl.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=Cl.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),i.debug("startMessageLongPolling",this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${n} longPollingSequence:`+o),s={groupID:e,type:r.GRP_LIVE};return Cl.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:n,startSequence:o}),Cl.startMessageLongPolling({group:s,longPollingKey:n,startSequence:o})}stopMessageLongPolling(e){e=e.groupID;return Cl.reset(e),this._core.ssoLog.debug("stopMessageLongPolling",this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(i){return de(this,void 0,void 0,function*(){var t=this._core["ssoLog"],s=i["groupID"];try{var e=yield function(r,i){return de(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(i,this._core),{RspMsgList:r=[]}=e||{};t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages ok, groupID:${s} count:`+r.length),0<r.length&&Cl.handleLiveHistoryMessages(s,r)}catch(e){t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages failed, groupID:${s} info:`+e.message)}})}},Ll=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,el.init(e),Cl.init(e,t),bl.init(e,t),Nl.init(e);var{notificationCenter:t,InnerEvent:e}=e,s=t["InnerEventSubType"];t.subscribeInnerEvent(e.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Cl.onAVChatRoomSystemNotification(e)}_reset(){Cl.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core,s=e["InnerEventSubType"];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)}};let Pl=new class{init(e){this.core=e}},wl="message",Gl="user",Ul={OR:"or",AND:"and"},kl=20,Fl=20,$l=20,ql={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},xl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Ul.OR,Ul.AND].includes(e)||"keywordListMatchType should be OR or AND"},Vl={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&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:t=>{var e=Pl.core["OuterConstant"];if(!Array.isArray(t))return"groupTypeList should be an array";var s=[e.GRP_PUBLIC,e.GRP_COMMUNITY,e.GRP_WORK,e.GRP_MEETING];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"groupTypeList should be supported group type"}},Kl={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=Pl.core["OuterConstant"],s=[e.MSG_TEXT,e.MSG_IMAGE,e.MSG_AUDIO,e.MSG_FILE,e.MSG_VIDEO,e.MSG_LOCATION,e.MSG_CUSTOM,e.MSG_MERGER];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"messageTypeList should be supported message type"}},Hl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Pl.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Wl=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),Yl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Pl.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},zl={searchCloudMessages:{keywordList:ql,keywordListMatchType:xl,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:Kl,conversationID:Hl,timePosition:Wl("timePosition"),timePeriod:Wl("timePeriod")},searchCloudUsers:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,count:Vl,miniBirthday:Wl("miniBirthday"),maxBirthday:Wl("maxBirthday"),gender:Yl},searchCloudGroupMembers:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,count:Vl,groupTypeList:jl,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,count:Vl,groupTypeList:jl}},Jl={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var td,Ql=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,Pl.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(p){return de(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a}=this._core,{conversationID:e,timePeriod:t,timePosition:s}=p,r=le(p,["conversationID","timePeriod","timePosition"]),i=Object.assign({count:100},r);e&&(e.startsWith(o.CONV_C2C)?i.account=e.replace(o.CONV_C2C,""):e.startsWith(o.CONV_GROUP)&&(i.groupID=e.replace(o.CONV_GROUP,""))),this._setTimeRangeParams(i,{timePeriod:t,timePosition:s});var n=yield function(c){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:i,endTime:n,startTime:o,cursor:a,account:l,groupID:u}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:i,EndTime:n,StartTime:o,Cursor:a,PeerAccount:l,GroupID:u};return Pl.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(i);if(!n)return{code:0,data:{}};var{ErrorCode:l,ErrorInfo:u,TotalCount:c,Cursor:d="",ConversationMsgs:h=[]}=n;if(0!==l)throw{errorCode:l,errorInfo:u};var g=`keywordList:${p.keywordList} keywordListMatchType:${p.keywordListMatchType} cursor:${p.cursor} res: totalCount:`+c;return{code:0,data:{searchResultList:h.map(e=>{let{MsgList:t,Count:s,GroupID:i,UserID:r}=e,n=i?""+o.CONV_GROUP+i:""+o.CONV_C2C+r;return this._isSearchingAllConversations(p)&&1<s?{conversationID:n,messageCount:s,messageList:[]}:{conversationID:n,messageCount:s,messageList:t.map(e=>{return a.isEmpty(i)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}),cursor:d,totalCount:c},successLog:{message:g}}}catch(e){var{errorCode:n,errorInfo:l}=e||{};this._handleError({errorCode:n,errorInfo:l,searchType:wl,functionName:"searchCloudMessages"})}})}searchCloudUsers(v){return de(this,void 0,void 0,function*(){var s;try{var{keywordListMatchType:e,count:t=Fl}=v,r=le(v,["keywordListMatchType","count"]),i=Object.assign({count:t,keywordListMatchType:e===Ul.AND?1:0},r),n=(this._setBirthdayRangeParams(i,v),yield function(a){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:i,cursor:n,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,UserBirthStart:r,UserBirthEnd:i,Gender:o};return Pl.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(i));if(!n)return{error:0,data:{}};var{ErrorCode:o,ErrorInfo:a,TotalCount:l,Cursor:u="",Users:c=[]}=n;if(0!==o)throw{errorCode:o,errorInfo:a};var d=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} count:${v.count} res: totalCount:`+l,h=[];for(let e=0,t=c.length;e<t;e++){var g,p,{UserID:_,ProfileItems:m}=c[e];_!==this._core.OuterConstant.USER_NOT_FOUND&&""!==_&&(g=m.map(e=>({tag:e.Tag,value:e.StrValue})),p=null==(s=this._core.user.userProfile)?void 0:s.createProfile(_,g),h.push(p))}return{code:0,data:{searchResultList:h,cursor:u,totalCount:l},successLog:{message:d}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(d){return de(this,void 0,void 0,function*(){try{var{count:t=$l,keywordListMatchType:s}=d,r=le(d,["count","keywordListMatchType"]),i=yield function(o){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i,groupIDList:n}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r,GroupIdList:n};return Pl.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Ul.AND?1:0},r));if(!i)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:o,GroupMembers:a=[],Cursor:u,TotalCount:c}=i;if(0!==n)throw{errorCode:n,errorInfo:o};let e=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+c,l=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:r,GroupMemberUserName:i,GroupMemberUserID:n,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:n,nick:i,nameCard:o,avatar:a};if(l.has(t)){let e=l.get(t);e.memberList.push(s),l.set(t,e)}else l.set(t,{groupInfo:e,memberList:[s]})}),{code:0,data:{searchResultList:[...l.values()],cursor:u,totalCount:c},successLog:{message:e}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(c){return de(this,void 0,void 0,function*(){try{var{count:t=kl,keywordListMatchType:s}=c,e=le(c,["count","keywordListMatchType"]),r=yield function(n){return de(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i}=n,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r};return Pl.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Ul.AND?1:0},e));if(!r)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:n,Groups:o,Cursor:a,TotalCount:l}=r;if(0!==i)throw{errorCode:i,errorInfo:n};var u=`keywordList:${c.keywordList} keywordListMatchType:${c.keywordListMatchType} cursor:${c.cursor} count:${c.count} res: totalCount:`+l;return{code:0,data:{searchResultList:(null==o?void 0:o.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:r,GroupName:i,GroupOwnerTinyID:n,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:l,GroupAddOption:u,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:i,ownerTinyID:n,ownerID:o,ownerNick:a,type:l,joinOption:u,inviteOption:c}}))||[],cursor:a,totalCount:l},successLog:{message:u}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&0<t&&(e.startTime=s&&0<s?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&0<s&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s}){var r=this._core["helper"];let i=e;throw 60020===e?i="SearchUnable":s!==wl&&27003===e?i="SearchParamsError":s!==wl&&60018===e&&(i="SearchOverLimit"),new r.ChatError({code:i,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){var{miniBirthday:t,maxBirthday:s}=t;void 0!==t&&(e.miniBirthday=t,void 0===s)&&(e.maxBirthday=4294967295),void 0!==s&&(e.maxBirthday=s)}};function Xl(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Zl="qualityStat",ed="im-ssolog-quality-stat",sd=(!function(e){e[e.ONLINE=8]="ONLINE"}(td=td||{}),"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},gd=[od,id,rd,ad,cd],pd=[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},vd="quality_stat";var fd=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(md))}init(e){this._core=e,Object.values(gd).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,i=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case i.TOTAL_COUNT:this._handleTotalCount(t);break;case i.SUCCESS_COUNT:this._handleSuccessCount(t);break;case i.FAILED_COUNT:this._handleFailedCount(t,s);break;case i.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,i,n,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:i}=o,r=Xl(s/t*100,2),n=Xl((i=s+i)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:i,percent_platform:n,average_value:o}):null}_handleTotalCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.totalCount++}_handleSuccessCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.successCount++}_handleFailedCount(s,e){var t=null!=(t=null==e?void 0:e.code)?t:null==e?void 0:e.errorCode;if(this._isUserSideError(t)){let e=this._getSendMessageSpecifiedKey(s),t=e&&this._messageStatsMap.get(e);t&&t.failedCountOfUserSide++}}_handleSendCost(e,t){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&(e.costSum+=Date.now()-t,e.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||120001<=e&&e<=13e4||10100<=e&&e<=10200}_getSendMessageSpecifiedKey(s){let{MSG_IMAGE:e,MSG_AUDIO:t,MSG_VIDEO:r,MSG_FILE:i,CONV_C2C:n,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,i].includes(s.type))return ad;if(s.conversationType===n)return od;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===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){e=this._messageStatsMap.get(e);e&&(e.totalCount=0,e.successCount=0,e.failedCountOfUserSide=0,e.costSum=0,e.costCount=0,e.fileSizeSum=0)}},Id=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){var{OuterEvent:e,notificationCenter:t}=this._core=e;this._initStatsMap(),t.subscribeOuterEvent(e.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){var t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:r},ssoLog:i}=this._core;s(t)||!this._currentCycleStats.has(t)?i.warn("addMessageSequence",Zl+".addMessageSequence invalid key:"+t):({conversationID:s,sequence:i}=e,e=s.replace(r,""),0!==(s=this._lastCycleStats.get(t)).size&&s.has(e)&&i>(r=s.get(e)).minSeq&&i<r.maxSeq?this._insertToLastCycle(i,r):this._addToCurrentCycle(t,e,i))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,i=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(i+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:i,percent_business:Xl(i/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(pd).forEach(e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)})}_onMessageReceived(e){var{data:e=[]}=e;e.forEach(e=>{this.addMessageSequence(e)})}_transferCycleDataOptimized(e){var t=this._currentCycleStats.get(e);if(t){let r=new Map;t.forEach((e,t)=>{var s=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;r.set(t,{sortedSequences:s,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,r),this._currentCycleStats.set(e,new Map)}}_getReceivedMessageSpecifiedKey(s){let{CONV_GROUP:e,GRP_AVCHATROOM:r}=this._core["OuterConstant"];if(s.conversationType===e&&!0!==(null==s?void 0:s._onlineOnlyFlag)){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);return t?(s=t["type"],s===r?dd:ud):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var 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,r=e.length-1;for(;s<=r;){var i=Math.floor((s+r)/2);if(e[i]===t)return i;e[i]<t?s=i+1:r=i-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},Ed=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(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)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],i=[s,r];t.forEach(e=>{!i.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Xl(this._totalDelay/e,1)}_calculatePercentage(e,t){return Xl(e/t*100,2)}},Sd=new class{init(e){this.core=e}},Cd=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:i,DESTROY:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;Sd.init(e),fd.init(e),Id.init(e),Ed.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(i,this._reset,this),s.subscribeInnerEvent(n,this._dispose,this)}handleLoginSuccess(){var{store:e,helper:t,utils:{isUndefined:s}}=this._core,e=(e.get("cloudConfig")||{})["q_rpt_interval"],s=s(e)?12e4:Number(e);t.taskScheduler.addTask({id:vd,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[..._d.map(e=>{e=this._buildQualityReportItem(e);return e?Object.assign(Object.assign({},e),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){var t=this._core["constants"]["QUALITY_METRICS"],{label:e,data:s}=e;e===t.MESSAGE_SEND_SUCCESS_RATE&&fd.dispatchSendStats(s)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){var{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},e=(e.get("instance")||{})["sdkAppId"],{q_rpt_sdkappid_bl:s=[]}=s;if(!t.isEmpty(s))return s.split(",").map(e=>Number(e)).includes(e)}_isTinyIDInWhitelist(){var{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},e=e.get("login")||{},e=Number(e.tinyID),{q_rpt_tinyid_wl:s=[]}=s;if(!t.isEmpty(s))return s.split(",").includes(e)}_buildQualityReportItem(e){var t=this._getStatResultByKey(e);return null===t?null:(e={quality_type:hd[e],timestamp:Date.now(),network_type:td.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case nd:return Ed.getStatResult();case od:case id:case rd:case ad:case cd:return fd.getStatResult(e);case ud:case ld:case dd:return Id.getStatResult(e);default:return null}}_uploadQualityReports(t){return de(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=Sd.core,s="imopenstat.tim_web_report_v2",e=e.generateSSOLogProtocolData({servcmd:s,data:r}),s=e.head.seq+s;t.sendPacket(e,{requestId:s})}(),this._reportIndex++,this._wholePeriod=!1}catch(e){console.warn("doReport failed. error:",e),this._pendingReports=this._pendingReports.concat(t),this._cacheFailedLogs()}})}_cacheFailedLogs(){var e=this._pendingReports,t=Zl+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(ed)||[],...e];10<s.length&&(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(){var e=this._core["helper"];e.taskScheduler.removeTask(vd)}_dispose(){var{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:r}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(r,this._dispose,this),this._reset(),Ed.dispose(),Id.dispose()}};let Md=1,yd=300;var Od=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:i}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(i.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return de(this,void 0,void 0,function*(){let i=this._core["OuterConstant"],n=[],o=[];return yield Promise.all(null==e?void 0:e.map(r=>de(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+i.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:o})),n.push(e.replace(i.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:n,groupTipList:o}})}_recoverHistoryForConversation(e){return de(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:S,serverLastMessageSequence:E,groupTipList:C}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:i,notificationCenter:n,message:o,appStore:a,common:{getMessagePreviewText:l}}=this._core,u=E-S,c=Math.min(20,u),d={},h=yield o.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:I,sequence:S+c,direction:i.Direction.FORWARD,count:c}),{nextReqMessageIDFromServer:g,hasNoMoreHistoryMessage:p,messageList:_,serverGroupTipList:m}=h,v=(e(m)&&C.push(...m),p&&g<0),f=[];if(e(_)&&(_.forEach(e=>{o.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===i.CONV_SYSTEM&&(e.isSystemMessage=!1),o.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&n.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:I,localLastMessageSequence:e,serverLastMessageSequence:E,groupTipList:C})}t(d.lastMessage)&&(d.lastMessage.messageForShow=l(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(I,d))}catch(S){this._core.ssoLog.error("_recoverHistoryForConversation","Recovery failed for conversation:"+I,{error:S})}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var i;0<(null==e?void 0:e.length)&&(i=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,i))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&t>=Md&&t<yd}};let Ad=Rs.STANDARD,Td=[];Ad=Rs.STANDARD,Td=[$n,Fn,Bn,Xn,to,Cd,Od,qi,Zr,wa,Zu,Ll,Ql,bo];var Rd=Object.freeze({__proto__:null,ChatError:Xs,WorkflowManager:ln,buildAndSendPacket:mn,get builtInPlugins(){return Td},checkBusinessCapabilityBits:un,deepMerge:Cn,getCurrentUserID:En,getErrorMessage:Qs,getMessagePreviewText:Mn,isC2CConv:e=>t(e)&&e.slice(0,3)===Is.CONV_C2C,isCommunity:hn,isGroupConv:e=>t(e)&&e.slice(0,5)===Is.CONV_GROUP,isTopic:gn,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=ts.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:dn,registerInterceptor:an,registerValidateConfig:cn,requireAuth:Zs,get sdkEdition(){return Ad},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:i,CONV_AT_ALL_AT_ME:n}=As;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:i}=As,{groupID:n,sequence:o}=t,a=!1;return hn({groupID:n})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[i]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[i],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(i)&&(e=[n]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:rn,validateParameters:en});class Dd{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Dd._instance||(Dd._instance=new Dd),Dd._instance}static setInstance(e){Dd._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){var s=[];let r=(s=n(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=-1<r?s.splice(r,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&ss(e.install)?(t.add(e.name),ss(e.getInstalledSubPlugins)?e.install(Gd.getInstance().exposeApiForPlugin(),i):e.install(Gd.getInstance().exposeApiForPlugin()),ss(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):ss(e)?(t.add(e.name),e(Gd.getInstance().exposeApiForPlugin()),ss(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=ts.store.get("login"))?void 0:e.isLoggedIn)}}var qd,xd,Vd,Wd,bd=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:i}=s,n=this._conversationMap.get(e);n&&!ve(t)&&(Object.keys(t).forEach(e=>{n[e]=t[e]}),r)&&ts.notificationCenter.emitInnerEvent(cs.CONVERSATION_UPDATED,{needSort:i})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),ts.notificationCenter.emitInnerEvent(cs.CONVERSATION_UPDATED))}},Nd=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){let s=this._groupMap.get(e);s&&!ve(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},Ld=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:i,updateUnreadCount:n=!0}=e,o=le(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(r=this._messagesByConversation.get(s))?void 0:r.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(i,{conversationID:s,messageList:a,updateUnreadCount:n}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];gn(s)?ts.notificationCenter.emitInnerEvent(ms[e],t):ts.notificationCenter.emitInnerEvent(e,t)}},Pd=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)}},wd=Object.freeze({__proto__:null,conversationStore:bd,groupStore:Nd,messageStore:Ld,userStore:Pd});class Gd{static getInstance(){return Gd._instance||(Gd._instance=new Gd),Gd._instance}static setInstance(e){Gd._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this),reportModalView:this.reportModalView.bind(this)},this._apiHandlersMap={},this._apiMap={on:ts.notificationCenter.subscribeOuterEvent.bind(ts.notificationCenter),off:ts.notificationCenter.unSubscribeOuterEvent.bind(ts.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Dd.getInstance().installExternalPlugin.bind(Dd.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){ts.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){ts.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){ts.ssoLog.debug("setLogLevel",e),ts.ssoLog.setLogLevel(e)}setApplicationID(e){ts.store.set("instance",{applicationID:e})}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{common:{timeManager:n},utils:{safeStringify:t}}=ts,{apiName:o,context:s,methodName:a=o,matcher:r}=e;this._apiHandlersMap[o]||(this._apiHandlersMap[o]=[]),this._apiHandlersMap[o].push({context:s,methodName:a,matcher:r}),this._apiMap[o]&&1!==this._apiHandlersMap[o].length||(this._apiMap[o]=(...s)=>{let r=n.getServerTimeMs(),i=0;"login"===o&&(i=4),ws.includes(o)&&ts.ssoLog.debug(o,o+" start params: "+t(s)),rn(a,s);for(let t of this._apiHandlersMap[o])if(!t.matcher||t.matcher(s))try{let e=t.context[t.methodName].bind(t.context)(...s);return this._isPromiseLike(e)?this._handleAsyncResult(e,o,i,r):(this._reportApiSuccessLog({result:e,apiName:o,eventType:i,startTime:r}),e)}catch(s){throw ts.ssoLog.error(o,`${o} fail ${null==s?void 0:s.message})`,{error:s,costTime:n.getServerTimeMs()-r,eventType:i,method:o}),s}})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return de(this,void 0,void 0,function*(){var e,t;try{null!=(e=ts.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),ts.notificationCenter.emitInnerEvent(cs.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{ts.notificationCenter.emitOuterEvent(rs.SDK_DESTROY,{SDKAppID:null==(t=ts.store.get("instance"))?void 0:t.sdkAppId}),dn.clear(),Dd.getInstance().clear(),ln.getInstance().destroy(),ts.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:cs,InnerEventSubType:ts.notificationCenter.InnerEventSubType,OuterEvent:rs,OuterConstant:As,SignalingEvent:us,helper:Object.assign(Object.assign(Object.assign({},ts.utils),ts.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:an,registerValidateConfig:cn,checkBusinessCapabilityBits:un,registerWorkflowStep:ln.getInstance().registerWorkflowStep.bind(ln.getInstance()),ChatError:Xs}),apiMap:this._apiMap},ts),{constants:Object.assign(Object.assign({},Gs),ts.constants),common:Object.assign(Object.assign(Object.assign({},Rd),ts.common),{workflowManager:ln.getInstance()}),utils:ts.utils,appStore:wd})}callExperimentalAPI(e,t){return ts.ssoLog.debug(`callExperimentalAPI.${e} start params: `+ts.utils.safeStringify(t)),this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new Xs({code:Ts.INVALID_OPERATION}))}reportModalView(e){var{ssoLog:t,utils:{safeStringify:s}}=ts;try{t.createSSOLogData({method:"reportModalView",message:e,eventType:30}).end(!0)}catch(e){t.debug("reportModalView Report failed: "+s(e))}}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,r){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:r}),e)).catch(e=>{throw ts.ssoLog.error(t,`${t} fail ${null==e?void 0:e.message})`,{error:e,costTime:ts.common.timeManager.getServerTimeMs()-r,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:r,eventType:i}=e;var e=ts.common["timeManager"],{successLog:{message:n,moreMessage:o}={message:"",moreMessage:""}}=t||{},a=e.getServerTimeMs();"login"===s&&(r+=e.getTimeOffsetWithServer()),ws.includes(s)&&ts.ssoLog.info(s,s+` success ${n} `+o,{costTime:a-r,eventType:i,message:n,moreMessage:o}),null!=t&&t.successLog&&delete t.successLog}}class Ud{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){var{notificationCenter:e,store:t}=ts;t.set("login",{isReady:!1}),Gd.getInstance().registerApi({apiName:"login",context:this}),Gd.getInstance().registerApi({apiName:"logout",context:this}),Gd.getInstance().registerApi({apiName:"getLoginUser",context:this}),Gd.getInstance().registerApi({apiName:"isReady",context:this}),Gd.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),e.subscribeInnerEvent(cs.RECONNECTED,this._reLogin,this),ts.notificationCenter.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}login(l){return de(this,void 0,void 0,function*(){var e;let t=(ts.store.get("instance")||{})["sdkEdition"];try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Xs({functionName:"login",code:Ts.REPEAT_LOGIN});var s=yield this._performLogin(l),r=(this._validateAfterLogin(s),this._handleLoginSuccess(s),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,null==(e=ts.channel.getSocketAdapter())?void 0:e.getId()),{appId:i,href:n}=ts.store.get("instance")||{},{instanceID:o,customStatus:a}=s||{};return{code:0,data:s,successLog:{message:t,moreMessage:`socketID:${r} instanceID:${o} customStatus:${a} href: ${n} appId: `+i}}}catch(e){let t=e["errorCode"],s=(t!==Ts.REPEAT_LOGIN&&(this._latestLoginAt=0),new Xs({functionName:"login",code:t}));throw console.error(s),s}})}_reLogin(){return de(this,void 0,void 0,function*(){var e,t,s,r,i;try{this._isLoginIn()&&(t=yield Js(this._customLoginInfo))&&({instanceID:s,customStatus:r}=t,ts.store.set("login",{statusInstanceId:s}),ln.getInstance().executeWorkflow(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:vs.USER_STATUS_ONLINE}),i=null==(e=ts.channel.getSocketAdapter())?void 0:e.getId(),ts.ssoLog.info("reLogin",`socketId:${i} instanceId:`+s))}catch(e){console.warn(e)}})}logout(){return de(this,arguments,void 0,function*(t=Us.USER_INITIATED){let e=ts["ssoLog"];e.debug("logout","logout start logoutReason: "+t);try{yield this._performLogout(t),e.info("logout","logout success"),ts.ssoLog.uploadSSOLogData()}catch(t){let e=t["errorCode"];throw new Xs({functionName:"logout",code:e})}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?En():""}isReady(){var e;return null==(e=ts.store.get("login"))?void 0:e.isReady}setCustomLoginInfo(e=""){this._customLoginInfo=e}_updateAndEmitSDKReady(){ts.store.set("login",{isReady:!0}),setTimeout(()=>{ts.notificationCenter.emitOuterEvent(rs.SDK_READY,{name:rs.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ts.store.set("login",{isReady:!1}),ts.notificationCenter.emitOuterEvent(rs.SDK_NOT_READY,{name:rs.SDK_NOT_READY})}_validateAfterLogin(e){if(!e)throw new Xs({functionName:"login",message:"login response is empty"});var{tinyID:e,a2Key:t}=e||{};if(!e)throw new Xs({functionName:"login",code:Ts.NO_TINYID});if(!t)throw new Xs({functionName:"login",code:Ts.NO_A2KEY})}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Qs({code:"RepeatLogin",replacement1:null==(e=ts.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return de(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return ts.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Js(this._customLoginInfo)})}_ensureAsyncComplete(){return de(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=ts.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:i,purchaseBits:n}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),ts.user.userStatus.setCustomStatus(i),ln.getInstance().executeWorkflow(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:n}),ts.common.taskScheduler.addTask({id:qs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(s){return de(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=ts.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield ts.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ln.getInstance().reset(),ts.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;ts.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return de(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=ts.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield ts.channel.sendPacket(t,{requestId:e})}catch(e){ts.ssoLog.warn("_sendOnlinePresenceRequest"," error:"+e.message)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=ts.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ts.common.taskScheduler.removeTask(qs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ts.store.clear("login"),ts.store.set("login",{isReady:!1}),ts.store.set("instance",{applicationID:0})}_dispose(){this._reset();var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}let kd={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Fd={logout:!0};class $d{constructor(){this.loginAction=new Ud,this.kickedOutHandler=new zs,this.loginAction.init(),this.kickedOutHandler.init(),cn({auth:Fd,params:kd})}}!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(qd=qd||{}),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(xd=xd||{}),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"}(Vd=Vd||{});let Bd={1:xd.MSG_PRIORITY_HIGH,2:xd.MSG_PRIORITY_NORMAL,3:xd.MSG_PRIORITY_LOW,4:xd.MSG_PRIORITY_LOWEST},Kd=0,Hd=1,Yd=(!function(e){e.IN="in",e.OUT="out"}(Wd=Wd||{}),2),zd={};function Jd(e){var t,s,r;return e?(void 0===zd[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),zd[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+zd[e])):zd[e]+=1,zd[e]):0}class Qd{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=xd.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=ts.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:i,needReadReceipt:n,isSupportExtension:o,customModerationConfigurationId:a,to:l,from:u,nick:c="",avatar:d="",time:h,messageControlInfo:g,tinyID:p,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:S=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:A=hs.SUCCESS,revokeReason:O="",conversationSubType:T,clientSequence:R,protocol:D="JSON",revokerInfo:b={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:L,groupProfile:P,atUserList:G,flow:w,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||p,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=l,this.nick=c,this.avatar=d,this.protocol=D,this.random=void 0===L?(t=t||99999999,Math.round(Math.random()*t)):L,this.time=h||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==g||!g.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==g||!g.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=_,this.messageLifeTime=m,this.from=u||null,this.sequence=I||0,this.conversationType=f||qd.CONV_C2C,this.hasRiskContent=1<S,this.version=v,this.isPlaceMessage=E,this.isRevoked=2===E||8===C,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=O,this.revokerInfo=b,this._receiverList=M,this.conversationSubType=T,this.revoker=(null==b?void 0:b.revoker)||"",this.clientSequence=R||I||0,this.status=A,this.atUserList=G||[],this.flow=w,this.isRead=U,this.reInitialize(i),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(P)}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;return this._relayFlag?{isValid:!0}:0<(null==(e=this._elements)?void 0:e.length)?null==(t=null==(e=this._elements[0])?void 0:e.validateBeforeSend)?void 0:t.call(e):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){var{readReceiptSentByPeer:e,timestamp:t=0}=e;this.conversationType===qd.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===e,this.readReceiptInfo.timestamp=t)}_extractGroupInfo(e){var t,s;e&&({From_AccountNick:e,From_AccountHeadurl:t,MsgFrom_AccountExtraInfo:s}=e,s=(s||{})["NameCard"],"string"==typeof e&&(this.nick=e),"string"==typeof t&&(this.avatar=t),"string"==typeof s)&&(this.nameCard=s)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){var t=this.conversationType;t!==qd.CONV_SYSTEM?(e=t!==qd.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=qd.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Jd(e)),0===this.sequence&&this.conversationType===qd.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===qd.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class Xd{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new Xd({data:e,description:s,extension:t})}constructor(e){this.type=Vd.MSG_CUSTOM;var{data:e="",description:t="",extension:s=""}=e;this.content={data:e,description:t,extension:s}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{data:e,description:t,extension:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:s,Desc:t}}}validateBeforeSend(){let t=ts.utils["isEmpty"],e=[this.content.data,this.content.description,this.content.extension].some(e=>!t(e));return{isValid:e,error:e?null:{message:"content can not be empty"}}}}class Zd{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new Zd({text:e})}constructor(e){this.type=ds.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e;return 0<(null==(e=null==(e=this.content)?void 0:e.text)?void 0:e.length)?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},e=(e?this.payload:this.content)["text"];return{MsgType:this.type,MsgContent:{Text:e}}}}var eh=new class{constructor(){this._elementClassMap={[Vd.MSG_CUSTOM]:Xd,[Vd.MSG_TEXT]:Zd}}init(){Gd.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Gd.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){void 0!==t.prototype&&"constructor"in t.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){var{from:t,flow:s=Wd.OUT}=e,r=(ts.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:r})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:r})&&(e.flow=Wd.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new Qd(t)}createCustomMessage(t){let e=En(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[Vd.MSG_CUSTOM];if(!s)return null;if(r){let e=new r(t.payload);s.setElement(e)}return s}createTextMessage(e){var t,s;return e?(t="string"==typeof e.payload?e.payload:(null==(t=null==e?void 0:e.payload)?void 0:t.text)||"",t=new Zd({text:t}),s=En(),(e=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:r,tinyID:i}=ts.store.get("login")||{},n=Pd.getUserProfile(r);return e.nick=t||(null==n?void 0:n.nick)||"",e.avatar=s||(null==n?void 0:n.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=r,e.status=hs.UNSENT,e.flow=Wd.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Wd.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Wd.OUT}};let th={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}},sh={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},nh={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function oh(r,i){return Object.keys(i).forEach(e=>{var{range:t,defaultValue:s}=i[e];r[e]=t.includes(r[e])?r[e]:s}),r}function ih(e){var t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function rh(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,e=oh(e,sh),{sound:s="",FCMChannelID:r=""}=e,e=le(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:ih(s),OPPOChannelID:t,GoogleChannelID:r})}function ah(t){var{apnsInfo:t={},ignoreIOSBadge:s=!1,disableVoipPush:r}=t,t=oh(t,nh),{ignoreIOSBadge:i,disableVoipPush:n,enableIOSBackgroundNotification:o}=t,t=le(t,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),i=!0===i||!0===s?1:0;let a;return e(r)||(a=!1===r?1:0),e(n)||(a=!1===n?1:0),Object.assign(Object.assign({},t),{BadgeMode:i,IsVoipPush:a,ContentAvailable:o?1:0})}function ch(e){return ts.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:ah(e),AndroidInfo:rh(e)}:th}function uh(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:i,IsSyncMsg:n,MsgBody:o,MsgClientTime:a,MsgLifeTime:l,MsgRandom:u,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,S,{From_Account:E,To_Account:C}=e;if(1===n){let e=C;C=E,E=e}if(I){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;S={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:E,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:n,clientTime:a,messageLifeTime:l,random:u,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:g,to:C,tinyID:p,checkResult:_,cloudCustomData:m,revokerInfo:S,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:i,elements:gh(o)}}function lh(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,To_Account:o,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,to:o,elements:gh(t),messageVersion:a,cloudCustomData:l}}function dh(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,TinyId:d,CloudCustomData:h,MsgVersion:g,MsgCheckResult:p,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,S=xd.MSG_PRIORITY_NORMAL;if(Object.keys(Bd).includes(String(e.MsgPriority))&&(S=Bd[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}var E=function(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{e.GroupAtAllFlag===Kd?t.push(e.GroupAt_Account):e.GroupAtAllFlag===Hd&&t.push(As.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:n,priority:S,random:o,sequence:a,time:l,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:c,tinyID:d,cloudCustomData:h,messageVersion:g,messageCheckResult:p,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:E,elements:gh(i),to:hh(e)}}function hh(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=ts,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:i}={}}=e;return r!==s||t(i)?e:i}function gh(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=ts.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=ts.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function ph(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,GroupId:o,TopicId:a,MsgVersion:l,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,groupID:o,topicID:a,elements:gh(t),messageVersion:l,cloudCustomData:u}}function _h({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:i,flow:n,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&n===Wd.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:i,unreadCount:t?1:0,lastMessage:a})}function mh(e){return e.filter(e=>{var t=!ve(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||ts.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:`+e.sequence),t&&!s})}function vh(e){var t=ts.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var fh=Object.freeze({__proto__:null,autoIncrementIndex:Jd,filterValidMessages:mh,parseServerGroupMessage:dh,parseServerPushC2CModifyMessage:lh,parseServerPushGroupModifyMessage:ph,parseServerPushMessage:uh,parseServerPushMessageElement:gh,shouldStoreMessage:vh,updateConversationFields:_h});let Ih=ts.utils["isPlainObject"];function Eh(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,i=t["offlinePushInfo"],n=(e.conversationType===qd.CONV_C2C&&!0===s&&(i?i.disablePush=!0:i={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(n=e.cloudCustomData);var o=[];if(r&&Ih(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:n,messageControlInfo:o,offlinePushInfo:i}}function Sh(e){var t,{webhookInfo:{disableCloudMessagePreHook:e=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(e||s)return t=[],e&&t.push("ForbidBeforeSendMsgCallback"),s&&t.push("ForbidAfterSendMsgCallback"),t}function Ch(t,s){return de(this,void 0,void 0,function*(){var e=yield mn((t.conversationType===qd.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:o,offlinePushInfo:a}=Eh(e,t),l=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let u;return n(e._receiverList)&&0<e._receiverList.length&&(u=e._receiverList,50<e._receiverList.length)&&(u=e._receiverList.slice(0,50),console.warn("ReceiverListLimit")),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null==(s=ts.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:l,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:ch(a),SendMsgControl:r?void 0:o,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:u,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:Sh(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=Eh(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=ts.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?n: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:ch(o),forbidCallbackControl:Sh(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let Mh=ts.utils["isPlainObject"],{MSG_AUDIO:yh,MSG_FILE:Oh,MSG_IMAGE:Ah,MSG_VIDEO:Th,MSG_MERGER:Rh}=As;class Dh{init(){Gd.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![yh,Oh,Ah,Th,Rh].includes(e[0].type)})}sendMessage(c,d){return de(this,void 0,void 0,function*(){let{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:t}=Ps;if(!(c instanceof Qd))throw new Xs({code:Ts.MSG_INSTANCE_REQUIRED});let s=c.validateBeforeSend();if(!s.isValid){let{code:e,message:t=""}=s.error||{};throw new Xs({code:e,message:t})}this._reportMessageSendQuality({name:e,message:c});let l=!1;var u=(ts.message||{})["messageDataHandler"];try{let r=(d||{})["messageControlInfo"],i=null,n=(u.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===qd.CONV_C2C?(l=!0===(null==d?void 0:d.onlineUserOnly),i=yield Ch(c,d)):c.conversationType===qd.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),i=yield Ch(c,d)),i){let{messageDropReason:e,sequence:t,time:s}=i;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t,e),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:o,message:c,startTs:n}),!0===c.isResend){let e=u.findMessage(c.ID);e&&(ts.ssoLog.debug("sendMessage","sendMessage resend ok. ID:"+e.ID),u.deleteConversationMessage(e))}return c.status=hs.SUCCESS,c.time=s,c.conversationType===qd.CONV_GROUP&&(c.sequence=t),l?c._onlineOnlyFlag=!0:(u.storeConversationMessage(c),this._applySentMessageControlInfo(c,r),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=hs.FAIL,u.removeRandomOfSentMessage(c.random);var r=(e||{})["errorCode"],i=(null==e?void 0:e.errorInfo)||(null==e?void 0:e.message)||"";throw this._hasRiskContent(r)&&(c.hasRiskContent=!0),l||this._isRejectedByRestApi(r)||u.storeConversationMessage(c),this._reportMessageSendQuality({name:t,message:c,error:e}),i=`type:${c.type} from:${c.from} to:${c.to} `+i,new Xs({code:r,message:i,data:{message:c}})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,i=gn(s)?cs.TOPIC_NEW_MESSAGE:cs.NEW_MESSAGE;ts.notificationCenter.emitInnerEvent(i,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Mh(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t,s){e=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:`+s;ts.ssoLog.warn("messageDropReason",e)}_updateNickAndAvatarOfSentMessageByMe(e){var t=(ts.message||{})["messageDataHandler"];let s=!1;var r,i=e["conversationID"],n=t.getLatestMsgSentByMe(i);n&&({nick:n,avatar:r}=n,s=n!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:i,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(i){return de(this,void 0,void 0,function*(){var{to:t,from:s}=i;let r=t,e=Nd.getGroup(r);if(hn({groupID:r})&&null!=e&&e.isSupportTopic)throw new Xs({code:Ts.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(gn(t)&&([r]=t.split(Ms.TOPIC),e=Nd.getGroup(r)),!e&&"function"==typeof(null==(t=Gd.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield Gd.getInstance().getApiMap().getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===As.GRP_AVCHATROOM){let e=Qs({code:Ts.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new Xs({code:Ts.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){ts.notificationCenter.emitInnerEvent(cs.QUALITY_STAT,{label:Ls.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class bh{constructor(e){this.value=e,this.next=null}}class Nh{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new bh(e);this.head?this.tail.next=e:this.head=e,this.tail=e,this.size+=1}delete(t){if(this.head)if(this.head.value===t)this.head=this.head.next;else{let e=this.head;for(;e.next;){if(e.next.value===t)return void(e.next=e.next.next);e=e.next}}}has(e){if(!this.head)return!1;let t=this.head,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,--this.size)}peek(){var e;return null==(e=this.head)?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}var Lh=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Nh(100)}init(){ts.notificationCenter.subscribeInnerEvent(cs.LOGOUT,this._reset,this),ts.notificationCenter.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}get _messagesByConversation(){return Ld.getMessages()}storeConversationMessage(e,t=!1){var s=e["conversationID"];return!!s&&(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),!this._shouldSkipStoreMessage(e,t))&&(t=this._getUniqueIdOfMessage(e),this._messagesByConversation.get(s).set(t,e),this._updateLatestMessageMap(e),!0)}_updateLatestMessageMap(e){var t=e["conversationID"];"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){var s=this._getUniqueIdOfMessage(e),r=this._messagesByConversation.get(e.conversationID);if(null!=r&&r.has(s)){let e=null==r?void 0:r.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var{conversationID:t=""}=e,e=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(t)&&null!=(t=this._messagesByConversation.get(t))&&t.delete(e)}modifyConversationMessage(a,t){var l;if(this._messagesByConversation.has(a)||this._sparseMessagesByConversation.has(a)){let e=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(a,e);if(o){let{messageVersion:s,elements:r,cloudCustomData:i,checkResult:e=0}=t,n=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:`+s),o.version<s){let e=this._getUniqueIdOfMessage(o),t=fe(r);return null!=(l=this._messagesByConversation.get(a))&&l.has(e)?Ld.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:i,hasRiskContent:n,operation:gs.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=i,o.isModified=!0,o.hasRiskContent=n),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,s){var t;if(this._messagesByConversation.has(e))return null==(t=this._messagesByConversation.get(e))?void 0:t.get(s);if(this._sparseMessagesByConversation.has(e)){let t=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<t.length;e++)if(this._getUniqueIdOfMessage(t[e])===s)return t[e]}return null}findMessage(t){let s=null,e=Array.from(this._messagesByConversation.values());for(var r of e)if(s=Array.from(r.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var i of e)if(s=i.get(t)||null,s)break}return s}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:t,sequence:s,random:r,revoker:i}){let e=this._messagesByConversation.get(t),n=null;if(e){var o=Array.from(e.values());if(n=this._findMessageBySequenceAndRandom({messageList:o,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(n);return Ld.updateMessage(t,[e],{isRevoked:!0,revoker:i,operation:gs.revoke}),n}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(n=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return n.isRevoked=!0,n.revoker=i,n}}_findMessageBySequenceAndRandom({messageList:s,sequence:r,random:i}){for(let t=0;t<s.length;t+=1){var n=s[t];if(n.sequence===r&&(e(i)||n.random===i))return n}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],i=[],n=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);n.has(e)||(r.push(t),i.push([e,t]))}if(0<i.length){let e=new Map([...i,...n.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var i=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];i.has(e.ID)||i.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:i}=e;return e+`-${t}-${s}-${r}-`+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.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:n,latestNick:o,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),i=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===i&&(t!==o&&(e.nick=o),s!==n)&&(e.avatar=n)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ts.notificationCenter.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),ts.notificationCenter.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}};function Ph(e,t){var s,r,i,n,o,a,l,u=bd.getConversation(e);null!=u&&u.lastMessage&&(u=u["lastMessage"],{lastTime:s,lastSequence:r,version:i}=u,{time:t,sequence:n,messageVersion:o,elements:a,cloudCustomData:l}=t,s===t)&&r===n&&i!==o&&(u.type=a[0].type,u.payload=a[0].content,u.messageForShow=Mn(u.type,u.payload),u.cloudCustomData=l,u.version=o,bd.updateConversation(e,{lastMessage:u}))}class wh{init(){Gd.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(u){return de(this,void 0,void 0,function*(){let{to:r,payload:t,sequence:i,conversationType:n,random:o,time:a,from:l,type:s}=u;if(this._canModifyMessageElement(s)){let e=u.getElements();1<e.length&&(e[0].type=s,e[0].content=t)}try{let t=null,s;if(n===qd.CONV_C2C?t=yield function(c){return de(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:i,time:n,type:o,cloudCustomData:a}=c,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:i,MsgTime:n,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},u=yield mn({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:gh(e),messageVersion:t,cloudCustomData:s}}})}(u):n===qd.CONV_GROUP&&(t=yield function(o){return de(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=o,i={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:r},n=yield mn({servcmd:"openim.modify_group_msg",data:i});if(n){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=n;return{elements:gh(e),messageVersion:t,cloudCustomData:s}}})}(u)),t){let e=""+n+r;return r===En()&&n===qd.CONV_C2C&&(e=""+n+l),s={conversationType:n,from:l,to:r,time:a,random:o,sequence:i,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:u},successLog:{message:"to:"+r}}}}catch(e){let t=(e||{})["errorCode"];throw new Xs({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent(rs.MESSAGE_MODIFIED,{name:rs.MESSAGE_MODIFIED,data:[r]}),ts.notificationCenter.emitInnerEvent(cs.MESSAGE_MODIFIED,{conversationID:t,message:r}),Ph(t,e)}_canModifyMessageElement(e){return[Vd.MSG_TEXT,Vd.MSG_CUSTOM,Vd.MSG_LOCATION,Vd.MSG_FACE].includes(e)}}class Gh{init(){var e=ts["notificationCenter"],t=e["InnerEventSubType"];ln.getInstance().registerWorkflowStep(Ds.RECEIVE_C2C_NEW_MESSAGE,bs.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ln.getInstance().registerWorkflowStep(Ds.RECEIVE_C2C_NEW_MESSAGE,bs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){ln.getInstance().executeWorkflow(Ds.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(ts.message||{})["messageDataHandler"],r=[],i=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):vh(e)&&(s.storeConversationMessage(e)&&_h({conversationUpdateFields:i,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||r.push(e))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[bs.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[bs.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(e)}_emitMessageEvents(e){var t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=qd.CONV_C2C,e=uh(e),t=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Wd.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(n){var s;let o=(ts.message||{})["messageDataHandler"],r=null==(s=ts.store.get("login"))?void 0:s.userId,{from:i,nick:a,avatar:l,conversationID:u=""}=n;if(i!==r){let i=o.getLatestMsgSentByPeer(u);if(i){let{nick:s,avatar:r}=i;e(a)||e(l)?(n.nick=t(s)?s:n.nick,n.avatar=t(r)?r:n.avatar):a===s&&l===r||(o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:l,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:u,nick:a,avatar:l}))}}else{let e=o.getLatestMsgSentByMe(u);!e||a===e.nick&&l===e.avatar||o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:l,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=bd.getConversation(e)||{};r.avatar===s&&r.nick===t||bd.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),ts.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Ph(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=qd.CONV_C2C,e=lh(e),{to:s,from:r}=e;let i=""+t+s;s===(null==(s=ts.store.get("login"))?void 0:s.userId)&&(i=""+t+r),e=Object.assign({conversationType:t,conversationID:i},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=ts["notificationCenter"],e=e["InnerEventSubType"];ts.notificationCenter.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ts.notificationCenter.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ts.notificationCenter.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}class Uh{init(){var e=ts["notificationCenter"],t=e["InnerEventSubType"];ln.getInstance().registerWorkflowStep(Ds.RECEIVE_GROUP_NEW_MESSAGE,bs.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ln.getInstance().registerWorkflowStep(Ds.RECEIVE_GROUP_NEW_MESSAGE,bs.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&ln.getInstance().executeWorkflow(Ds.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=ts.message["messageDataHandler"],r=[],i=new Map,n=null==t?void 0:t.GroupMsgArray;return null!=n&&n.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):vh(e)&&s.storeConversationMessage(e)&&(r.push(e),_h({conversationUpdateFields:i,message:e})))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[bs.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&ts.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=qd.CONV_GROUP,e=dh(e),t=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Wd.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(i){var e;let t=(ts.message||{})["messageDataHandler"],s=null==(e=ts.store.get("login"))?void 0:e.userId,{from:r,nick:n,avatar:o,conversationID:a="",_elements:l}=i;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}else if(r===As.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=l,r={};if(ve(t)?ve(s)||(r=s):[ys.JOINED,ys.KICKED,ys.ADMIN_SET,ys.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!ve(r)){let{nick:e="",avatar:t=""}=r;i.nick=e,i.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Ph(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=qd.CONV_GROUP,{topicID:s,groupID:r}=e=ph(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=ts["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var{GroupId:e,GroupType:t}=(null==(e=null==(e=null==e?void 0:e.GroupMsgArray)?void 0:e[0])?void 0:e.GroupInfo)||{},t=t===Cs.GRP_AVCHATROOM;return!(!Nd.getGroup(e)&&t)}}var kh=new class{constructor(){this.c2cMessageReceiver=new Gh,this.groupMessageReceiver=new Uh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let Fh={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=>{return"string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(e=null==e?void 0:e.text)?void 0:e.length))||"payload.text must be a string"}}}},$h={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var qh=new class{getGroupRoamingMessagesByAnchor(i){return de(this,void 0,void 0,function*(){try{var{conversationID:t,count:s,direction:l,sequence:u,messageSequenceList:e,getType:r}=i,c=t.replace(Is.CONV_GROUP,""),d=[];let a=u;if(l===ps.BACKWARD){if("number"!=typeof u)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=u+s-1}var h=yield function(o){return de(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s,messageSequenceList:r,getType:i}=o,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1,GetType:i};return s&&(e.ReqMsgSeq=s),n(r)&&0<r.length&&(e.ReqMsgSeqList=r),yield mn({servcmd:"group_open_http_svc.group_msg_get",data:e})})}({groupID:c,count:s,messageSequence:a,messageSequenceList:e,getType:r});if(h){let{RspMsgList:s=[],NextReqMsgSeq:e=0,IsFinished:t,InvisibleMsgSeq:r}=h,i=`groupID:${c} sequence:${u} reqSeq:${a} direction:${l} complete:${t} nextSequence:${e} remoteMsgCount:${s.length} invisibleSequenceList:`+r,n=[];for(let t=0;t<s.length;t++){var g=s[t];g.From_Account===As.CONV_SYSTEM&&d.push(g);let e=this._parseMessage(g);n.push(e)}n.reverse();let o=t===Yd;l===ps.BACKWARD&&(o=n[n.length-1].sequence>=u);var p=mh(n);return ts.ssoLog.info("getGroupRoamingMessagesByAnchor",i),{messageList:p,invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,serverGroupTipList:d}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new Xs({code:t,message:s})}})}_parseMessage(e){var t=Is.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=As.MSG_GRP_TIP),dh(e)),t=eh.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class xh{constructor(){this.messageHelper=fh,this.messageFactory=eh,this.messageSender=new Dh,this.messageAction=new wh,this.messageReceiver=kh,this.messageDataHandler=Lh,this.messageHistory=qh,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),cn({auth:$h,params:Fh})}}let Vh="Tag_Profile_IM_",Bh={NICK:Vh+"Nick",GENDER:Vh+"Gender",BIRTHDAY:Vh+"BirthDay",LOCATION:Vh+"Location",SELFSIGNATURE:Vh+"SelfSignature",ALLOWTYPE:Vh+"AllowType",LANGUAGE:Vh+"Language",AVATAR:Vh+"Image",MESSAGESETTINGS:Vh+"MsgSettings",ADMINFORBIDTYPE:Vh+"AdminForbidType",LEVEL:Vh+"Level",ROLE:Vh+"Role"},jh="Tag_Profile_Custom",Kh="profileCustomField",Hh="USER_STATUS",Wh=1,Yh=1e3,zh={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:[]},Jh=new Map([[Bh.NICK,"nick"],[Bh.GENDER,"gender"],[Bh.BIRTHDAY,"birthday"],[Bh.LOCATION,"location"],[Bh.SELFSIGNATURE,"selfSignature"],[Bh.ALLOWTYPE,"allowType"],[Bh.LANGUAGE,"language"],[Bh.AVATAR,"avatar"],[Bh.MESSAGESETTINGS,"messageSettings"],[Bh.ADMINFORBIDTYPE,"adminForbidType"],[Bh.LEVEL,"level"],[Bh.ROLE,"role"]]);var pg,_g,mg,Qh=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(jh)?s.profileCustomField.push({key:e,value:t}):Jh.has(e)&&(s[Jh.get(e)]=t)}),Object.assign(Object.assign({},zh),s)}parseProfileItem(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.Value})}),t}parseProfileList(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.ValueBytes})}),t}convertParamsToProfile(t){let s=[];return Object.keys(t).forEach(e=>{e!==Kh&&s.push({tag:Bh[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&n(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let r={},i=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(jh)&&i.push({key:t,value:s}),Jh.has(t)&&void 0!==s){let e=Jh.get(t);r[e]=s}}),0<i.length&&(r.profileCustomField=i),r}};let Xh=ts.common["generateProtocolData"];function Zh(r){return de(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:En(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var n=Xh({servcmd:e,data:t}),s=n.head.seq+e,n=yield ts.channel.sendPacket(n,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:i}=n,o=[];return i.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:i,ProfileItem:n}=e,n=Qh.parseProfileItem(n);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:i,profileItem:n})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:o}}})}function eg(e){return Pd.getFriendMap().has(e)}let tg=ts.utils["isEmpty"];class sg{constructor(){this._strangerProfileMap=new Map}init(){Gd.getInstance().registerApi({apiName:"getMyProfile",context:this}),Gd.getInstance().registerApi({apiName:"getUserProfile",context:this}),Gd.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Qh.createProfile.bind(Qh);var e=ts["notificationCenter"];ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,bs.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}getMyProfile(){return de(this,void 0,void 0,function*(){try{var e,t=En(),s=yield Zh([t]);if(s)return e=this._handleProfileFormResponse(s)[0],Pd.getUserProfileMap().set(t,e),{code:0,data:e}}catch(e){var{errorCode:s,errorInfo:t}=e;throw new Xs({functionName:"getMyProfile",code:s,message:t})}})}getUserProfile(u){return de(this,void 0,void 0,function*(){try{var t=u["userIDList"],{userIdListToRequest:e,profileFromCache:s}=this._filterRequestAndCacheUsers(t);if(0===e.length)return{code:0,data:s,successLog:{message:"userIDList.length:"+t.length}};e.length>Yh&&(ts.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),e.length=Yh);var{data:r,error:i}=yield this._batchFetchUserProfiles(e),o=e.length,a=r.length,l=o-a;if(0===s.length&&o===l&&!tg(i))throw i;if(n(r)){r.forEach(e=>{(eg(e.userID)?Pd.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=r.concat(s);return{code:0,data:e,successLog:{message:`getUserProfile query:${o} success:${a} fail:${l} from cache:`+s.length}}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return de(this,void 0,void 0,function*(){var e=En(),e=Pd.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return de(this,void 0,void 0,function*(){let t=En(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);var r=Qh.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};yield function(r){return de(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Xh({servcmd:e,data:r}),s=""+t.head.seq+e,i=yield ts.channel.sendPacket(t,{requestId:s});if(i){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=i;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var i=Pd.getUserProfile(t),n=i?Object.assign(Object.assign({},i),s):Qh.createProfile(t,r),o=!ns(i,n,["lastUpdatedTime"]);return n.lastUpdatedTime=Date.now(),Pd.getUserProfileMap().set(t,n),o&&this._emitProfileUpdated(n),{code:0,data:n,successLog:{message:"profileArray: "+ts.utils.safeStringify(r)}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(i){return de(this,void 0,void 0,function*(){var e=En(),t=Date.now(),s=Pd.getUserProfile(e),r={};(r=s?Object.assign(s,i):Qh.createProfile(e,i)).lastUpdatedTime=t,Pd.getUserProfileMap().set(e,r)})}_onProfileDataModify(r){var e,t=function(){var{Profile_Account:e,PushType:t,ProfileList:s}=r.ProfileDataMod[0];return{userId:e,pushType:t,profileList:Qh.parseProfileList(s)}}();tg(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){ts.notificationCenter.emitInnerEvent(cs.PROFILE_UPDATE,{name:cs.PROFILE_UPDATE,data:[e]}),ts.notificationCenter.emitOuterEvent(rs.PROFILE_UPDATED,{name:rs.PROFILE_UPDATED,data:[e]}),bd.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=Pd.getUserProfile(t);if(!(En()===t||eg(t)&&r))return{isProfileUpdated:!1,profile:null};let i=Qh.normalizeProfileFields(s),n=Object.keys(i).some(e=>e===Kh?!ns(r.profileCustomField,i.profileCustomField):r[e]!==i[e]);return n?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),i),{lastUpdatedTime:e}),Pd.getUserProfileMap().set(t,e),{isProfileUpdated:n,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=Pd.getUserProfileMap().has(e);eg(e)&&t?r.push(Pd.getUserProfile(e)):this._isStrangerAndProfileValid(e)?r.push(this._strangerProfileMap.get(e)):s.push(e)}),{userIdListToRequest:s,profileFromCache:r}}_handleProfileFormResponse(e){e=e.userProfile;if(!Array.isArray(e))return[];let t=e.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!tg(e.profileItem)),s=Date.now();return t.map(e=>{e=Qh.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!eg(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=ts.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,r){return Array.from({length:Math.ceil(s.length/r)},(e,t)=>s.slice(t*r,(t+1)*r))}_batchFetchUserProfiles(e){return de(this,void 0,void 0,function*(){let t=[],r=[],i={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(Zh(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);n(t)&&r.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};i={errorCode:e,message:t}}}),{data:r,error:i}})}_reset(){Pd.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}let ng=new Map,og=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=og.length;e<t;e++)ng.set(e,og[e]);function ig(e){if(!e)return"";var i=String(e).replace(/[=]+$/,"");let n="";if(i.length%4==1)return"";for(let e,t,s=0,r=0;t=i.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(n+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}let rg=ts.utils["isEmpty"],ag=ts.common["generateProtocolData"];function cg(i){return de(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=ag({servcmd:s,data:{To_Account:i}}),s=r.head.seq+s,r=yield ts.channel.sendPacket(r,{requestId:s});if(r)return{ErrorCode:s,ErrorInfo:r,ErrorList:e=[],UserStatusList:t=[]}=r,{errorCode:s,errorInfo:r,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:ig(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:rg(t)?e:t,code:s,message:r}})}})}class ug{constructor(){this._customStatus=""}init(){var e=ts["notificationCenter"];Gd.getInstance().registerApi({apiName:"getUserStatus",context:this}),Gd.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Gd.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Gd.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}setSelfStatus(s){return de(this,void 0,void 0,function*(){let e=En(),t=s["customStatus"];try{return yield function(i){return de(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=ag({servcmd:e,data:{CustomStatus:i}}),s=""+t.head.seq+e,r=yield ts.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,{code:0,data:{userID:e,statusType:Wh,customStatus:t},successLog:{message:"customStatus: "+t}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(s){return de(this,void 0,void 0,function*(){var{userIDList:e=[]}=s;let t={};return this._isOnlyMeInArray(e)&&(t=this._getMyStatus()),t=yield this._getUserStatus(e),Object.assign(Object.assign({},t),{successLog:{message:"userIDList length: "+e.length}})})}setCustomStatus(e){e=ig(e);this._customStatus=e}subscribeUserStatus(i){return de(this,void 0,void 0,function*(){try{var{userIDList:e=[]}=i,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return de(this,void 0,void 0,function*(){var e=ts["channel"],t="im_open_status.ws_status_subscribe",s=ag({servcmd:t,data:{To_Account:r}}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(i){return de(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=i,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return de(this,void 0,void 0,function*(){var e=ts["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=ag({servcmd:t,data:s}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){var{UserStatusList:e=[]}=e||{},e=e.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:ig(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=ig(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:En(),statusType:Wh,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){ts.notificationCenter.emitOuterEvent(rs.USER_STATUS_UPDATED,{name:rs.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){var{ErrorList:e=[]}=e;return e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:ts.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!ts.store.get("commercialConfig").get(Hh))throw new Xs({functionName:e,code:Ts.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=ts.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:En(),statusType:Wh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return de(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");var t=this._getMaxUserCount("query"),{successUserList:e,failureUserList:s}=(yield cg(this._sliceUserIDList(r,t)))||{};return{code:0,data:{successUserList:e,failureUserList:s}}}catch(e){t=e["errorCode"];throw new Xs({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){var t=En();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let lg={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(var 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||!t.key.startsWith(jh))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}}},dg={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class hg{constructor(){this.userProfile=new sg,this.userStatus=new ug,this.userProfile.init(),this.userStatus.init(),cn({auth:dg,params:lg})}}function gg(s){var r=[];if(t(s)){var i=s.length;if(0!==i)for(let e=i-1;0<=e;e--)"1"===s[e]&&r.push(2**(i-e-1))}return r}!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(pg=pg||{}),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(_g=_g||{}),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(mg=mg||{});class vg{constructor(){this._name="SyncConversationHandler",this._pagingStatus=pg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=ts["notificationCenter"];ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.CONVERSATION_RECOVER,this._syncConversationList,this),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,bs.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this),ts.ssoLog.debug(this._name+".init")}isSyncCompleted(){return this._pagingStatus===pg.RESOLVED}_syncConversationListAfterLogin(){return de(this,void 0,void 0,function*(){return this._pagingStatus=pg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return de(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:s}}=ts;t.debug("_syncConversationList","start");try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=pg.RESOLVED;var{conversationList:r=[]}=e||{};return t.info("_syncConversationList","success count:"+r.length),e}catch(e){var{errorCode:r,errorInfo:i}=e,r=new Xs({code:r,message:i});t.error("_syncConversationList","fail "+s(e),{error:r})}})}_pagingGetConversationList(c){return de(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=pg.PENDING,yield function(n){return de(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:i}=n;return mn({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:i,TopTimeStamp:r}})})}({fromAccount:En(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:i=[],TimeStamp:n,StartIndex:o,TopTimeStamp:a,TopStartIndex:l}=s||{};if(0<i.length){let e=this._getConversationOptions(i);t.push(...e);var u=ts["notificationCenter"];u.emitInnerEvent(cs.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=n,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=l,1!==r&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){let{isUndefined:t}=ts["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===_g.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===_g.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(As.CONV_C2C)?e.replace(As.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+As.CONV_C2C+e.userID,type:As.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:null!=(t=e.lastMsg)&&t.elements[0]?null==(t=e.lastMsg)?void 0:t.elements[0].type:null,payload:null!=(t=e.lastMsg)&&t.elements[0]?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===mg.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null==(t=null==(t=e.lastMsg)?void 0:t.revokerInfo)?void 0:t.revoker)||null},unreadCount:0,userProfile:s,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:gg(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var{userID:e,nick:t,peerAvatar:s}=e,t=[{tag:"Tag_Profile_IM_Nick",value:t},{tag:"Tag_Profile_IM_Image",value:s}];return null==(s=ts.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===En()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+As.CONV_GROUP+e.groupID,type:As.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===mg.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null==(t=null==(t=e.lastMsg)?void 0:t.revokerInfo)?void 0:t.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:gg(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(s){var e,t,r=ts["utils"]["isEmpty"];if(r(s))return null;let i="",n=null;if(!r(s.GroupTips)){let{From_Account:e,GroupName:t}=(null==(r=s.GroupTips)?void 0:r.GroupInfo)||{};i=As.MSG_GRP_TIP,n=Object.assign(Object.assign({},this._parseContent(i,s.GroupTips.MsgBody)),{groupProfile:{from:e,groupName:t}})}return s.MsgBody&&(i=null==(e=s.MsgBody[0])?void 0:e.MsgType,n=this._parseContent(i,s.MsgBody[0])),{event:s.Event,elements:[{type:i,content:n,cloudCustomData:s.CloudCustomData}],revokerInfo:{revoker:null==(t=s.RevokerInfo)?void 0:t.Revoker_Account}}}_parseContent(e,t){return t&&((e=ts.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return le(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=As.MSG_REMIND_ACPT_AND_NOTE:1===e?t=As.MSG_REMIND_DISCARD:2===e?t=As.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=As.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=ts["utils"]["isUndefined"],{event:e,elements:s=[]}=e.lastMsg||{};return t(e)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:As.MSG_GRP_TIP,payload:(null==(t=null==s?void 0:s[0])?void 0:t.content)||{}}}_computeGroupUnreadCount(e){var{unreadCount:e=0,noUnreadCount:t=0}=e,e=e-t;return 0<e?e:0}_reset(){this._pagingStatus=pg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=ts["notificationCenter"];e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}class fg{constructor(){this.syncConversationHandler=new vg,this.syncConversationHandler.init()}}ts.ssoLog.debug("TencentCloudLiteChat.VERSION:"+it);var Ig={create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:i="",oversea:n=!1,instance:o,disableIndependentDomain:a=!1}=e,l=e;if("number"!=typeof l&&(e=Number(l),Number.isNaN(e)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(l=Number(l),dn.has(l))return dn.get(l);let u=null;if(o)(u=o)._workflowManager&&ln.setInstance(u._workflowManager),u._pluginManager&&u._pluginManager.installBuiltInPlugin(Td),!o.isReady()||null!=(o=(e=ln.getInstance()).executeWorkflow)&&o.call(e,Ds.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(c()+c())+c()+c()+c()+c()+c()+c();ts.init({sdkAppId:l,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:r,disableIndependentDomain:a,scene:i,oversea:n,sdkEdition:Ad}),ln.getInstance().init(),ts.message=new xh,ts.user=new hg,ts.login=new $d,ts.conversation=new fg,Dd.getInstance().installBuiltInPlugin(Td),(u=Gd.getInstance().exposeApiForClient())._workflowManager=ln.getInstance(),u._pluginManager=Dd.getInstance()}function c(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return dn.set(l,u),u},TSignaling:us,EVENT:rs,VERSION:it,TYPES:As};export{Ig as default};