@tencentcloud/lite-chat 1.4.2 → 1.5.1

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.js CHANGED
@@ -1 +1,5 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChat=t()}(this,(function(){"use strict";class e{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,t,s){var n;t&&(this.listeners[e]=null===(n=this.listeners[e])||void 0===n?void 0:n.filter((e=>{const n=e.fn===t,o=!s||e.context===s;return!(n&&o)})))}emit(e,...t){const s=this.listeners[e];s&&s.forEach((e=>{const{fn:s,context:n}=e;s.apply(n,t)}))}once(e,t,s){const n=(...o)=>{t.apply(s,o),this.off(e,n)};this.on(e,n)}}const t={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},s=["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 n;!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"}(n||(n={}));var o,i=Object.freeze({__proto__:null,get ConvModifyPushType(){return n},ENUM_PLATFORM:t,IS_TOPIC_MESSAGE:2,NOT_NEED_CRC_SERVCMD:s});function r(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach((e=>{2===e.GroupInfo.MillionGroupFlag?s.push(o.TOPIC_TIPS_NOTIFICATION):s.push(o.GROUP_TIPS_NOTIFICATION)})),s}!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"}(o||(o={}));const a=[{conditions:[{type:"event",value:100}],subType:o.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:o.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:o.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:o.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:o.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:o.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:o.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:o.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:o.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:o.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.C2cNotifyMsgArray)||void 0===t||t.forEach((e=>{e.WithdrawC2cMsgNotify&&s.push(o.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(o.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(o.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(o.C2C_REMIND_TYPE_SYNC)})),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:r},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach((e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(o.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(o.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(o.TOPIC_MESSAGE_READ_SYNC):s.push(o.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(o.TOPIC_SYSTEM_NOTIFICATION):s.push(o.GROUP_SYSTEM_NOTIFICATION)})),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:r},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach((e=>{const{GroupAtTips:{TopicId:t}}=e;t?s.push(o.TOPIC_AT_TIPS):s.push(o.GROUP_AT_TIPS)})),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach((e=>{switch(e.PushType){case n.CONV_MARK_UPDATED:s.push(o.CONVERSATION_MARK_UPDATED);break;case n.CONV_GROUP_ADDED:s.push(o.CONVERSATION_GROUP_ADD);break;case n.CONV_GROUP_DELETED:s.push(o.CONVERSATION_GROUP_DELETED);break;case n.CONV_GROUP_UPDATED:s.push(o.CONVERSATION_GROUP_UPDATED);break;default:s.push(o.CONV_MODIFIED)}})),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:o.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:o.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:o.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:o.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:o.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:o.ALL_MESSAGE_READ}];var c;function u(e){var t;const s=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],n=[];return s.forEach((t=>{t.Flag=e.body.Flag;const s=a.find((e=>e.conditions.every((e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}))));if(!s)return null;let o=[];"function"==typeof s.subTypeParser?o=s.subTypeParser(t):s.subType&&(o=s.subType),Array.isArray(o)?o.forEach((e=>{n.push({type:`${c.SERVER_PUSH_MESSAGE}:${e}`,data:t})})):n.push({type:`${c.SERVER_PUSH_MESSAGE}:${o}`,data:t})})),n}!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",e.ERROR="error"}(c||(c={}));const l={[c.SERVER_PUSH_MESSAGE]:u,[c.SERVER_PUSH_MESSAGE_MULTIPLE]:u,[c.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const d=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=o}subscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.on(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.on(e,n,s)}}emitInnerEvent(e,t){var s,n;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(l).includes(e)){const s=null===(n=l[e])||void 0===n?void 0:n.call(l,t);null==s||s.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.off(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.off(e,n,s)}}subscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.off(e,t,s)}emitOuterEvent(e,t){var s;null===(s=this._outerEventEmitter)||void 0===s||s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function h(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}function g(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const p=e=>void 0===e,_=e=>"string"==typeof e,m=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},v=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===m(e),f=e=>null!==e&&"object"==typeof e,I=e=>v(e)||f(e),S=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},E=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function C(e=99999999){return Math.round(Math.random()*e)}const M=(e,t,s,n)=>{if(!I(e)||!I(t))return 0;let o=0;const i=Object.keys(t);let r;for(let a=0,c=i.length;a<c;a++)if(r=i[a],!(p(t[r])||s&&s.includes(r)))if(I(e[r])&&I(t[r]))o+=M(e[r],t[r],s,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],o+=1)}return o};function y(e){let t,s,n=e;e.length%8!=0&&(n="0".repeat(8-e.length%8)+e);let o="";for(let e=0,{length:i}=n;e<i;e+=8)t=parseInt(n.slice(e,e+4),2),s=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(t)+base16Map.get(s);return o}const O="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),A="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||O,T=A&&"function"==typeof wx.createGamePortal,R="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),D="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),b="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),L="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,P="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,G=A&&"object"==typeof wx.miniapp,w="undefined"!=typeof uni,U=A||R||D||b||L||P||N,k="undefined"==typeof window&&!U&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,F="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),$="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),x="undefined"!=typeof uni?!U:"undefined"!=typeof window&&!U&&!F,q=R?qq:D?tt:b?swan:L?my:A?wx:P?uni:N?jd:{},V=x&&window&&window.navigator&&window.navigator.userAgent||"",B=/(micromessenger|webbrowser)/i.test(V),j=function(){let e="WEB";return B?e="WEB":R?e="QQ_MP":D?e="TT_MP":b?e="BAIDU_MP":L?e="ALI_MP":A?e=G?"DONUT_NATIVE_APP":"WX_MP":P?e="UNI_NATIVE_APP":k?e="NS_NATIVE_APP":F&&(e="RN_NATIVE_APP"),t[e]}(),K=/iPad/i.test(V),H=/iPhone/i.test(V)&&!K,W=/iPod/i.test(V),Y=H||K||W,z=function(){const e=V.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),J=/Android/i.test(V),Q=function(){const e=V.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),s=e[2]&&parseFloat(e[2]);return t&&s?parseFloat(`${e[1]}.${e[2]}`):t||null}(),X=/Firefox/i.test(V),Z=/Edge/i.test(V),ee=!Z&&/Chrome/i.test(V),te=/MSIE/.test(V)||V.indexOf("Trident")>-1&&V.indexOf("rv:11.0")>-1,se=function(){const e=/MSIE\s(\d+)\.\d/.exec(V);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(V)&&/rv:11.0/.test(V)&&(t=11),t}(),ne=/Safari/i.test(V)&&!ee&&!J&&!Z,oe=/Windows/i.test(V),ie=/MAC OS X/i.test(V),re=x&&"undefined"!=typeof Worker&&!te,ae=J||Y,ce=x&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ue=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!Y||e||ne)}();function le(){let e="unknown";if(ie&&(e="mac"),oe&&(e="windows"),Y&&(e="ios"),J&&(e="android"),U)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const de=2800,he=2801,ge=3e3,pe="application/x-www-form-urlencoded;charset=UTF-8";function _e(e){return g(this,arguments,void 0,(function*({method:e,url:t,data:s,timeout:n=ge}){return new Promise(U?(o,i)=>{q.request({url:t,data:s,method:e,timeout:n,header:{"content-type":pe},success:e=>o(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${de}}`))})}:(o,i)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${he}}`))}),n);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{o(r.responseText?JSON.parse(r.responseText):null)}catch(e){o(r.responseText)}else i(new Error(`{"message":"Network error","code":${de}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",pe),r.send(s||null)})}))}function me(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(E(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return("[object Map]"===Object.prototype.toString.call(e)||"[object Set]"===Object.prototype.toString.call(e)||"[object File]"===Object.prototype.toString.call(e))&&0===e.size}function ve(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const t=new Map;return e.forEach(((e,s)=>{t.set(ve(s),ve(e))})),t}if(e instanceof Set){const t=new Set;return e.forEach((e=>{t.add(ve(e))})),t}if(Array.isArray(e))return e.map((e=>ve(e)));const t=Object.getPrototypeOf(e),s=Object.create(t);return[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach((t=>{const n=Object.getOwnPropertyDescriptor(e,t);n&&(n.get||n.set?Object.defineProperty(s,t,n):s[t]=ve(e[t]))})),s}function fe(){let e,t;return{promise:new Promise(((s,n)=>{e=s,t=n})),resolve:e,reject:t}}var Ie=Object.freeze({__proto__:null,ANDROID_VERSION:Q,IE_VERSION:se,IN_ALIPAY_MINI_APP:L,IN_BAIDU_MINI_APP:b,IN_BROWSER:x,IN_DONUT_NATIVE_APP:G,IN_JD_MINI_APP:N,IN_MINI_APP:U,IN_NS_NATIVE_APP:k,IN_QQ_MINI_APP:R,IN_RN_APP:F,IN_TT_MINI_APP:D,IN_UNI_APP:w,IN_UNI_NATIVE_APP:P,IN_WX_MINI_APP:A,IN_WX_MINI_APP_DESK:O,IN_WX_MINI_GAME:T,IN_WX_MINI_PLUGIN:$,IOS_VERSION:z,IS_ANDROID:J,IS_CHROME:ee,IS_EDGE:Z,IS_FIREFOX:X,IS_IE:te,IS_IOS:Y,IS_IPAD:K,IS_IPHONE:H,IS_IPOD:W,IS_MAC:ie,IS_SAFARI:ne,IS_WECHAT:B,IS_WIN:oe,IS_WORKER_AVAILABLE:re,MINI_APP_NAMESPACE:q,USER_AGENT:V,base16EncodeBinaryString:y,deepCopyWithMethods:ve,deepMerge:M,generatePromise:fe,getPlatformType:le,getType:m,httpRequest:_e,isArray:v,isArrayOrObject:I,isEmpty:me,isFlutterWeb:ce,isH5:ae,isIOSWebView:ue,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:f,isPlainObject:E,isString:_,isUndefined:p,isValidRequestKey:S,platform:j,randomInt:C,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let s=32;s>0;--s)t+=e[Math.floor(62*Math.random())];return t}});class Se{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,s;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=n,this._socket.onerror=o,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Ee{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket.onClose(n),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(o),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Ce="CONNECT",Me="SEND",ye="DISCONNECT",Oe="OPEN",Ae="MESSAGE",Te="CLOSE",Re="ERROR",De="SEND_FAIL";class be{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){const t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:Ce,url:e})}send(e){var t,s;try{null===(t=this._worker)||void 0===t||t.postMessage({type:Me,data:e})}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;if(this._worker){const e={[Oe]:t,[Ae]:s,[Te]:n,[Re]:o,[De]:i};this._onSendFail=i,this._worker.onmessage=t=>{var s;const{type:n}=(null==t?void 0:t.data)||{};"function"==typeof e[n]&&(null===(s=e[n])||void 0===s||s.call(e,null==t?void 0:t.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:ye}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Le,Ne=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(U){if(L){return my.getStorageSync({key:e}).data}return q.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){U?L?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"}(Le||(Le={}));class Pe{constructor(t){this._url="",this._readyState=Le.DISCONNECTED,this._url=t,this._id=C(),this._emitter=new e,A?this._socket=new Ee:this._canUseWebWorker()?this._socket=new be:this._socket=new Se,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Le.CONNECTED,Le.CONNECTING].includes(this._readyState)||(this._readyState=Le.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Le.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Le.CONNECTED,Le.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===Le.CONNECTED}disconnect(){this._readyState=Le.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Le.CONNECTING&&(this._readyState=Le.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Le.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Le.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Le.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const e=Ne.get("cloudConfig")||{};return(p(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&re}}const Ge="CHINA",we="OVERSEA",Ue="SINGAPORE",ke="KOREA",Fe="GERMANY",$e="IND",xe="JPN",qe="USA",Ve="INDONESIA",Be={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",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",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",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",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",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",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",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",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",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},je={[Ue]:[[2e7,3e7],[172e7,173e7]],[ke]:[[3e7,4e7],[173e7,174e7]],[Fe]:[[4e7,5e7],[174e7,175e7]],[$e]:[[5e7,6e7],[175e7,176e7]],[xe]:[[6e7,7e7],[176e7,177e7]],[qe]:[[7e7,8e7],[177e7,178e7]],[Ve]:[[8e7,9e7],[178e7,179e7]]};function Ke(e){var t;if(null===(t=Ne.get("instance"))||void 0===t?void 0:t.oversea)return we;for(const t of Object.keys(je))for(const[s,n]of je[t])if(e>=s&&e<n)return t;return Ge}var He,We="1.4.2";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST",e.IPV6="IPV6"}(He||(He={}));let Ye=He.INITIAL;function ze(){const e=Math.random();return 0===e?ze():e}function Je(e,t){const{isBinary:s=!1}=t||{},n=Ne.get("instance"),{sdkAppId:o,instanceId:i}=n,r=ze(),a=le(),c=function(){const e=le();let t=-1;"ios"===e?t=z||-1:"android"===e&&(t=Q||-1);return t}(),u=(l={sdkappid:o,instanceid:i,random:r,platform:j,host:a,version:c,sdkversion:We},Object.keys(l).map((e=>`${e}=${l[e]}`)).join("&"));var l;return s?`${e}/binfo?${u}&compress=gzip`:`${e}/info?${u}`}var Qe=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const s=Date.now(),n=s-e;this._timeOffsetWithServer=t+n-s}};const Xe=16;var Ze=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:s,context:n,isOnce:o=!1,intervalMs:i=Xe}=e,r=Math.max(i,Xe);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:n,isOnce:o}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const s=this._taskMap.get(e);s&&(s.intervalMs=t,s.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function et(e){const t=[];for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n>=55296&&n<=56319){const o=e.charCodeAt(++s)-56320+(n-55296<<10)+65536;t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}else n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function st(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&S(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=st(e[s]));return t}function nt(e,t){if(s.includes(e))return 0;const n=et(JSON.stringify(t));let o=4294967295;const{length:i}=n;for(let e=0;e<i;e++){o^=n[e];for(let e=0;e<8;e++)1&~o?o>>>=1:o=o>>>1^3988292384}return(4294967295^o)>>>0}function ot(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ne.get("login")||{},s=Ne.get("instance")||{};return{servcmd:e,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,tjgID:"",seq:at(),cs:0}}(t),o=st(s);return n.cs=nt(t,o),{head:n,body:o}}function it(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ne.get("login")||{},s=Ne.get("instance")||{};return{servcmd:e,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:at(),cs:0}}(t),o=st(s);return n.cs=nt(t,o),{head:n,body:o}}let rt=C();function at(){return rt=rt<2415919103?rt+1:C(),rt}function ct(){const e=Ne.get("login")||{},t=Ne.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.4.2",tiny_id:Number(e.tinyID),user_id:e.userId,platform:j,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var ut,lt=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ne.get("login")||{},s=Ne.get("instance")||{};return{servcmd:e,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:at(),cs:0}}(t),o=st(s);return n.cs=nt(t,o),{head:n,body:o}},generateProtocolData:ot,generateSSOLogProtocolData:it,generateSequence:at,getCommonHead:ct,taskScheduler:Ze,timeManager:Qe});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(ut||(ut={}));const dt={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 ht{constructor(e){this.level=ut.info,this._canSendLog=!0,this._logCreatedAt=Qe.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=void 0;const{method:t,eventType:s=0,uiPlatform:n,message:o}=e||{};this.eventType=s,this.method=t,this.uiPlatform=n,this.message=o||""}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Qe.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Qe.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Qe.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Qe.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())}),0)}setError(e){var t;if(!(e instanceof Error))return console.warn("SSOLogData.setError value not instanceof Error, please check!"),this;if(!this._canSendLog)return this;return(null===(t=Ne.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=ut.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(dt).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const s=t;dt[s]&&(e[dt[s]]=this[s])})),e}}var gt;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(gt||(gt={}));var pt=gt;const _t=20,mt=6e4,vt=[4,5,6],ft=[],It=[],St="report-logger";var Et=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=_t,this._maxThreshold=100,this._waitingTime=mt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,d.subscribeInnerEvent(pt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Ze.addTask({id:St,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=_t,evt_rpt_waiting:s=mt,evt_rpt_level:n=vt,evt_rpt_sdkappid_bl:o=ft,evt_rpt_tinyid_wl:i=It}=e||{};this._sdkAppIdBlackList=o,this._waitingTime=s,this._minThreshold=t,this._reportLevel=n,this._tinyIdWhiteList=i}createSSOLogData(e){const t=new ht(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())}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return g(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const s={Header:ct(),Event:t};me(s.Header.user_id)||(yield function(e){const t="imopenstat.tim_web_report_v2",s=it({servcmd:t,data:e}),n=`${s.head.seq}${t}`;qt.sendPacket(s,{requestId:n})}(s)),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(A){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;Ne.set("instance",{appId:e,envVersion:t})}}else x&&Ne.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Ne.get("login")||{},{sdkAppId:s}=Ne.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),Ze.removeTask(St),d.unSubscribeInnerEvent(pt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=_t,this._maxThreshold=100,this._waitingTime=mt,this._logQueue=[]}};const Ct=15e3,Mt="Channel",yt="channel_schedule_task",Ot="channel_reconnect_task",At="connected",Tt="connecting",Rt="disconnected",Dt=1e3,bt="network_status_change",Lt="activity_status_change",Nt="send_fail",Pt="reconnect_failed",Gt="socket_error",wt="socket_close";function Ut(e){return Ut="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},Ut(e)}function kt(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 Ft,$t={exports:{}};var xt=(Ft||(Ft=1,function(e){e.exports=function e(t,s,n){function o(r,a){if(!s[r]){if(!t[r]){if(!a&&kt)return kt(r);if(i)return i(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=s[r]={exports:{}};t[r][0].call(u.exports,(function(e){return o(t[r][1][e]||e)}),u,u.exports,e,t,s,n)}return s[r].exports}for(var i=kt,r=0;r<n.length;r++)o(n[r]);return o}({1:[function(e,t,s){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t,s,n=Array.prototype.slice.call(arguments,1);n.length;){var o=n.shift();if(o){if("object"!=Ut(o))throw new TypeError(o+"must be non-object");for(var i in o)t=o,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=o[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,s,n,o){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+n),o);else for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){var t,s,n,o,i,r;for(t=n=0,s=e.length;t<s;t++)n+=e[t].length;for(r=new Uint8Array(n),t=o=0,s=e.length;t<s;t++)i=e[t],r.set(i,o),o+=i.length;return r}},i={arraySet:function(e,t,s,n,o){for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,o)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(n)},{}],2:[function(e,t,s){var n=e("./common"),o=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var r=new n.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&o))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}r[254]=r[254]=1,s.string2buf=function(e){var t,s,o,i,r,a=e.length,c=0;for(i=0;i<a;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),c+=s<128?1:s<2048?2:s<65536?3:4;for(t=new n.Buf8(c),i=r=0;r<c;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),s<128?t[r++]=s:(s<2048?t[r++]=192|s>>>6:(s<65536?t[r++]=224|s>>>12:(t[r++]=240|s>>>18,t[r++]=128|s>>>12&63),t[r++]=128|s>>>6&63),t[r++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new n.Buf8(e.length),s=0,o=t.length;s<o;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,n,o,i,a=t||e.length,u=new Array(2*a);for(s=n=0;s<a;)if((o=e[s++])<128)u[n++]=o;else if(4<(i=r[o]))u[n++]=65533,s+=i-1;else{for(o&=2===i?31:3===i?15:7;1<i&&s<a;)o=o<<6|63&e[s++],i--;1<i?u[n++]=65533:o<65536?u[n++]=o:(o-=65536,u[n++]=55296|o>>10&1023,u[n++]=56320|1023&o)}return c(u,n)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+r[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,n){for(var o=65535&e,i=e>>>16&65535,r=0;0!==s;){for(s-=r=2e3<s?2e3:s;i=i+(o=o+t[n++]|0)|0,--r;);o%=65521,i%=65521}return o|i<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var n=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,o){var i=n,r=o+s;e^=-1;for(var a=o;a<r;a++)e=e>>>8^i[255&(e^t[a])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,n,o,i,r,a,c,u,l,d,h,g,p,_,m,v,f,I,S,E,C,M,y,O,A;s=e.state,n=e.next_in,O=e.input,o=n+(e.avail_in-5),i=e.next_out,A=e.output,r=i-(t-e.avail_out),a=i+(e.avail_out-257),c=s.dmax,u=s.wsize,l=s.whave,d=s.wnext,h=s.window,g=s.hold,p=s.bits,_=s.lencode,m=s.distcode,v=(1<<s.lenbits)-1,f=(1<<s.distbits)-1;e:do{p<15&&(g+=O[n++]<<p,p+=8,g+=O[n++]<<p,p+=8),I=_[g&v];t:for(;;){if(g>>>=S=I>>>24,p-=S,0==(S=I>>>16&255))A[i++]=65535&I;else{if(!(16&S)){if(!(64&S)){I=_[(65535&I)+(g&(1<<S)-1)];continue t}if(32&S){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}E=65535&I,(S&=15)&&(p<S&&(g+=O[n++]<<p,p+=8),E+=g&(1<<S)-1,g>>>=S,p-=S),p<15&&(g+=O[n++]<<p,p+=8,g+=O[n++]<<p,p+=8),I=m[g&f];s:for(;;){if(g>>>=S=I>>>24,p-=S,!(16&(S=I>>>16&255))){if(!(64&S)){I=m[(65535&I)+(g&(1<<S)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(C=65535&I,p<(S&=15)&&(g+=O[n++]<<p,(p+=8)<S&&(g+=O[n++]<<p,p+=8)),c<(C+=g&(1<<S)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(g>>>=S,p-=S,(S=i-r)<C){if(l<(S=C-S)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(y=h,(M=0)===d){if(M+=u-S,S<E){for(E-=S;A[i++]=h[M++],--S;);M=i-C,y=A}}else if(d<S){if(M+=u+d-S,(S-=d)<E){for(E-=S;A[i++]=h[M++],--S;);if(M=0,d<E){for(E-=S=d;A[i++]=h[M++],--S;);M=i-C,y=A}}}else if(M+=d-S,S<E){for(E-=S;A[i++]=h[M++],--S;);M=i-C,y=A}for(;2<E;)A[i++]=y[M++],A[i++]=y[M++],A[i++]=y[M++],E-=3;E&&(A[i++]=y[M++],1<E&&(A[i++]=y[M++]))}else{for(M=i-C;A[i++]=A[M++],A[i++]=A[M++],A[i++]=A[M++],2<(E-=3););E&&(A[i++]=A[M++],1<E&&(A[i++]=A[M++]))}break}}break}}while(n<o&&i<a);n-=E=p>>3,g&=(1<<(p-=E<<3))-1,e.next_in=n,e.next_out=i,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=i<a?a-i+257:257-(i-a),s.hold=g,s.bits=p}},{}],8:[function(e,t,s){var n=e("../utils/common"),o=e("./adler32"),i=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,u=2,l=0,d=-2,h=1,g=852,p=592;function _(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(g),t.distcode=t.distdyn=new n.Buf32(p),t.sane=1,t.back=-1,l):d}function f(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,v(e)):d}function I(e,t){var s,n;return e&&e.state?(n=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?d:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=s,n.wbits=t,f(e))):d}function S(e,t){var s,n;return e?(n=new m,(e.state=n).window=null,(s=I(e,t))!==l&&(e.state=null),s):d}var E,C,M=!0;function y(e){if(M){var t;for(E=new n.Buf32(512),C=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,E,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(u,e.lens,0,32,C,0,e.work,{bits:5}),M=!1}e.lencode=E,e.lenbits=9,e.distcode=C,e.distbits=5}function O(e,t,s,o){var i,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new n.Buf8(r.wsize)),o>=r.wsize?(n.arraySet(r.window,t,s-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(o<(i=r.wsize-r.wnext)&&(i=o),n.arraySet(r.window,t,s-o,i,r.wnext),(o-=i)?(n.arraySet(r.window,t,s-o,o,0),r.wnext=o,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}s.inflateReset=f,s.inflateReset2=I,s.inflateResetKeep=v,s.inflateInit=function(e){return S(e,15)},s.inflateInit2=S,s.inflate=function(e,t){var s,g,p,m,v,f,I,S,E,C,M,A,T,R,D,b,L,N,P,G,w,U,k,F,$=0,x=new n.Buf8(4),q=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;12===(s=e.state).mode&&(s.mode=13),v=e.next_out,p=e.output,I=e.avail_out,m=e.next_in,g=e.input,f=e.avail_in,S=s.hold,E=s.bits,C=f,M=I,U=l;e:for(;;)switch(s.mode){case h:if(0===s.wrap){s.mode=13;break}for(;E<16;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(2&s.wrap&&35615===S){x[s.check=0]=255&S,x[1]=S>>>8&255,s.check=i(s.check,x,2,0),E=S=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&S)<<8)+(S>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&S)){e.msg="unknown compression method",s.mode=30;break}if(E-=4,w=8+(15&(S>>>=4)),0===s.wbits)s.wbits=w;else if(w>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<w,e.adler=s.check=1,s.mode=512&S?10:12,E=S=0;break;case 2:for(;E<16;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(s.flags=S,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=S>>8&1),512&s.flags&&(x[0]=255&S,x[1]=S>>>8&255,s.check=i(s.check,x,2,0)),E=S=0,s.mode=3;case 3:for(;E<32;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}s.head&&(s.head.time=S),512&s.flags&&(x[0]=255&S,x[1]=S>>>8&255,x[2]=S>>>16&255,x[3]=S>>>24&255,s.check=i(s.check,x,4,0)),E=S=0,s.mode=4;case 4:for(;E<16;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}s.head&&(s.head.xflags=255&S,s.head.os=S>>8),512&s.flags&&(x[0]=255&S,x[1]=S>>>8&255,s.check=i(s.check,x,2,0)),E=S=0,s.mode=5;case 5:if(1024&s.flags){for(;E<16;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}s.length=S,s.head&&(s.head.extra_len=S),512&s.flags&&(x[0]=255&S,x[1]=S>>>8&255,s.check=i(s.check,x,2,0)),E=S=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(f<(A=s.length)&&(A=f),A&&(s.head&&(w=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),n.arraySet(s.head.extra,g,m,A,w)),512&s.flags&&(s.check=i(s.check,g,A,m)),f-=A,m+=A,s.length-=A),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===f)break e;for(A=0;w=g[m+A++],s.head&&w&&s.length<65536&&(s.head.name+=String.fromCharCode(w)),w&&A<f;);if(512&s.flags&&(s.check=i(s.check,g,A,m)),f-=A,m+=A,w)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===f)break e;for(A=0;w=g[m+A++],s.head&&w&&s.length<65536&&(s.head.comment+=String.fromCharCode(w)),w&&A<f;);if(512&s.flags&&(s.check=i(s.check,g,A,m)),f-=A,m+=A,w)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;E<16;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(S!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}E=S=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(;E<32;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}e.adler=s.check=_(S),E=S=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=S,s.bits=E,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){S>>>=7&E,E-=7&E,s.mode=27;break}for(;E<3;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}switch(s.last=1&S,E-=1,3&(S>>>=1)){case 0:s.mode=14;break;case 1:if(y(s),s.mode=20,6!==t)break;S>>>=2,E-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}S>>>=2,E-=2;break;case 14:for(S>>>=7&E,E-=7&E;E<32;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if((65535&S)!=(S>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&S,E=S=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(A=s.length){if(f<A&&(A=f),I<A&&(A=I),0===A)break e;n.arraySet(p,g,m,A,v),f-=A,m+=A,I-=A,v+=A,s.length-=A;break}s.mode=12;break;case 17:for(;E<14;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(s.nlen=257+(31&S),S>>>=5,E-=5,s.ndist=1+(31&S),S>>>=5,E-=5,s.ncode=4+(15&S),S>>>=4,E-=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(;E<3;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}s.lens[q[s.have++]]=7&S,S>>>=3,E-=3}for(;s.have<19;)s.lens[q[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,k={bits:s.lenbits},U=a(0,s.lens,0,19,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;b=($=s.lencode[S&(1<<s.lenbits)-1])>>>16&255,L=65535&$,!((D=$>>>24)<=E);){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(L<16)S>>>=D,E-=D,s.lens[s.have++]=L;else{if(16===L){for(F=D+2;E<F;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(S>>>=D,E-=D,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}w=s.lens[s.have-1],A=3+(3&S),S>>>=2,E-=2}else if(17===L){for(F=D+3;E<F;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}E-=D,w=0,A=3+(7&(S>>>=D)),S>>>=3,E-=3}else{for(F=D+7;E<F;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}E-=D,w=0,A=11+(127&(S>>>=D)),S>>>=7,E-=7}if(s.have+A>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;A--;)s.lens[s.have++]=w}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,k={bits:s.lenbits},U=a(c,s.lens,0,s.nlen,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,k={bits:s.distbits},U=a(u,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,k),s.distbits=k.bits,U){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=f&&258<=I){e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=S,s.bits=E,r(e,M),v=e.next_out,p=e.output,I=e.avail_out,m=e.next_in,g=e.input,f=e.avail_in,S=s.hold,E=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;b=($=s.lencode[S&(1<<s.lenbits)-1])>>>16&255,L=65535&$,!((D=$>>>24)<=E);){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(b&&!(240&b)){for(N=D,P=b,G=L;b=($=s.lencode[G+((S&(1<<N+P)-1)>>N)])>>>16&255,L=65535&$,!(N+(D=$>>>24)<=E);){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}S>>>=N,E-=N,s.back+=N}if(S>>>=D,E-=D,s.back+=D,s.length=L,0===b){s.mode=26;break}if(32&b){s.back=-1,s.mode=12;break}if(64&b){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&b,s.mode=22;case 22:if(s.extra){for(F=s.extra;E<F;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}s.length+=S&(1<<s.extra)-1,S>>>=s.extra,E-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;b=($=s.distcode[S&(1<<s.distbits)-1])>>>16&255,L=65535&$,!((D=$>>>24)<=E);){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(!(240&b)){for(N=D,P=b,G=L;b=($=s.distcode[G+((S&(1<<N+P)-1)>>N)])>>>16&255,L=65535&$,!(N+(D=$>>>24)<=E);){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}S>>>=N,E-=N,s.back+=N}if(S>>>=D,E-=D,s.back+=D,64&b){e.msg="invalid distance code",s.mode=30;break}s.offset=L,s.extra=15&b,s.mode=24;case 24:if(s.extra){for(F=s.extra;E<F;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}s.offset+=S&(1<<s.extra)-1,S>>>=s.extra,E-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===I)break e;if(A=M-I,s.offset>A){if((A=s.offset-A)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}A>s.wnext?(A-=s.wnext,T=s.wsize-A):T=s.wnext-A,A>s.length&&(A=s.length),R=s.window}else R=p,T=v-s.offset,A=s.length;for(I<A&&(A=I),I-=A,s.length-=A;p[v++]=R[T++],--A;);0===s.length&&(s.mode=21);break;case 26:if(0===I)break e;p[v++]=s.length,I--,s.mode=21;break;case 27:if(s.wrap){for(;E<32;){if(0===f)break e;f--,S|=g[m++]<<E,E+=8}if(M-=I,e.total_out+=M,s.total+=M,M&&(e.adler=s.check=s.flags?i(s.check,p,M,v-M):o(s.check,p,M,v-M)),M=I,(s.flags?S:_(S))!==s.check){e.msg="incorrect data check",s.mode=30;break}E=S=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;E<32;){if(0===f)break e;f--,S+=g[m++]<<E,E+=8}if(S!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}E=S=0}s.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return d}return e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=S,s.bits=E,(s.wsize||M!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&O(e,e.output,e.next_out,M-e.avail_out)?(s.mode=31,-4):(C-=e.avail_in,M-=e.avail_out,e.total_in+=C,e.total_out+=M,s.total+=M,s.wrap&&M&&(e.adler=s.check=s.flags?i(s.check,p,M,e.next_out-M):o(s.check,p,M,e.next_out-M)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0===C&&0===M||4===t)&&U===l&&(U=-5),U)},s.inflateEnd=function(e){if(!e||!e.state)return d;var t=e.state;return t.window&&(t.window=null),e.state=null,l},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,l):d},s.inflateSetDictionary=function(e,t){var s,n=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?d:11===s.mode&&o(1,t,n,0)!==s.check?-3:O(e,t,n,n)?(s.mode=31,-4):(s.havedict=1,l):d},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var n=e("../utils/common"),o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,c,u,l,d,h){var g,p,_,m,v,f,I,S,E,C=h.bits,M=0,y=0,O=0,A=0,T=0,R=0,D=0,b=0,L=0,N=0,P=null,G=0,w=new n.Buf16(16),U=new n.Buf16(16),k=null,F=0;for(M=0;M<=15;M++)w[M]=0;for(y=0;y<c;y++)w[t[s+y]]++;for(T=C,A=15;1<=A&&0===w[A];A--);if(A<T&&(T=A),0===A)return u[l++]=20971520,u[l++]=20971520,h.bits=1,0;for(O=1;O<A&&0===w[O];O++);for(T<O&&(T=O),M=b=1;M<=15;M++)if(b<<=1,(b-=w[M])<0)return-1;if(0<b&&(0===e||1!==A))return-1;for(U[1]=0,M=1;M<15;M++)U[M+1]=U[M]+w[M];for(y=0;y<c;y++)0!==t[s+y]&&(d[U[t[s+y]]++]=y);if(0===e?(P=k=d,f=19):1===e?(P=o,G-=257,k=i,F-=257,f=256):(P=r,k=a,f=-1),M=O,v=l,D=y=N=0,_=-1,m=(L=1<<(R=T))-1,1===e&&852<L||2===e&&592<L)return 1;for(;;){for(I=M-D,d[y]<f?(S=0,E=d[y]):d[y]>f?(S=k[F+d[y]],E=P[G+d[y]]):(S=96,E=0),g=1<<M-D,O=p=1<<R;u[v+(N>>D)+(p-=g)]=I<<24|S<<16|E,0!==p;);for(g=1<<M-1;N&g;)g>>=1;if(0!==g?(N&=g-1,N+=g):N=0,y++,0==--w[M]){if(M===A)break;M=t[s+d[y]]}if(T<M&&(N&m)!==_){for(0===D&&(D=T),v+=O,b=1<<(R=M-D);R+D<A&&!((b-=w[R+D])<=0);)R++,b<<=1;if(L+=1<<R,1===e&&852<L||2===e&&592<L)return 1;u[_=N&m]=T<<24|R<<16|v-l}}return 0!==N&&(u[v+N]=M-D<<24|64<<16),h.bits=T,0}},{"../utils/common":1}],10:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,s){var n=e("./zlib/inflate"),o=e("./utils/common"),i=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),l=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var s=n.inflateInit2(this.strm,t.windowBits);if(s!==r.Z_OK)throw new Error(a[s]);if(this.header=new u,n.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=i.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=n.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[s])}function h(e,t){var s=new d(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}d.prototype.push=function(e,t){var s,a,c,u,d,h=this.strm,g=this.options.chunkSize,p=this.options.dictionary,_=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=i.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new o.Buf8(g),h.next_out=0,h.avail_out=g),(s=n.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&p&&(s=n.inflateSetDictionary(this.strm,p)),s===r.Z_BUF_ERROR&&!0===_&&(s=r.Z_OK,_=!1),s!==r.Z_STREAM_END&&s!==r.Z_OK)return this.onEnd(s),!(this.ended=!0);h.next_out&&(0!==h.avail_out&&s!==r.Z_STREAM_END&&(0!==h.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=i.utf8border(h.output,h.next_out),u=h.next_out-c,d=i.buf2string(h.output,c),h.next_out=u,h.avail_out=g-u,u&&o.arraySet(h.output,h.output,c,u,0),this.onData(d)):this.onData(o.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(_=!0)}while((0<h.avail_in||0===h.avail_out)&&s!==r.Z_STREAM_END);return s===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(s=n.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(h.avail_out=0))},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=d,s.inflate=h,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},s.ungzip=h},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")}($t)),$t.exports);var qt=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=Dt,this._currentConnectState=At,this._beforeSendInterceptors=[]}init(){Ze.addTask({id:yt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Ne.get("instance"),{sdkAppId:s,testEnv:n}=t,o=Ke(s);return Je(n?Be.TEST[o].DEFAULT:Be.PRODUCTION[o].INITIAL.replace("*",`${s}`),{isBinary:e})}(this._isBinarySupported),d.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),d.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:n,timeout:o=Ct,canResend:i=!0}=t||{};if(me(e))return console.warn(`${Mt}.sendPacket: packet is empty `,e),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===Rt&&this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Nt});const r=JSON.stringify(e);let a=null;if(n){const{resolve:e,reject:t,promise:s}=fe();a=s,this._pendingRequests.set(n,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:o,canResend:i})}const c=this._isBinarySupported?et(r).buffer:r;return null===(s=this._socketAdapter)||void 0===s||s.send(c),a}connect(){var e;this._socketAdapter=new Pe(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${Mt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._connectionId=t,this._ssoLog({method:"connect",message:s}),console.log(s)}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),n=`${Mt}.disconnect socketID:${s}`;this._ssoLog({method:"disconnect",message:n}),console.log(n),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Mt}.dispose`),Ze.removeTask(yt),Ze.removeTask(Ot),d.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),d.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=Dt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===Tt&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return g(this,void 0,void 0,(function*(){const e=`${Mt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=function(e){const t=Ne.get("instance"),{sdkAppId:s,testEnv:n}=t,o=Ke(s);if(n)return Je(Be.TEST[o].DEFAULT,{isBinary:e});const i=Be.PRODUCTION[o],r=x&&i.ANYCAST;return Je({[He.INITIAL]:()=>(Ye=He.DEFAULT,i.DEFAULT),[He.DEFAULT]:()=>(Ye=He.IPV6,i.IPV6),[He.IPV6]:()=>(Ye=He.BACKUP,i.BACKUP),[He.BACKUP]:()=>(Ye=r?He.ANYCAST:He.DEFAULT,r?i.ANYCAST:i.DEFAULT),[He.ANYCAST]:()=>(Ye=He.DEFAULT,i.ANYCAST="",i.DEFAULT)}[Ye](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Pt}),console.warn(`${Mt}.reconnect failed: `,e)}}}))}_addEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.on("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.on("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.off("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.off("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},n=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,o=`${Mt}.onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${n} code: ${null==s?void 0:s.code} reason: ${null==s?void 0:s.reason}`;this._ssoLog({method:"onClose",message:o}),console.warn(o),t===this._connectionId&&this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:wt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:s}=e||{},n=`${Mt}.onError sourceSocketID: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(s)}`;this._ssoLog({method:"onError",message:n}),console.warn(n),t===this._connectionId&&this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Gt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:s}=e||{},n=`${Mt}.onSendFail sendFailSocketId: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${s}`;this._ssoLog({method:"onSendFail",message:n}),console.warn(n),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,s;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let s;try{s=xt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s})(e.data):function(e){const t=new Uint8Array(e);let s="",n=0;const{length:o}=t;for(;n<o;){let e=t[n],i=0,r=0;if(e<=127?(i=0,r=255&e):e<=223?(i=1,r=31&e):e<=239?(i=2,r=15&e):e<=244&&(i=3,r=7&e),o-n-i>0)for(let s=0;s<i;s+=1)e=t[n+s+1],r=r<<6|63&e;else r=65533,i=o-n;s+=String.fromCodePoint(r),n+=i+1}return s}(e.data):e.data,s=JSON.parse(t)}catch(t){const s=e.data;return this._ssoLog({method:"jsonParseError",message:s}),void console.error(t)}if(!s||!s.head)return;const{seq:n,servcmd:o}=s.head,i=`${n}${o}`;this._pendingRequests.has(i)?this._handleRequestResponse(s):this._handlePushMessage(s)}_handleRequestResponse(e){const{seq:t,servcmd:s}=e.head,{int32_error_code:n,str_error_message:o,ErrorCode:i=n,ErrorInfo:r=o}=(null==e?void 0:e.body)||{},a=`${t}${s}`,{resolve:c,reject:u,timestamp:l,headSeq:h}=this._pendingRequests.get(a);if(this._pendingRequests.delete(a),i&&0!==i)return d.emitInnerEvent("error",{errorCode:i,errorInfo:r}),void u({errorCode:i,errorInfo:r});c(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:n}=e.body;1===s&&this._sendAck(n),d.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${Mt}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var s;const{uplinkData:n,canResend:o,resolve:i,reject:r,timeout:a}=e;if(o){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:n,timeout:a,canResend:o});const e=this._isBinarySupported?et(n).buffer:n;null===(s=this._socketAdapter)||void 0===s||s.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:s={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const n=Date.now()-this._connectionStartTime,o=`${Mt}.onConnect cost:${n} ms. socketID:${t} res:${JSON.stringify(s)}`;if(this._ssoLog({method:"onConnect",message:o}),console.log(o),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${Mt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),d.emitInnerEvent(pt.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:At,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){const t=ot({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return g(this,void 0,void 0,(function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()}))}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return g(this,void 0,void 0,(function*(){var e;const t=ot({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=Ne.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,n=`${Mt}.sendHeartbeat failed. isNetWorkOnline:${s} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:n}),console.debug(n),this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}}))}_sendHeartbeatIfReady(){return g(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=P?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${Mt}.networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:s,networkType:n}=e;s&&"none"!==n?this._handleConnectStateChange({state:At,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:bt}):this._handleConnectStateChange({state:Rt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:bt})}isPrivateNetWork(){const e=Ne.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,shouldAttemptReconnect:s,shouldEmitEvent:n,reason:o}=e,i=`${Mt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${s} shouldEmitEvent: ${n} reason: ${o}`;this._currentConnectState!==t&&(this._ssoLog({method:"handleConnectStateChange",message:i}),console.log(i),n&&(console.log(`${Mt}._handleConnectStateChange from ${this._currentConnectState} to ${t}`),d.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),this._currentConnectState=t,t===Rt&&d.emitInnerEvent(pt.SOCKET_DISCONNECTED)),s&&(this._resetReconnectDelay(),Ze.addTask({id:Ot,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(e){var t,s;const n=null===(s=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===s?void 0:s.readyState,o=`${Mt}.activityStatusChange ${JSON.stringify(e)} readyState: ${n}`;this._ssoLog({method:"activityStatusChange",message:o}),console.warn(o),3===n&&this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Lt})}_resetReconnectDelay(){var e;console.log(`${Mt}._resetReconnectDelay`),Ze.removeTask(Ot);const t=null===(e=Ne.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Dt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=Ne.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(Dt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const s=(new Date).toTimeString().slice(0,8),n=`${Mt}.scheduleReconnectWithBackoff timeStr: ${s} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:n}),console.log(n),this.reconnect(),Ze.updateTaskInterval(Ot,this._intendedDelay)}_ssoLog(e){const{method:t,message:s}=e;Et.createSSOLogData({method:t}).setLogInfo({message:s}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){g(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const s=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield _e({method:"GET",url:s,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){g(this,void 0,void 0,(function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield _e({method:"GET",url:t,data:{}})}catch(e){console.warn("diagnoseByCDN failed. error:",e)}}))}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:n,timeout:o}=t;Date.now()-n>=o&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:he,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Ne.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=le();(L||A&&"windows"===t||P)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const Vt={init:function(e){Ne.set("instance",e),qt.init()},destroy:function(){qt.dispose(),Ne.clear(),Ze.dispose()},notificationCenter:d,channel:qt,store:Ne,ssoLog:Et,utils:Ie,common:lt,constants:i};const Bt=e=>"function"==typeof e;function jt(e,t,s){const n=s||[];if(!e||!t)return!1;const o=Object.keys(e).filter((e=>!n.includes(e))),i=Object.keys(t).filter((e=>!n.includes(e)));return o.length===i.length&&o.every((n=>!!t.hasOwnProperty(n)&&("object"==typeof e[n]&&null!==e[n]?jt(e[n],t[n],s):e[n]===t[n])))}var Kt;!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"}(Kt||(Kt={}));var Ht,Wt=Kt;!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"}(Ht||(Ht={}));var Yt,zt=Ht;!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"}(Yt||(Yt={}));var Jt=Yt;const Qt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Xt={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"};var Zt;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Zt||(Zt={}));const es={modify:zt.MESSAGE_MODIFIED,delete:zt.MESSAGE_DELETED,revoke:zt.MESSAGE_REVOKED};var ts;!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(ts||(ts={}));const ss=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xt),{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:Zt,Direction:ts}),ns={[es.modify]:zt.TOPIC_MESSAGE_MODIFIED,[es.delete]:zt.TOPIC_MESSAGE_DELETED,[es.revoke]:zt.TOPIC_MESSAGE_REVOKED},os={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"},is=Object.assign({},os),rs={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},as=Object.assign(Object.assign(Object.assign(Object.assign({},rs),{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"}),cs=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"}),us={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ls={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ds={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},hs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},us),{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:ls,GROUP_TIPS_OPERATION_TYPE:ds}),gs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Qt),ss),is),as),cs),hs),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),ps={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},_s={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},ms={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message"},vs={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"},fs={[ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:vs.USER_STATUS_UPDATE},{stepId:vs.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.CONVERSATION_RECOVER},{stepId:vs.HISTORY_MESSAGE_RECOVER,dependency:vs.CONVERSATION_RECOVER},{stepId:vs.BLACKLIST_RECOVER},{stepId:vs.FRIEND_RECOVER},{stepId:vs.GROUP_REVOKED_NOTICE_RECOVER,dependency:vs.HISTORY_MESSAGE_RECOVER},{stepId:vs.GROUP_TIPS_RECOVER,dependency:vs.HISTORY_MESSAGE_RECOVER},{stepId:vs.TOPIC_REQUEST_INFO_RESET},{stepId:vs.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC,vs.CONVERSATION_RECOVER]},{stepId:vs.EMIT_C2C_MESSAGE_EVENT,dependency:[vs.UNREAD_MESSAGE_SYNC,vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[ms.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:vs.COMMERCIAL_CONFIG_UPDATE},{stepId:vs.CLOUD_CONFIG_SYNC},{stepId:vs.USER_PROFILE_SYNC},{stepId:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.FRIEND_AND_BLACKLIST_SYNC},{stepId:vs.GROUP_LIST_SYNC},{stepId:vs.CONVERSATION_LIST_SYNC},{stepId:vs.SIGNALING_MESSAGE_RECOVER,dependency:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC]},{stepId:vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC,vs.CONVERSATION_LIST_SYNC]},{stepId:vs.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[vs.GROUP_LIST_SYNC,vs.CONVERSATION_LIST_SYNC]},{stepId:vs.CONVERSATION_GROUP_LIST_SYNC},{stepId:vs.CONVERSATION_GROUP_UPDATE,dependency:[vs.CONVERSATION_LIST_SYNC,vs.CONVERSATION_GROUP_LIST_SYNC]},{stepId:vs.QUALITY_REPORT}],[ms.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:vs.HANDLE_C2C_NEW_MESSAGE},{stepId:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:vs.HANDLE_C2C_NEW_MESSAGE},{stepId:vs.EMIT_C2C_MESSAGE_EVENT,dependency:[vs.HANDLE_C2C_NEW_MESSAGE,vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC]}],[ms.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.UPDATE_GROUP_NEXT_SEQUENCE,dependency:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.EMIT_GROUP_MESSAGE_EVENT,dependency:[vs.HANDLE_GROUP_NEW_MESSAGE,vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},Is={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Ss={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var Es=Object.freeze({__proto__:null,ERROR_CODE:ps,InnerEvent:zt,OuterConstant:gs,OuterEvent:Wt,QUALITY_METRICS:Is,SDK_EDITION:_s,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Ss,SignalingEvent:Jt,WORKFLOW_DEFINITIONS:fs,WORKFLOW_NAME:ms,WORKFLOW_STEP:vs});var Cs,Ms,ys;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Cs||(Cs={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Ms||(Ms={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(ys||(ys={}));const Os={[Ms.multipleAccount]:"multipleAccount",[Ms.multipleDevice]:"multipleDevice",[Ms.restApi]:"REST_API_Kick",[ys.multipleAccount]:"multipleAccount",[ys.multipleDevice]:"multipleDevice",[ys.restApi]:"REST_API_Kick",[ys.usersigExpired]:"userSigExpired"},As="login_online_presence_task",{ERROR:Ts,DESTROY:Rs,FORCE_OFFLINE:Ds}=zt,{KICKED_OUT_MULT_ACCOUNT:bs,KICKED_OUT_MULT_DEVICE:Ls,KICKED_OUT_REST_API:Ns,ACCOUNT_A2KEY_EXPIRED:Ps,MSG_A2KEY_EXPIRED:Gs}=ps;class ws{init(){const{notificationCenter:e}=Vt;e.subscribeInnerEvent(Ds,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Ts,Gs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ts,Ps,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ts,bs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ts,Ls,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ts,Ns,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Rs,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:s}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:s})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return g(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{this._logKickedOutEvent(e),yield Vt.login.loginAction.logout(Cs.KICKED_OUT)}catch(e){console.debug(e)}finally{Vt.notificationCenter.emitOuterEvent(Wt.KICKED_OUT,{data:{type:Os[t]},name:Wt.KICKED_OUT}),[Ms.restApi,Ps,Gs].includes(t)&&Vt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,n=Vt.ssoLog.createSSOLogData({method:"kickedOut"}),o=`type:${Os[t]} newInstanceInfo: ${JSON.stringify(s)}`;n.setLogInfo({message:o}).end(!0),console.warn(`loginModule.${o}`)}_isKickedOut(e){return[Ms.multipleAccount,Ms.multipleDevice,Ms.restApi].includes(e)}_dispose(){const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(Ds,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Ts,Ps,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ts,Gs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ts,bs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ts,Ls,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ts,Ns,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Rs,this._dispose,this)}}function Us(){return g(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=Vt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=`${t.head.seq}${e}`;try{const e=yield Vt.channel.sendPacket(t,{timeout:9e4,requestId:s});if(e){const{HelloInterval:t,InstId:s,TinyId:n,TimeStamp:o,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:u,ErrorInfo:l,ActionStatus:d}=e;return{helloInterval:t,instanceID:s,tinyID:n,timeStamp:o,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:u,errorInfo:l,actionStatus:d}}}catch(e){throw console.warn(e),e}}))}function ks(e){var t;try{const s=Ne.getStorage("errorMessage");if(!e||!s)return"";const n=(null===(t=JSON.parse(s))||void 0===t?void 0:t.errorMessage)||{},{isIntl:o=!1,code:i,replacement1:r="",replacement2:a=""}=e;if(!i)return"";const c=o?`${i}_en`:`${i}_cn`;let u=n[n[c]?c:i]||"";return u&&(r&&(u=u.replace("$replacement1",r)),a&&(u=u.replace("$replacement2",a))),u}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Fs extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:n="",data:o=""}=e;let i=n;s&&!n&&(i=ks(e));const r=s?`${t} failed. error: {"message": ${i}, "code": ${s}}`:`${t} failed. error: {"message": ${i}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=o}}function $s(e,t){var s;if(!e)return;if(!(!0===(null===(s=Vt.store.get("login"))||void 0===s?void 0:s.isLoggedIn)))throw new Fs({code:ps.USER_NOT_LOGGED_IN,functionName:t})}function xs(e,t,s){if(Array.isArray(e))for(let n=0;n<e.length;n++)qs.call(this,Object.assign(Object.assign({},e[n]),{value:t[n],name:s}));else for(const n in e)qs.call(this,Object.assign(Object.assign({},e[n]),{value:t[0][n],name:s,key:n}))}function qs({required:e,rules:t,range:s,value:n,allowEmpty:o,name:i,key:r,customValidator:a}){if(void 0===n){if(e){throw new Fs({functionName:i,message:`[${i}] Missing required params: "${r}"`})}return}let c="";if(!t.some((e=>{return e===(t=n,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let s=t[e];s=s.replace(s[0],s[0].toUpperCase()),c+=`${s}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(n)}.`;throw new Fs({functionName:i,message:e})}if(!1===o){if(Array.isArray(n)&&(0===n.length||"string"==typeof n[0]&&""===n[0].trim())){throw new Fs({functionName:i,message:`${r} can not be empty.`})}if("string"==typeof n&&""===n.trim()){throw new Fs({functionName:i,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(n);if(!0!==e){throw new Fs({functionName:i,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const Vs=[],Bs={},js={};function Ks(e,t){$s(Bs[e],e),xs(js[e],t,e),function(e){Vs.forEach((t=>{const{interceptor:s,context:n}=t;s.apply(n,[e])}))}(e)}function Hs(e,t){Vs.push({interceptor:e,context:t})}function Ws(e){const{params:t,auth:s}=e;t&&"object"==typeof t&&Object.assign(js,t),s&&"object"==typeof s&&Object.assign(Bs,s)}function Ys(e){return Vt.store.get("commercialConfig").get(e)}class zs{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const s=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,s),console.log(`[Workflow ${e}] Step ${t} started at ${new Date(s).toISOString()}`)):(this._workflowStartTimes.set(e,s),console.log(`[Workflow ${e}] started at ${new Date(s).toISOString()}`))},success:(e,t)=>{const s=Date.now();if(t){const n=this._stepStartTimes.get(`${e}-${t}`),o=n?s-n:0;this._stepStartTimes.delete(`${e}-${t}`),console.log(`[Workflow ${e}] Step ${t} completed successfully at ${new Date(s).toISOString()} (${o}ms)`)}else{const t=this._workflowStartTimes.get(e),n=t?s-t:0;this._workflowStartTimes.delete(e),console.log(`[Workflow ${e}] completed successfully at ${new Date(s).toISOString()} (${n}ms)`)}},error:(e,t,s)=>{const n=Date.now();if(t){const o=this._stepStartTimes.get(`${e}-${t}`),i=o?n-o:0;this._stepStartTimes.delete(`${e}-${t}`),console.error(`[Workflow ${e}] Step ${t} failed at ${new Date(n).toISOString()} (${i}ms)`,s)}else{const t=this._workflowStartTimes.get(e),o=t?n-t:0;this._workflowStartTimes.delete(e),console.error(`[Workflow ${e}] failed at ${new Date(n).toISOString()} (${o}ms)`,s)}}}}static getInstance(){return zs._instance||(zs._instance=new zs),zs._instance}static setInstance(e){zs._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,n){if(!this._handlers.has(e))return void console.debug(`Workflow '${e}' not defined in core`);if(!fs[e].find((e=>e.stepId===t)))return void console.debug(`Step '${t}' not defined in workflow '${e}'`);const o=this._handlers.get(e);o.has(t)||o.set(t,n?s.bind(n):s)}executeWorkflow(e,t){return g(this,void 0,void 0,(function*(){if(!this._validateWorkflow(e))return;console.log(`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const s=fs[e],n={},o={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:o});try{const i=new Map;s.forEach((e=>{i.set(e.stepId,e)}));const r={workflowName:e,pendingSteps:new Set(s.map((e=>e.stepId))),completedSteps:new Set,runningSteps:new Set,stepMap:i,stepResults:n,data:t,cancelToken:o};yield new Promise(((t,s)=>{const n=()=>{if(o.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).forEach((o=>{r.completedSteps.has(o)||r.runningSteps.has(o)||this._executeWorkflowStep(o,r,{onComplete:()=>{if(0===r.pendingSteps.size)return void t();0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).length&&0===r.runningSteps.size&&(console.log(`Workflow ${e} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:n})}))};n()})),console.log(`[Workflow ${e}] Completed execution at ${(new Date).toISOString()}`)}catch(t){console.error(`[Workflow ${e}] Failed execution at ${(new Date).toISOString()}`,t)}finally{this._activeWorkflows.delete(e)}}))}_executeWorkflowStep(e,t,s){return g(this,void 0,void 0,(function*(){const{workflowName:n,runningSteps:o,stepMap:i,stepResults:r,data:a}=t;o.add(e),this._logWorkflowExecution(n,e,"start");try{const s=i.get(e);let o=null;(null==s?void 0:s.dependency)&&(_(s.dependency)?o=r[s.dependency]:Array.isArray(s.dependency)&&(o={},s.dependency.forEach((e=>{o[e]=r[e]}))));const c=this._handlers.get(n).get(e);if(c){const t=yield Promise.resolve(c({data:a,result:o}));r[e]=t,this._logWorkflowExecution(n,e,"success")}t.completedSteps.add(e)}catch(t){const o=`[Workflow].${n}.${e}`,{errorCode:i,errorInfo:r=`${o} failed`}=t||{},a=new Fs({functionName:o,code:i,message:r});Vt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${n}, stepId: ${e}`}).setError(a).end(),this._logWorkflowExecution(n,e,"error",t),s.onError(t)}finally{o.delete(e),t.pendingSteps.delete(e),s.onStepComplete(),s.onComplete()}}))}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(fs).forEach((e=>{this._handlers.has(e)||this._handlers.set(e,new Map)}))}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:s}=t;s.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(fs).forEach((e=>{this._cancelWorkFlow(e)}))}_validateWorkflow(e){if(!fs[e])return console.debug(`Workflow '${e}' not defined`),!1;return!!this._handlers.get(e)||(console.debug(`No handlers registered for workflow '${e}'`),!1)}_getExecutableSteps(e){const{pendingSteps:t,completedSteps:s,stepMap:n,workflowName:o}=e;return Array.from(t).filter((e=>{const t=n.get(e)||{},{dependency:i,skipIfDependencyMissing:r=!0}=t;if(!i)return!0;if(_(i))return this._isStepRegistered({workflowName:o,stepId:i})?s.has(i):!r;if(v(i)){if(i.filter((e=>!this._isStepRegistered({workflowName:o,stepId:e}))).length>0&&r)return!1;for(const e of i)if(!s.has(e))return!1;return!0}return!1}))}_isStepRegistered(e){var t;const{workflowName:s,stepId:n}=e;return null===(t=this._handlers.get(s))||void 0===t?void 0:t.has(n)}_logWorkflowExecution(e,t,s,n){this._logHandlers[s](e,t)}}const Js=new Map,Qs=({type:e,groupID:t})=>e===gs.GRP_COMMUNITY||`${t}`.startsWith(ls.COMMUNITY)&&!`${t}`.includes(ls.TOPIC),Xs=(e="")=>{const t=e.startsWith("GROUP")?e.replace("GROUP",""):e;return t.startsWith(ls.COMMUNITY)&&`${t}`.includes(ls.TOPIC)},Zs="openim",en="million_group_open_http_svc";function tn(e){return g(this,void 0,void 0,(function*(){const{servcmd:t,data:s}=function(e){const{data:t}=e;return sn(t)||nn(t)}(e)?function(e){let{servcmd:t,data:s}=e;if(nn(s))return function(e){const{servcmd:t,data:s}=e;let{GroupId:n=""}=s;const o=n;return[n]=o.split(ls.TOPIC),{servcmd:on(t),data:Object.assign(Object.assign({},s),{GroupId:n,TopicId:o})}}(e);sn(s)&&(t=on(t));return{servcmd:t,data:s}}(e):e,n=Vt.common.generateProtocolData({servcmd:t,data:s}),o=`${n.head.seq}${t}`;return Vt.channel.sendPacket(n,{requestId:o})}))}function sn(e){const{Type:t,GroupId:s,GroupIdList:n=[]}=e,o=s||n[0]||"";return Qs({type:t,groupID:o})}function nn(e){const{GroupId:t=""}=e;return Xs(t)}function on(e){if(e.includes(Zs))return e;const t=e.split(".")[1];return`${en}.${t}`}function rn(){var e;return null===(e=Vt.store.get("login"))||void 0===e?void 0:e.userId}const an=e=>v(e)||f(e),cn=(e,t,s,n)=>{if(!an(e)||!an(t))return 0;let o=0;const i=Object.keys(t);let r;for(let a=0,c=i.length;a<c;a++)if(r=i[a],!(p(t[r])||s&&s.includes(r)))if(an(e[r])&&an(t[r]))o+=cn(e[r],t[r],s,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],o+=1)}return o},un=(e,t)=>{if(p(t))return"";switch(e){case gs.MSG_TEXT:return t.text||"";case gs.MSG_IMAGE:return"[Image]";case gs.MSG_LOCATION:return"[Location]";case gs.MSG_AUDIO:return"[Voice]";case gs.MSG_VIDEO:return"[Video]";case gs.MSG_FILE:return"[File]";case gs.MSG_CUSTOM:return"[Custom Messages]";case gs.MSG_GRP_TIP:return"[Group Notification]";case gs.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case gs.MSG_FACE:return"[Animated Sticker]";case gs.MSG_MERGER:return"[Chat Record]";default:return""}},ln=[{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_members",interval:3,count:1},{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}],dn="im_sdk_config_mgr.fetch_config",hn="im_sdk_config_mgr.push_configv2",gn="cloud-config",pn=2996;var _n=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},channel:r}=e;t.subscribeInnerEvent(hn,this._handlePushedConfig,this),n.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(ln),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t;const s={code:0,data:""};return e?(s.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",s):s}checkMethodCallOverLimit(e){if(!this._cmdFrequencyLimitMap.has(e))return;if(!this._methodCallFrequencyMap.has(e))return void this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});const{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e);let{startTime:n,methodCallCounter:o}=this._methodCallFrequencyMap.get(e);if(Date.now()-n>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(o+=1,this._methodCallFrequencyMap.set(e,{startTime:n,methodCallCounter:o}),o>t)throw new this._core.helper.ChatError({code:pn,replacement1:e})}_fetchCloudConfig(){return g(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:dn,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=`${t.head.seq}${dn}`;return yield this._core.channel.sendPacket(t,{requestId:s})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}}))}_handlePushedConfig(e){this._updateCloudConfig(e)}_handleLoginSuccess(){return g(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:gn,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return g(this,void 0,void 0,(function*(){if(this._canFetch())try{const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}}))}_updateCloudConfig(e){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t))}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:s,str_json_config:n,uint32_expired_time:o,uint32_sdkappid:i,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(n),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*o}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){var e;let t=null===(e=this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;const{isEmpty:s}=this._core.utils;if(!s(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}}_updateCmdFreqLimitMap(e){e.forEach((e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,count:e.count})}))}_reset(){this._core.helper.taskScheduler.removeTask(gn),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(ln),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(hn,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class mn{constructor(e=0,t=0){this.high=e,this.low=t}equal(e){return null!==e&&(this.low===e.low&&this.high===e.high)}toString(){const e=Number(this.high).toString(16);let t=Number(this.low).toString(16);if(t.length<8){let e=8-t.length;for(;e;)t=`0${t}`,e--}return e+t}}const vn={SEARCH_GRP_SNS:new mn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new mn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new mn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new mn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new mn(0,Math.pow(2,6)).toString(),USER_STATUS:new mn(0,Math.pow(2,7)).toString(),CONV_MARK:new mn(0,Math.pow(2,9)).toString(),CONV_GROUP:new mn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new mn(0,Math.pow(2,11)).toString(),MSG_EXT:new mn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new mn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new mn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new mn(Math.pow(2,7)).toString(),PLUGIN_CS:new mn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new mn(Math.pow(2,9)).toString(),PLUGIN_BOT:new mn(Math.pow(2,10)).toString(),MSG_REACTION:new mn(Math.pow(2,16)).toString(),FOLLOW:new mn(Math.pow(2,20)).toString()},fn="CommercialConfig",In="commercial-config";var Sn=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){this._core=e;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:o,InnerEvent:i}}=e;s.subscribeInnerEvent(i.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(i.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(i.DESTROY,this._dispose,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,o.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return g(this,void 0,void 0,(function*(){const t=parseInt(e,10).toString(2),{length:s}=t;let n,o=!0;for(let e=s-1,i=0;e>=0;e--,i++)if("1"===t.charAt(e)&&(n=i<32?new mn(0,2**i).toString():new mn(2**(i-32),0).toString(),!this._featureMap.get(n))){o=!1;break}return console.log(`${fn}.isFeatureEnabled decimalNumber:${e} key:${n} ret:${o}`),{code:0,data:{enabled:o}}}))}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return g(this,void 0,void 0,(function*(){var e;try{this._isFetching=!0;const t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}}),s=yield this._core.channel.sendPacket(t);(null==s?void 0:s.body)&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_syncCommercialConfig(e){return g(this,void 0,void 0,(function*(){const{purchaseBits:t}=(null==e?void 0:e.data)||{};t&&(this._parsePurchaseBits(t),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:In,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})}))}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,s=Date.now()>=this._expirationTime;return t&&!this._isFetching&&s}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return g(this,void 0,void 0,(function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())}))}_parseCommercialConfig(e){if("object"!=typeof e)return;const{int32_error_code:t,str_error_message:s,str_purchase_bits:n,uint32_expired_time:o}=e;0===t?(this._parsePurchaseBits(n),this._expirationTime=Date.now()+1e3*o):void 0===t?(console.log(`${fn}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${fn}._parseCommercialConfig errorCode:${t} errorMessage:${s}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){if(this._isValidPurchaseBits(e)){this._purchaseBits=e,this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let s=e.length-1,n=0;s>=0;s--,n++)if(t=n<32?new mn(0,2**n).toString():new mn(2**(n-32),0).toString(),"1"===e[s]){this._featureMap.set(t,!0);const e=this._getKeyByValue(vn,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(vn,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${fn}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const s=Object.entries(e).find((([e,s])=>s===t));return s?s[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(In),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}};var En=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,channel:n}=this._core;t.subscribeInnerEvent(s.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:s}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(e)}_handleOverLoadPush(e){const{OverLoadServCmd:t,DelaySecs:s}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:s})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var Cn=new class{constructor(){this.name="ConfigCenter"}install(e){_n.install(e),Sn.install(e),En.install(e)}};var Mn=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return g(this,void 0,void 0,(function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}}))}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return g(this,void 0,void 0,(function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}}))}_isExpired(e){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),s={},n=new RegExp(/'/g);for(let e=0;e<t.length;e++){const o=t[e].indexOf(":"),i=t[e].slice(0,o);let r=t[e].slice(o+1);if(!i.startsWith("//")){if(""===r)continue;r=r.replace(n,""),s[i]=r}}return s}}};function yn(e,t){return g(this,void 0,void 0,(function*(){const{cookie:s,syncFlag:n,syncTriggerEvent:o}=e,i="openim.getmsg",r=t.helper.generateProtocolData({servcmd:i,data:{Cookie:s,SyncFlag:n,IsOnlineSync:o,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${i}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:s,C2CRemainingUnreadCount:n,EventArray:o}=e,{unreadMessageList:i,revokedMessageList:c}=function(e,t){const s=[],n=[];return null==e||e.forEach((e=>{var o,i,r;const a=function(e,t){const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,IsNeedReadReceipt:i,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:u,MsgTimeStamp:l,SendMsgControl:d,SupportMessageExtension:h,To_Account:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,IsPeerRead:v,MsgFlagBits:f,MsgVersion:I,EventArray:S}=e;return{from:s,avatar:n,nick:o,needReadReceipt:1===i,readReceiptSentByPeer:v,clientTime:a,messageFlagBits:f,random:c,sequence:u,time:l,messageControlInfo:d,isSupportExtension:h,to:g,tinyID:p,checkResult:_,cloudCustomData:m,messageVersion:I,eventArray:S,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(i=null===(o=null==e?void 0:e.EventArray)||void 0===o?void 0:o[0])||void 0===i?void 0:i.hasOwnProperty)||void 0===r?void 0:r.call(i,"C2cNotifyMsgArray"))n.push(...function(e){var t;const s=[];return null===(t=e.EventArray)||void 0===t||t.forEach((e=>{var t,n;const{C2cNotifyMsgArray:o}=e,i=null===(n=null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===n?void 0:n.C2cWithdrawInfoArray;Array.isArray(i)&&s.push(...i)})),s}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:n}=a;e.setElement(n),s.push(e)}})),{unreadMessageList:s,revokedMessageList:n}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:c,unreadCountList:s,overflowUnreadCountList:n,cookie:null==e?void 0:e.Cookie,groupTipList:o}}catch(e){console.warn(e)}}))}var On,An;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(On||(On={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(An||(An={}));var Tn=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){this._core=e;const{constants:t}=e;e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(e){return g(this,void 0,void 0,(function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:s=!1,isAfterLogin:n=!1}=e||{};let o=On.START_SYNC;const i=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:o});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:o,syncTriggerEvent:s?An.NEW_MESSAGE_RECEIVED:An.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:n=[],revokedMessageList:u=[],overflowUnreadCountList:l,unreadCountList:d,groupTipList:h}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",o=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(n),a.push(...u),this._updateConversationUnreadOptions({unreadCountList:d,overflowUnreadCountList:l,conversationUpdateFieldList:i}),Array.isArray(h)&&r.push(...h),t){const{messages:e}=this._handleNewMessageList(n);c.push(...e)}}return t?{conversationUpdateFieldList:i,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:i,isInstantMessage:!n,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}}))}_syncUnreadDBMessageAfterLogin(){return g(this,void 0,void 0,(function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})}))}_syncUnreadDBMessageAfterNewMessageReceived(e){return g(this,void 0,void 0,(function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})}))}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:n}=e,{constants:{OuterConstant:{CONV_C2C:o,CONV_SYSTEM:i}}}=this._core;null==t||t.forEach((e=>{const{From_Account:t,UnreadCount:s}=e;if(t!==i){const e=n.find((({conversationID:e})=>e===`${o}${t}`));e?e.unreadCount=s:n.push({conversationID:`${o}${t}`,unreadCount:s,type:o})}})),null==s||s.forEach((e=>{const{From_Account:t,LastMsgTime:s}=e;if(t!==i){n.find((({conversationID:e})=>e===`${o}${t}`))||n.push({conversationID:`${o}${t}`,type:o,lastMsgTime:s})}}))}_syncUnreadDBMessageAfterReOnline(){return g(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterReOnline:!0})}))}_updateMessageProfile(e){var t;const{messageDataHandler:s}=this._core.message||{},n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a=""}=e;if(o!==n){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:n,avatar:o}=t;i&&r?i===n&&r===o||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}):(e.nick=n,e.avatar=o)}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},s=new Map,n=[];return e.forEach((e=>{this._updateMessageProfile(e);let o=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=o:o=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||n.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;s.has(t)?(s.get(t).lastMessage=c,"in"===i&&(r||s.get(t).unreadCount++)):s.set(t,{conversationID:t,type:n,subType:o,unreadCount:r||"in"!==i?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!o||n.push(e)}})),{messages:n,conversationOptions:s}}_fetchUnreadDBMessage(e){return g(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const s=yield yn(e,this._core);if(!s)return null;const{syncFlag:n,unreadMessageList:o,revokedMessageList:i,cookie:r,unreadCountList:a,overflowUnreadCountList:c,groupTipList:u}=s;return this._parseAndSaveUnreadMessageList(o),{syncFlag:n,cookie:r,unreadMessageList:o,revokedMessageList:i,unreadCountList:a,overflowUnreadCountList:c,groupTipList:u}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var s;return t===On.START_SYNC||t===On.SYNCING&&!(null===(s=this._core)||void 0===s?void 0:s.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Rn=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const s="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:s}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:s})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Dn=new class{init(e){var t;this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var e;const{MINI_APP_NAMESPACE:t}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};t.onAppShow((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})})),t.onAppHide((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var bn=new class{init(e){const{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Dn.init(e):Rn.init(e))}};const Ln="none",Nn="online";var Pn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return g(this,void 0,void 0,(function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)}))}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Nn})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Ln})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Gn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return g(this,void 0,void 0,(function*(){try{this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),wx.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}}))}_deactivateNetworkMonitoring(){null!==this._mpNetworkStatusCallback&&(wx.offNetworkStatusChange&&wx.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var wn=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Gn.init(e):Pn.init(e)}};var Un=new class{constructor(){this.name="SystemStateMonitor"}install(e){bn.init(e),wn.init(e)}};const kn=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.*"]),Fn="tui_room_svr.*";var $n=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=kn}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n}=e;t.subscribeInnerEvent(s.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),n.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),n.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return g(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:s=Fn}=e||{};if(!this._isValidTransferredCommand(s))throw new this._core.helper.ChatError({code:2995,functionName:t});const n=yield function(e,t){return g(this,void 0,void 0,(function*(){const{helper:s,channel:n}=t,{serviceCommand:o=Fn,data:i}=e||{};let r={};try{r="string"==typeof i?JSON.parse(i):i}catch(e){console.warn(e)}const a=s.generateProtocolData({servcmd:o,data:r}),c=`${a.head.seq}${o}`;return n.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:n||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}}))}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:s}=this._core,{MsgContent:n}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:o}=t;s.emitOuterEvent(o,{name:o,data:n})}_reset(){this._transferredCommands=kn}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const xn=1,qn=2,Vn=3,Bn=4,jn=5,Kn="TIMCustomElem",Hn="C2C",Wn="GROUP",Yn="invite",zn="accept",Jn="cancel",Qn="reject",Xn="modifyInvitation",Zn="signaling",eo=8010,to="signaling-timeout";function so(e){return e.filter((e=>{if(e.type===Kn){const{cloudCustomData:t="",payload:{data:s=""}={}}=e,n=t.match(/"type":"tsignaling"/),o=s.match(/inviteID/),i=s.match(/actionType/);return n||o&&i}return!1}))}function no(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function oo(e,t){return e.toString(16).padStart(t,"0")}function io(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var ro=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${Zn}.isInvitationValid`,{inviteID:s,groupID:n,inviter:o}=e,i=o===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(s))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(s);if(console.log(`${t} inviteID:${s} inviteeList:${r} groupID:${n}`),n){if(i)return r.length>0;const e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){const t=`${Zn}.updateSignaling`,{inviteID:s,inviter:n,inviteeList:o,groupID:i}=e;if(console.log(`${t} inviteID:${s} inviter:${n} groupID:${i}`),i&&this.hasSignaling(s)){const e=o[0],{inviteeList:n}=this._onlineSignalingMap.get(s);n.includes(e)&&(n.splice(n.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${n.length}`)),0===n.length&&this.removeSignaling(s)}else this.removeSignaling(s)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var ao=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),s=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:n,inviteeList:o}=s,i=n||o[0];return{signaling:this._createSignaling(s,i),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:s,inviter:n}=t,o=s||n;return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:s,inviteeList:n}=t,o=s||n[0];return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:s,inviter:n}=t,o=s||n;return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,s=this._createTimeoutSignalingData(e),{groupID:n,inviteeList:o,inviter:i}=s,r=n||(t?o[0]:i);return{signaling:this._createSignaling(s,r),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}_createSignalingExtensionOptions(e){var t,s;const{data:n="",onlineUserOnly:o,inviteID:i="",offlinePushInfo:r,actionType:a}=e,c=(null===(s=null===(t=ro.getSignaling(i))||void 0===t?void 0:t.signaling)||void 0===s?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:o||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(n,a)}}_createMessageControlInfo(e,t){const s=t===jn&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),n=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:s||n,excludedFromLastMessage:s||n}}_createInviteSignalingData(e){const t=`${Zn}._createInviteSignalingData`,{userID:s,timeout:n=0,groupID:o="",inviteeList:i=[]}=e,r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:xn,inviter:r,inviteeList:o?i:[s],timeout:n});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${Zn}._createAcceptSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviter:o,groupID:i}=ro.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Vn,groupID:i,inviter:o,inviteeList:[n]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${Zn}._createCancelSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviteeList:o,groupID:i}=ro.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:qn,groupID:i,inviter:n,inviteeList:o});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${Zn}._createRejectSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviter:o,groupID:i}=ro.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Bn,groupID:i,inviter:o,inviteeList:[n]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${Zn}._createTimeoutSignalingData`,{isInviter:s=!1,inviteID:n}=e,{inviteeList:o,inviter:i}=ro.getSignaling(n),r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:jn,inviter:i,inviteeList:s?o:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var s,n,o;const{groupID:i=""}=e,r={to:t,conversationType:i?Wn:Hn,priority:"High",payload:{data:JSON.stringify(e)}};return null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.createCustomMessage(r)}_generateInviteID(){return[oo(io(32),8),oo(io(16),4),oo(16384|io(12),4),oo(32768|io(14),4),oo(io(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:s="",groupID:n=""}=e;return{businessID:1,timeout:0,data:t,inviteID:s,groupID:n}}};var co=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return g(this,void 0,void 0,(function*(){var t;console.log(`${Zn}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:s,signalingData:n,signalingExtensionOptions:o}=ao.createInviteSignaling(e),i=yield this._sendSignaling(s,o);if(0===(null==i?void 0:i.code)){const{inviteID:e,timeout:o}=n;return ro.saveSignaling(e,Object.assign(Object.assign({},n),{signaling:s})),o>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${to}-${e}`,intervalMs:1e3*(o+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}return i}catch(e){throw console.error(`${Zn}.invite error:${e}`),e}}))}accept(e){return g(this,void 0,void 0,(function*(){console.log(`${Zn}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:s,signalingData:n,signalingExtensionOptions:o}=ao.createAcceptSignaling(e),i=yield this._sendSignaling(s,o);return 0===(null==i?void 0:i.code)?(ro.updateSignaling(n),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${Zn}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return g(this,void 0,void 0,(function*(){console.log(`${Zn}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:n}=ao.createCancelSignaling(e),o=yield this._sendSignaling(s,n);return 0===(null==o?void 0:o.code)?(ro.removeSignaling(t),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${Zn}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return g(this,void 0,void 0,(function*(){console.log(`${Zn}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:n}=ao.createRejectSignaling(e),o=yield this._sendSignaling(s,n);return 0===(null==o?void 0:o.code)?(ro.removeSignaling(t),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${Zn}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return g(this,void 0,void 0,(function*(){var t,s;console.log(`${Zn}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:n,data:o}=e;let i="";try{this._validateBeforeModifyInvitation(n);const e=ro.getSignaling(n),{signaling:r}=e,a=h(e,["signaling"]);i=r.payload.data,a.data=o,r.payload.data=JSON.stringify(a);const c=yield null===(s=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===s?void 0:s.modifyMessage(r);return ro.hasSignaling(n)&&ro.saveSignaling(n,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(i){const{signaling:e}=ro.getSignaling(n);e.payload.data=i}throw e}}))}getSignalingInfo(e){if(0===so([e]).length)return;const t=no(e),s={businessID:t.businessID||1,inviteID:t.inviteID,groupID:t.groupID||"",inviter:t.inviter||"",inviteeList:t.inviteeList||[],data:t.data||"",actionType:t.actionType||xn,timeout:t.timeout||0};return console.log(`${Zn} getSignalingInfo `,s),s}addSignalingListener(e,t,s){var n,o;e===(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&ro.setSignalingListenStatus(!0),null===(o=this._core)||void 0===o||o.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var n,o;e===(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&ro.setSignalingListenStatus(!1),null===(o=this._core)||void 0===o||o.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){const t=ro.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();if(!t.has(e))return;const n=t.get(e).inviter===s;this._sendTimeoutNotice({inviteID:e,isInviter:n})}_sendSignaling(e,t){return g(this,void 0,void 0,(function*(){var s,n,o;return null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)}))}_sendTimeoutNotice(e){return g(this,void 0,void 0,(function*(){var t,s,n;console.log(`${Zn}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:o,inviteID:i}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=ao.createTimeoutSignaling(e),u=yield this._sendSignaling(r,c);if(0===(null==u?void 0:u.code)){const{data:e,groupID:c,inviteeList:u,inviter:l}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,{name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:i,inviteeList:u,inviter:l,isSelfTimeout:!0,message:r}}),o?ro.removeSignaling(i):ro.updateSignaling(a)}}))}_validateInviteId(e,t){if(!ro.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:eo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=Yn,{userID:s}=e,n=this._core.common.getCurrentUserID();if(s===n)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${n}, inviteeId:${s}`})}_validateBeforeAccept(e){const t=zn;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:n}=ro.getSignaling(e);if(!n.includes(s)){const n=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:n})}}_validateBeforeCancel(e){const t=Jn;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviter:n}=ro.getSignaling(e);if(n!==s){const e=`unmatched inviter:${n} and my userID:${s}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=Qn;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:n}=ro.getSignaling(e);if(!n.includes(s)){const n=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:n})}}_validateBeforeModifyInvitation(e){const t=Xn;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}};var uo=new class{constructor(){this._actionProcessor=new Map([[xn,this._onNewInvitationReceived.bind(this)],[Bn,this._onInviteeRejected.bind(this)],[Vn,this._onInviteeAccepted.bind(this)],[qn,this._onInvitationCancelled.bind(this)],[jn,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach((e=>{const t=no(e);if(t){const s=this._actionProcessor.get(t.actionType);null==s||s(t,e)}}))}_handleMessageReceived(e){if(!ro.getSignalingListenStatus())return;const t=so(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!ro.getSignalingListenStatus())return;const t=so(e.data);t.length>0&&t.forEach((e=>{const t=no(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var s,n;const o=`${Zn}._onNewInvitationReceived`,{inviteID:i,inviteeList:r,groupID:a}=e,c=this._core.common.getCurrentUserID();console.log(`${o} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:u}=e;const l=Date.now()/1e3-t.time;u>0&&l>0&&u>l&&(u-=l);const d=ro.getSignaling(i);d!==e&&(d||ro.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),u>0&&(null===(s=this._core)||void 0===s||s.helper.taskScheduler.addOnceTask({id:`${to}-${i}`,intervalMs:1e3*u,callback:co.handleInvitationExpiryTimer.bind(co,i)})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const s=`${Zn}._onInviteeRejected`,{inviteID:n,inviter:o,groupID:i,inviteeList:r}=e,a=ro.hasSignaling(n);console.log(`${s} inviteID:${n} hasInviteID:${a} inviter:${o} groupID:${i}`),a&&(ro.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const s=`${Zn}._onInviteeAccepted`,{inviteID:n,inviter:o,groupID:i,inviteeList:r}=e,a=ro.hasSignaling(n);console.log(`${s} inviteID:${n} hasInviteID:${a} inviter:${o} groupID:${i}`),a&&(ro.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const s=`${Zn}._onInvitationCancelled`,{inviteID:n,inviter:o,groupID:i}=e,r=ro.hasSignaling(n);console.log(`${s} inviteID:${n} hasInviteID:${r} inviter:${o} groupID:${i}`),r&&(ro.removeSignaling(n),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const s=`${Zn}._onInvitationTimeout`,{inviteID:n,inviteeList:o}=e,i=ro.hasSignaling(n);console.log(`${s} inviteID:${n} hasInviteID:${i} data:${e.data}`),i&&(ro.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:o,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s;const n=`${Zn}._onInvitationModified`,{inviteID:o,data:i}=e,r=ro.hasSignaling(o);console.log(`${n} inviteID:${o} data:${i}`),r&&(ro.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:o,data:i}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:s,groupID:n,data:o}=e;return{inviteID:t,inviter:s,groupID:n,data:o||""}}_dispose(){var e,t,s;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(s=this._core)||void 0===s||s.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var lo=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:s,constants:{InnerEvent:n,WORKFLOW_STEP:o,WORKFLOW_NAME:i}}=e;t.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,o.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(!(0!==(null==t?void 0:t.size)&&ro.getSignalingListenStatus()))return;const s=so([...t.values()]);if(0!==s.length&&(s.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();uo.handleActionSignaling(e)}}_handleC2CActionType(e){const t=no(e);if(!t)return;const{actionType:s}=t;s===xn?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:s,inviteeList:n=[],timeout:o=0}=e,i=this._core.common.getCurrentUserID();if(!n.includes(i))return;const r=Date.now()/1e3-t.time;o>0&&r>o&&0!==o||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach((t=>{e=[...e,...t.signalingList]})),e.sort(((e,t)=>e.time-t.time))}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const ho={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}}},go={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var po=new class{constructor(){this.name="Signaling"}install(e){co.init(e),uo.init(e),ao.init(e),ro.init(e),lo.init(e),e.helper.registerValidateConfig({auth:go,params:ho})}};const _o=new class{init(e){this.core=e}};var mo,vo;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(mo||(mo={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(vo||(vo={}));const fo="MSG_REACTION",Io="MSG_EXT",So=0,Eo=1,Co={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Mo="16k_zh",yo="16k_en",Oo="16k_yue",Ao="16k_ja",To="16k_zh-PY",Ro={[Co.ZH_CN]:Mo,[Co.EN_US]:yo,[Co.YUE_HK]:Oo,[Co.JA_JP]:Ao,[Co.ZH_PY]:To},Do=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,bo={READ:0,UNREAD:1},Lo=1,No=2,Po=3,Go=1,wo=2;const Uo=2116,ko=2500,Fo="C2C",$o="GROUP",xo=20;function qo(e){return g(this,void 0,void 0,(function*(){var t;const{appStore:s}=_o.core,{messageList:n,conversationID:o}=e,i=s.conversationStore.getConversationMap();let r=null===(t=i.get(o))||void 0===t?void 0:t.peerReadTime;if(!r){const e=o.replace(Fo,""),t=yield function(e){return g(this,void 0,void 0,(function*(){const t={To_Account:e};return _o.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:t})}))}([e]);if(t){const{ReadTime:e}=t;r=null==e?void 0:e[0],i.has(o)&&(i.get(o).peerReadTime=r)}}n.forEach((e=>{e.time<=r&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)}))}))}function Vo(e){return g(this,void 0,void 0,(function*(){var t;const{message:s,user:n,appStore:o,constants:{OuterConstant:i}}=_o.core,r=o.conversationStore.getConversationMap();if(r.has(e)){const s=null===(t=r.get(e))||void 0===t?void 0:t.userProfile;if(s&&e.startsWith(i.CONV_C2C)){const{avatar:t,nick:n}=s;_o.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:n,isSentByMe:!1})}}const{data:a}=(yield n.userProfile.getMyProfile())||{};if(a){const{avatar:t,nick:n}=a;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:n,isSentByMe:!0})}}))}function Bo(e){let t;const{message:s}=_o.core,{conversationID:n,messageID:o}=e;if(t=s.messageDataHandler.getLocalMessageList(n).find((e=>e.ID===o)),!t){t=s.messageDataHandler.getSparseMessageList(n).find((e=>e.ID===o))}return t}function jo(e){return e.map((e=>{const{from:t,to:s,cloudCustomData:n,avatar:o,nick:i,ID:r,clientSequence:a,clientTime:c,messageRandom:u,messageSequence:l,time:d}=e;return{ClientSeq:a,CloudCustomData:n,From_Account:t,From_AccountHeadurl:o,From_AccountNick:i,Id:r,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:c,MsgRandom:u,Random:u,MsgSeq:l,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}}))}function Ko(e){var t;const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,GroupId:i,MsgClientTime:r,ClientSeq:a,To_Account:c,MsgTimeStamp:u,TinyId:l,MsgRandom:d,MsgSeq:h}=e;return{from:s,avatar:n,nick:o,clientTime:r,time:u,tinyID:l,random:d,sequence:h,to:c,groupID:i,clientSequence:a,_elements:null===(t=e.MsgBody)||void 0===t?void 0:t.map((e=>{const{MsgType:t}=e;return _o.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)}))}}var Ho=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{MESSAGE_REACTION_UPDATED:o,MESSAGE_REACTION_UPDATED_SYNC:i}}=e;t.registerApi({apiName:"addMessageReaction",context:this}),t.registerApi({apiName:"removeMessageReaction",context:this}),t.registerApi({apiName:"getMessageReactions",context:this}),t.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),s.subscribeInnerEvent(n,o,this._handleReactionUpdated,this),s.subscribeInnerEvent(n,i,this._handleReactionSync,this)}addMessageReaction(e,t){return g(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:n,helper:o}=this._core;this._validateMessageReactionBusinessCapability();const i=n.createSSOLogData({method:"addMessageReaction"}),{conversationID:r,ID:a,conversationType:c,from:u,to:l,clientSequence:d,random:h,time:p,sequence:_}=e;try{return this._recordMessageReactedByMe(a,t),c===s.CONV_C2C?yield function(e,t){return g(this,void 0,void 0,(function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:u})}))}({from:u,to:l,clientSequence:d,random:h,time:p,reactionID:t},this._core):c===s.CONV_GROUP&&(yield function(e,t){return g(this,void 0,void 0,(function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:r})}))}({to:l,reactionID:t,sequence:_},this._core)),i.setLogInfo({message:`conversationID:${r} messageID:${a} reactionID:${t}`}).end(),{code:0}}catch(e){this._removeMyReactionRecord(a,t);const{errorCode:s}=e||{},n=new o.ChatError({functionName:"addMessageReaction",code:s});i.setError(n).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(e,t){return g(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:n,helper:o}=this._core;this._validateMessageReactionBusinessCapability();const i=n.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:n,ID:o,conversationType:r,from:a,to:c,clientSequence:u,random:l,time:d,sequence:h}=e;return this._removeMyReactionRecord(o,t),r===s.CONV_C2C?yield function(e,t){return g(this,void 0,void 0,(function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:u})}))}({from:a,to:c,clientSequence:u,random:l,time:d,reactionID:t},this._core):r===s.CONV_GROUP&&(yield function(e,t){return g(this,void 0,void 0,(function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:r},t)}))}({to:c,reactionID:t,sequence:h},this._core)),i.setLogInfo({message:`conversationID:${n} messageID:${o} reactionID:${t}`}).end(),{code:0}}catch(e){const{errorCode:t}=e||{},s=new o.ChatError({functionName:"removeMessageReaction",code:t});i.setError(s).end(),console.error("removeMessageReaction error: ",e)}}))}getAllUserListOfMessageReaction(e){return g(this,void 0,void 0,(function*(){this._validateMessageReactionBusinessCapability();const{message:t,reactionID:s,nextSeq:n=0}=e,o=e.count>100?100:e.count,{conversationID:i}=t,{ssoLog:r,helper:a,constants:c}=this._core;try{let e=null;if(e=i.startsWith(c.OuterConstant.CONV_C2C)?yield function(e){return g(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{from:i,to:r,clientSequence:a,random:c,time:u}=t,l={Reaction:n,NextSeq:s,Count:o,From_Account:i,To_Account:r,MsgKey:`${a}_${c}_${u}`};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:l})}))}({message:t,reactionID:s,nextSeq:n,count:o}):yield function(e){return g(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{sequence:i,to:r}=t,a={Reaction:n,NextSeq:s,GroupId:r,Count:o,MsgSeq:i};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:a})}))}({message:t,reactionID:s,nextSeq:n,count:o}),e){const{Reaction_Account:t,NextSeq:s}=e,o=yield this._getUserProfileList(t);return{code:0,data:{nextSeq:s,isCompleted:0===n,userList:o}}}}catch(e){const{errorCode:t}=e||{},s=new a.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});r.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}}))}getMessageReactions(e){return g(this,void 0,void 0,(function*(){const{constants:t}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:s,maxUserCountPerReaction:n=10}=e,o=s[0];let i=null;const r=new Map,{from:a,to:c,conversationType:u}=o,l=this._generateMessageKeyList(s,r);u===t.OuterConstant.CONV_C2C?i=yield function(e){return g(this,void 0,void 0,(function*(){const{from:t,to:s,messageKeyList:n,maxUserCountPerReaction:o}=e,i={From_Account:t,To_Account:s,MsgKeyList:n,Count:o};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})}))}({from:a,to:c,messageKeyList:l,maxUserCountPerReaction:n}):u===t.OuterConstant.CONV_GROUP&&(i=yield function(e){return g(this,void 0,void 0,(function*(){const{groupId:t,messageSequenceList:s,maxUserCountPerReaction:n}=e,o={GroupId:t,MsgSeqList:s,Count:n};return _o.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:o})}))}({groupId:c,messageSequenceList:l,maxUserCountPerReaction:n}));const{Results:d=[]}=i||{},h=this._extractUserIDsFromReactionResults(d),p=yield this._getUserProfileMap(h);return{code:0,data:{resultList:d.map((e=>{const{ReactionList:t,MsgSeq:s,MsgKey:n}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:n,messageIDMap:r}),reactionList:t.map((e=>{const{Reaction:t,Count:s,Reaction_Account:n,ReactedByMe:o}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:n,userProfileMap:p}),reactedByMyself:1===o}}))}}))}}}))}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){const t=[];return null==e||e.forEach((e=>{const{ReactionList:s=[]}=e;s.forEach((e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)}))})),t}_getUserProfileList(e){return g(this,void 0,void 0,(function*(){var t;try{const s=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return s?s.data:[]}catch(e){return[]}}))}_getUserProfileMap(e){return g(this,void 0,void 0,(function*(){const t=new Map;return(yield this._getUserProfileList(e)).forEach((e=>{const{nick:s,avatar:n,userID:o}=e;t.set(o,{nick:s,avatar:n,userID:o})})),t}))}_recordMessageReactedByMe(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)?this._reactionsMap.get(s).reactedByMe=!0:this._reactionsMap.set(s,{reactedByMe:!0})}_removeMyReactionRecord(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)&&(this._reactionsMap.get(s).reactedByMe=!1)}_recordMessageReactionInfo(e){const{messageID:t,reactionID:s,reactionInfo:n}=e,o=`${t}-${s}`,i=this._reactionsMap.get(o)||{};this._reactionsMap.set(o,Object.assign(Object.assign({},i),n))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(fo))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){const{MsgReactionNotifyList:t}=e,{notificationCenter:s,constants:n}=this._core;t.forEach((e=>g(this,void 0,void 0,(function*(){const{C2CMsgInfo:t,GroupMsgInfo:o,MsgReactionSummary:i}=e,{TinyId:r,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},t),o),u=`${r}-${a}-${c}`,l=this._extractUserIDsFromReactionResults([{ReactionList:i}]),d=yield this._getUserProfileMap(l),h=i.map((e=>{var t;const{Reaction:s,Reaction_Account:n}=e,o=this._generatePartialUserInfo({userIDList:n,userProfileMap:d}),i=n?e.Count:0,r=(null===(t=this._reactionsMap.get(`${u}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:u,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:i,partialUserList:o}}),{reactionID:s,totalUserCount:i,partialUserList:o,reactedByMyself:r}}));s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:u,reactionList:h}})}))))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:n}=this._core,{C2CMsgInfo:o={},GroupMsgInfo:i={},Reaction:r,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:u=0,MsgRandom:l=0}=Object.assign(Object.assign({},o),i),d=`${c}-${u}-${l}`,h=`${d}-${r}`;if(1===a?this._recordMessageReactedByMe(d,r):this._removeMyReactionRecord(d,r),null===(t=this._reactionsMap.get(h))||void 0===t?void 0:t.reactionID){const e=this._reactionsMap.get(h);e.reactedByMyself=1===a,s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:d,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){const s=[];return null==e||e.forEach((e=>{t.has(e)&&s.push(t.get(e))})),s}_generateMessageID(e){const{messageSequence:t,messageKey:s,messageIDMap:n}=e;return s?n.get(s):n.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,n=e[0],{conversationType:o}=n;let i=[];return o===s.OuterConstant.CONV_C2C?i=e.map((e=>{const{clientSequence:s,random:n,time:o,ID:i}=e,r=`${s}_${n}_${o}`;return t.set(r,i),r})):o===s.OuterConstant.CONV_GROUP&&(i=e.map((e=>{const{ID:s,sequence:n}=e;return t.set(n,s),n}))),i}};var Wo=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:o},notificationCenter:i}=e;t.registerApi({apiName:"sendMessageReadReceipt",context:this}),t.registerApi({apiName:"getMessageReadReceiptList",context:this}),t.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(s,o,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return g(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core,n=this._filterValidMessageSendByOther(e);if(0===n.length)throw new t.ChatError({code:s.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:e}=n[0];return e===s.OuterConstant.CONV_C2C?yield function(e){return g(this,void 0,void 0,(function*(){const{common:t,constants:s}=_o.core,n=e[0].conversationID.replace(s.OuterConstant.CONV_C2C,""),o=e.map((e=>{const{from:t,to:s,sequence:n,random:o,time:i,clientTime:r}=e;return{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:o,MsgTime:i,MsgClientTime:r}})),i={Peer_Account:n,C2CMsgInfo:o};return t.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:i})}))}(n):yield function(e){return g(this,void 0,void 0,(function*(){const{common:t,constants:s}=_o.core,n={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:n})}))}(n),{code:0,data:{}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}}))}getMessageReadReceiptList(e){return g(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core;try{const{conversationType:t}=e[0];if(t===s.OuterConstant.CONV_GROUP){const t=this._filterValidMessageSendByMe(e);if((null==t?void 0:t.length)>0){const s=yield function(e){return g(this,void 0,void 0,(function*(){const{common:t,constants:s}=_o.core,n={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:n})}))}(t),{GroupMsgReceiptList:n}=s||{};this._updateGroupMessagesReadReceiptInfo({messageList:e,readReceiptList:n})}}return{code:0,data:{messageList:e}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}}))}getGroupMessageReadMemberList(e){return g(this,void 0,void 0,(function*(){const{constants:t,common:s}=this._core,{message:n,filter:o=bo.READ,cursor:i=""}=e,{conversationID:r,sequence:a,ID:c}=n,u=r.replace(t.OuterConstant.CONV_GROUP,""),l=e.count>=100?100:e.count;try{const e=yield function(e){return g(this,void 0,void 0,(function*(){const{sequence:t,groupID:s,filter:n,cursor:o,count:i}=e,r={MsgSeq:t,GroupId:s,Filter:n,Cursor:o,Num:i};return _o.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:r})}))}({groupID:u,sequence:a,filter:o,cursor:i,count:l});if(e){const{Cursor:t,IsFinish:s,UnreadList:n,ReadList:i}=e,r={cursor:t,isCompleted:1===s,messageID:c,unreadUserIDList:[],readUserIDList:[]};return o===bo.READ?r.readUserIDList=i.map((e=>e.Read_Account)):o===bo.UNREAD&&(r.unreadUserIDList=n.map((e=>e.Unread_Account))),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:n}=e;throw new s.ChatError({code:t,message:n})}}))}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:n}=this._core,{C2cMsgInfo:o,PeerReadTime:i,Peer_Account:r}=e;if(n.isEmpty(o))return;const a=`${s.OuterConstant.CONV_C2C}${r}`;null==o||o.forEach((e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:o}=e,c=`${s}-${n}-${o}`,u=Bo({conversationID:a,messageID:c});u&&!u.readReceiptInfo.isPeerRead&&(u.readReceiptInfo.isPeerRead=!0,u.readReceiptInfo.timestamp=i,t.push({userID:r,messageID:c,isPeerRead:!0,timestamp:i}))})),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,n=new Map;t.forEach((e=>{n.set(e.sequence,e)})),null==s||s.forEach((e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:o}=e,i=n.get(t);i&&(i.readReceiptInfo.readCount=s,i.readReceiptInfo.unreadCount=o)}}))}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:n}=e;n.forEach((e=>{const{MsgBody:{GroupMsgReceiptList:n},GroupInfo:{GroupId:o}}=e,i=`${s.OuterConstant.CONV_GROUP}${o}`;null==n||n.forEach((e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:r,ReadNum:a,UnreadNum:c}=e,u=`${s}-${n}-${r}`,l=Bo({conversationID:i,messageID:u}),d={groupID:o,messageID:u,readCount:0,unreadCount:0};l&&("number"==typeof a&&(l.readReceiptInfo.readCount=a,d.readCount=a),"number"==typeof c&&(l.readReceiptInfo.unreadCount=c,d.unreadCount=c),t.push(d))}))})),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()}))}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:s,status:n}=e;return s===this._core.common.getCurrentUserID()&&n===t.MessageStatus.SUCCESS}))}_filterNeedReadReceiptMessages(e){return e.filter((e=>!0===e.needReadReceipt))}dispose(){const{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:n}=this._core;n.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),n.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Yo(e,t,s){return g(this,void 0,void 0,(function*(){const{common:{buildAndSendPacket:n}}=_o.core,{from:o,to:i,clientSequence:r,random:a,time:c}=e;return n({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:o,To_Account:i,MsgKey:`${r}_${a}_${c}`,OperateType:s,ExtensionList:t}})}))}function zo(e,t,s){return g(this,void 0,void 0,(function*(){const{common:{buildAndSendPacket:n}}=_o.core,{to:o,sequence:i}=e;return n({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:o,MsgSeq:i,OperateType:s,ExtensionList:t}})}))}var Jo=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){this._core=e;const{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:n,LOGOUT:o},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=e;s({apiName:"setMessageExtensions",context:this}),s({apiName:"getMessageExtensions",context:this}),s({apiName:"deleteMessageExtensions",context:this}),t.subscribeInnerEvent(n,i,this._handleMessageExtensionsNotify,this),t.subscribeInnerEvent(o,this.reset,this)}setMessageExtensions(e,t){return g(this,void 0,void 0,(function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:s},ssoLog:n}=this._core,{ID:o,conversationID:i,sequence:r,time:a,conversationType:c}=e,u=n.createSSOLogData({method:"setMessageExtensions"});let l=t;t.length>20&&(l=t.slice(0,20),console.warn("the length of extensions cannot exceed 20"));const d=this._generateServerExtensions(e,l);try{let t;if(c===s.CONV_C2C?t=yield Yo(e,d,Lo):c===s.CONV_GROUP&&(t=yield zo(e,d,Lo)),t){const{resultList:s,successCount:n,failureCount:c}=this._handleModifyMessageExtensions(e,t);return u.setLogInfo({message:`convID:${i} messageID:${o} sequence:${r}\n time:${a} count:${l.length} successCount:${n} failCount:${c}`}).end(),{code:0,data:{extensions:s}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t});throw u.setError(s).end(),s}}))}getMessageExtensions(e){return g(this,void 0,void 0,(function*(){const{utils:{isUndefined:t}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:s,ID:n,sequence:o,time:i}=e,r=this._core.ssoLog.createSSOLogData({method:"getMessageExtensions"});r.setLogInfo({message:`convID:${s} messageID:${n} sequence:${o} time:${i}`});try{let s;this._completedFetchExtensions.has(n)&&(s=this._extensionsLatestSequenceMap.get(n));const o=yield this._fetchMessageExtensions(e,s);return t(s)&&o.length>1&&this._completedFetchExtensions.add(n),r.end(),{code:0,data:{extensions:o}}}catch(e){const{errorCode:t,errorInfo:s=""}=e||{},n=new this._core.common.ChatError({code:t,message:s});throw r.setError(n).end(),n}}))}deleteMessageExtensions(e,t){return g(this,void 0,void 0,(function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:s},constants:{OuterConstant:n},ssoLog:o}=this._core,{conversationType:i,conversationID:r,sequence:a,ID:c,time:u}=e;let l=Po;const d=[];s(t)||(l=No,null==t||t.forEach((e=>{d.push({key:e,value:"",seq:0})})));const h=o.createSSOLogData({method:"deleteMessageExtensions"});h.setLogInfo({message:`convID:${r} messageID:${c} sequence:${a} time:${u} operateType:${l}`});const g=this._generateServerExtensions(e,d);try{let t;if(i===n.CONV_C2C?t=yield Yo(e,g,l):i===n.CONV_GROUP&&(t=yield zo(e,g,l)),t){const{resultList:s,successCount:n,failureCount:o}=this._handleModifyMessageExtensions(e,t);return h.setMoreMessage(`success count:${n} fail count:${o}`),h.end(),{code:0,data:{extensions:s}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t});throw h.setError(s).end(),s}}))}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:n}}=this._core;e.unSubscribeInnerEvent(t,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){const{ID:s}=e,{Seq:n}=t,o=t.ExtensionList||[],i=[];let r=0,a=0,c=[];return o.forEach((e=>{const{ErrorCode:t,Extension:s}=e,{Key:n,Value:o,Seq:u}=s;i.push({code:t,key:n,value:o}),0===t?r++:a++,c.push({key:n,value:o,seq:u})})),this._extensionsLatestSequenceMap.set(s,n),c.length>0&&this._updateLocalExtensions(e.ID,c),{resultList:i,successCount:r,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);const s=this._messageExtensionsMap.get(e);null==t||t.forEach((e=>{const{key:t,seq:n,value:o=""}=e;null==s||s.set(t,{value:o,seq:n})}))}_fetchMessageExtensions(e,t){return g(this,void 0,void 0,(function*(){const{constants:{OuterConstant:s},utils:{isEmpty:n}}=this._core;try{let o;const{conversationType:i,ID:r}=e;if(i===s.CONV_C2C?o=yield function(e,t){const{common:{buildAndSendPacket:s}}=_o.core,{from:n,to:o,clientSequence:i,random:r,time:a}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,StartSeq:t}})}(e,t):i===s.CONV_GROUP&&(o=yield function(e,t){const{common:{buildAndSendPacket:s}}=_o.core,{to:n,sequence:o}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:n,MsgSeq:o,StartSeq:t}})}(e,t)),o){const{LatestSeq:t,ClearSeq:s,CompleteFlag:i}=o,a=(o.ExtensionList||[]).map((e=>({key:e.Key,value:e.Value,seq:e.Seq})));if(this._updateLocalExtensions(r,a),this._clearLocationExtensions(r,s),this._extensionsLatestSequenceMap.set(r,t),1!==i){const t=a[a.length-1].seq+1;return this._fetchMessageExtensions(e,t)}const c=[];if(this._messageExtensionsMap.has(r)){const e=this._messageExtensionsMap.get(r);null==e||e.forEach(((e,t)=>{const{value:s}=e;n(s)||c.push({key:t,value:s})}))}return c}}catch(e){console.error(e)}}))}_clearLocationExtensions(e,t){if(!(t<=0)&&this._messageExtensionsMap.has(e)){const s=this._messageExtensionsMap.get(e);null==s||s.forEach(((e,n)=>{e.seq<=t&&s.delete(n)}))}}_generateServerExtensions(e,t){const{ID:s}=e;if(this._messageExtensionsMap.has(s)){const e=this._messageExtensionsMap.get(s);return t.map((t=>{var s;const{key:n,value:o}=t;let i=0;return(null==e?void 0:e.has(n))&&(i=null===(s=e.get(n))||void 0===s?void 0:s.seq),{Key:n,Value:o,Seq:i}}))}return t.map((e=>({Key:e.key,Value:e.value,Seq:0})))}_validateMessageExtensionBusinessCapability(e){const{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(Io))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){const{SetKVInfo:t,DeleteKVInfo:s,ClearKVInfo:n,MsgOptType:o,TinyId:i,MsgLastSeq:r,ExtensionC2cMsgInfo:a,ExtensionGroupMsgInfo:c}=(null==e?void 0:e.MsgExtensionNotify)||{},u=a||c||{},{MsgClientTime:l,MsgRandom:d}=u,h=`${i}-${l}-${d}`;this._extensionsLatestSequenceMap.set(h,r),o===Lo?this._handleMessageExtensionsUpdated({messageID:h,updateMessageExtensionsInfo:t}):o===No?this._handleMessageExtensionsDeleted({messageID:h,deleteMessageExtensionsInfo:s}):o===Po&&this._handleMessageExtensionsCleared({messageID:h,clearMessageExtensionsInfo:n})}_handleMessageExtensionsUpdated(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,updateMessageExtensionsInfo:o=[]}=e,i=[];o.forEach((e=>{const{MsgKeyValue:t=[]}=e,s=t.map((e=>(i.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq})));this._updateLocalExtensions(n,s)})),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:n,extensions:i}})}_handleMessageExtensionsDeleted(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,deleteMessageExtensionsInfo:o=[]}=e,i=[];o.forEach((e=>{const{MsgKeyValue:t=[]}=e,s=t.map((e=>(i.push(e.Key),{key:e.Key,seq:e.Seq})));this._updateLocalExtensions(n,s)})),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:n,keyList:i}})}_handleMessageExtensionsCleared(e){const{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:n}}=this._core,{messageID:o,clearMessageExtensionsInfo:i=[]}=e,r=[];i.forEach((e=>{const{ClearMsgSeq:t}=e;if(this._messageExtensionsMap.has(o)){(this._messageExtensionsMap.get(o)||[]).forEach(((e,s)=>{e.seq<=t&&!n(e.value)&&r.push(s)}))}this._clearLocationExtensions(o,t)})),t.emitOuterEvent(s,{name:s,data:{messageID:o,keyList:r}})}};const Qo={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{constants:{OuterConstant:t}}=_o.core;return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},Xo={setMessageExtensions:[Qo,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Qo],deleteMessageExtensions:[Qo]},Zo=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=>{const t=function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e);return!0!==t?t:!((null==e?void 0:e.atUserList)&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{utils:{isString:t,isNumber:s}}=_o.core;return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),Xo),ei=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});class ti{constructor(e){this._core=e}deleteMessage(e){return g(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,n={From_Account:this._core.common.getCurrentUserID(),To_Account:t,MsgKeyList:s};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:n})}))}revokeMessage(e){return g(this,void 0,void 0,(function*(){const{to:t,from:s,sequence:n,time:o,random:i}=e,r={MsgInfo:{From_Account:s,To_Account:t,MsgSeq:n,MsgRandom:i,MsgTimeStamp:o}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:r})}))}}class si{constructor(e){this._core=e}deleteMessage(e){return g(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,n={GroupId:t,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:s};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:n})}))}revokeMessage(e){return g(this,void 0,void 0,(function*(){const{to:t,sequence:s}=e,n={GroupId:t,MsgSeqList:[{MsgSeq:s}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:n})}))}}class ni{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:n,tinyID:o,clientTime:i,revokeReason:r,revoker:a}=e;let c={};const{messageDataHandler:u}=this._core.message;return c=u.revokeMessage({conversationID:t,sequence:s,random:n,revoker:a}),c||(c={conversationID:t,sequence:s},o&&i&&n&&(c.ID=`${o}-${i}-${n}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:r,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return g(this,void 0,void 0,(function*(){const t=e.map((e=>e.revoker));try{const s=yield this._fetchUserInfos(t);s&&e.forEach((e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)}))}catch(e){console.debug(e)}}))}_fetchUserInfos(e){return g(this,void 0,void 0,(function*(){var t,s;const n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(s=n.data)||void 0===s?void 0:s.reduce(((e,{userID:t,nick:s,avatar:n})=>(e[t]={nick:s||"",avatar:n||""},e)),{}):null}))}}var oi=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 ti(e),this._messageHelper=new ni(e);const{helper:t}=e;t.registerApi({apiName:"deleteMessage",context:this}),t.registerApi({apiName:"revokeMessage",context:this}),t.registerApi({apiName:"resendMessage",context:this}),t.registerApi({apiName:"findMessage",context:this})}deleteMessage(e){return g(this,void 0,void 0,(function*(){let t=[],s=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:Uo});if(e.forEach((e=>{const{conversationID:i,conversationType:r,status:a,_onlineOnlyFlag:c,sequence:u,random:l,time:d}=e||{};if("success"===a&&i===n&&r===o){if(!c){const e="C2C"===r?`${u}_${l}_${d}`:String(u);t.push(e)}s.push(e)}})),0===t.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};t.length>30&&(t=t.slice(0,30),s=s.slice(0,30));try{return"C2C"===o?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:t}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:t}),this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}}))}revokeMessage(e){return g(this,void 0,void 0,(function*(){var t;const s=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:n,isRevoked:o}=e;let i=null;if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(o)throw new this._core.helper.ChatError({message:"message has been revoked"});s.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(i="C2C"===n?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),i){const{RecallRetList:n}=i,o=(null===(t=null==n?void 0:n[0])||void 0===t?void 0:t.RetCode)||0;if(0!==o)throw new this._core.helper.ChatError({code:o});return s.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"revokeMessage",code:t});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(s).end(),s}}))}resendMessage(e,t){return g(this,void 0,void 0,(function*(){var s,n;return e.isResend=!0,e.status="unSend",null===(n=null===(s=this._core)||void 0===s?void 0:s.apiMap)||void 0===n?void 0:n.sendMessage(e,t)}))}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(e){if(0===e.length)return;const{message:{messageDataHandler:t},common:{isTopic:s},notificationCenter:n,InnerEvent:o}=this._core;e.forEach((e=>{e.isDeleted=!0;const s=t.getLocalMessageList(e.conversationID);null==s||s.forEach((t=>{t.ID===e.ID&&(t.isDeleted=!0)}))}));const{conversationID:i=""}=e[0];s(i)?n.emitInnerEvent(o.TOPIC_MESSAGE_DELETED,i):n.emitInnerEvent(o.MESSAGE_DELETED,i)}_handleRevokeMessageSuccess(e){return g(this,void 0,void 0,(function*(){var t;const s=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{conversationID:n,sequence:o,random:i}=e;this._core.message.messageDataHandler.revokeMessage({conversationID:n,sequence:o,random:i,revoker:s}),yield this._messageHelper.updateRevokerInfo([e])}))}};class ii{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:n}=t;return new ii({index:s,data:n})}constructor(e){this.type=mo.MSG_FACE;const{index:t,data:s}=e;this.content={index:t,data:s}}validateBeforeSend(){var e,t;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(t=this.content)||void 0===t?void 0:t.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{index:n,data:o}=s;return{MsgType:this.type,MsgContent:{Index:n,Data:o}}}}class ri{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Desc:s,Longitude:n,Latitude:o}=t;return new ri({description:s,longitude:n,latitude:o})}constructor(e){this.type=mo.MSG_LOCATION;const{description:t,longitude:s,latitude:n}=e;this.content={description:t,longitude:s,latitude:n}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{description:n,longitude:o,latitude:i}=s;return{MsgType:this.type,MsgContent:{Desc:n,Longitude:o,Latitude:i}}}}var ai=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(mo.MSG_FACE,ii),e.message.messageFactory.registerElementClass(mo.MSG_LOCATION,ri),e.helper.registerApi({apiName:"createFaceMessage",context:this}),e.helper.registerApi({apiName:"createTextAtMessage",context:this}),e.helper.registerApi({apiName:"createForwardMessage",context:this}),e.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(e){if(!e)return null;const{index:t,data:s}=(null==e?void 0:e.payload)||{},n=new ii({index:t,data:s}),o=this._core.common.getCurrentUserID(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:n}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],o=[];t.forEach((t=>{t!==n.MSG_AT_ALL?(e.push({GroupAtAllFlag:So,GroupAt_Account:t}),o.push(t)):(e.push({GroupAtAllFlag:Eo}),o.push(n.MSG_AT_ALL))})),s._groupAtInfoList=e,s.atUserList=o}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:n,conversationType:o,priority:i,payload:r,needReadReceipt:a,receiverList:c,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(r._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(r.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const d=this._core.common.getCurrentUserID(),h=this._core.message.messageFactory.createMessage({to:n,from:d,conversationType:o,isPlaceMessage:0,priority:i,payload:r,needReadReceipt:a,isSupportExtension:l,cloudCustomData:u,receiverList:c});return h.setRelayFlag(!0),h.setElement(r._elements[0]),h}createLocationMessage(e){if(!e)return null;const{description:t,longitude:s,latitude:n}=(null==e?void 0:e.payload)||{},o=new ri({description:t,longitude:s,latitude:n}),i=this._core.common.getCurrentUserID(),r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return r.setElement(o),r}};let ci=class{init(e){this._messageHelper=new ni(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:n},helper:{registerWorkflowStep:o},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:r}}=e;t.subscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this),o(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:t}=e;null==t||t.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return g(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:t}}=e;yield this._parseAndEmitC2CRevokedMessages(t)}catch(e){console.debug(e)}}))}_parseAndEmitC2CRevokedMessages(e){return g(this,void 0,void 0,(function*(){const t=[],{notificationCenter:s,OuterEvent:n,common:{getCurrentUserID:o}}=this._core;e.forEach((e=>{const{MsgRand:s,MsgSeq:n,To_Account:i,From_Account:r,RevokerInfo:{Revoker_Account:a,Revoke_Reason:c,Reason:u=c}}=e,l=o()===r?`C2C${i}`:`C2C${r}`,d=this._messageHelper.generateRevokeMessage({conversationID:l,sequence:n,random:s,revoker:a,revokeReason:u});t.push(d)})),t.length>0&&(yield this._messageHelper.updateRevokerInfo(t),s.emitOuterEvent(n.MESSAGE_REVOKED,{name:n.MESSAGE_REVOKED,data:t}))}))}_handleC2CRevokeMessagesFromUnreadMessageSync(e){return g(this,void 0,void 0,(function*(){const{revokedMessageList:t}=e.result;yield this._parseAndEmitC2CRevokedMessages(t)}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},ui=class{init(e){this._messageHelper=new ni(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:n}}=e;t.subscribeInnerEvent(s,n,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){const{GroupTips:t}=e;null==t||t.forEach((e=>{var t;Array.isArray(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return g(this,void 0,void 0,(function*(){try{const{RevokerInfo:t,MsgBody:{GroupWithdrawInfoArray:s},GroupInfo:n}=e,o=[],i=[],{notificationCenter:r,OuterEvent:a,utils:{isEmpty:c},common:{isCommunity:u}}=this._core;let l=!1;n&&(l=u({groupID:n.GroupId})||!c(n.TopicId)),s.forEach((e=>{const{Random:s,MsgSeq:r,GroupId:a,MsgClientTime:c,TinyId:u,TopicId:d,RevokerInfo:{Revoker_Account:h=(null==t?void 0:t.Revoker_Account)||"",Reason:g=(null==t?void 0:t.Reason)||""}}=e,p=d?`GROUP${d}`:`GROUP${a}`,_=this._messageHelper.generateRevokeMessage({conversationID:p,sequence:r,random:s,tinyID:u,clientTime:c,revoker:h,revokeReason:g});l?(_.revokerInfo.nick=n.From_AccountNick,_.revokerInfo.avatar=n.From_AccountHeadurl,o.push(_)):i.push(_)})),i.length>0&&(yield this._messageHelper.updateRevokerInfo(i),o.push(...i)),0!==o.length&&r.emitOuterEvent(a.MESSAGE_REVOKED,{name:a.MESSAGE_REVOKED,data:o})}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var li=new class{constructor(){this._c2cMessageReceiver=new ci,this._groupMessageReceiver=new ui}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class di{constructor(e){this._core=e;const{constants:t}=e;this._messageHelper=new ni(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){const{recoverRevokeNoticeGroupIDList:t=[]}=e.result,s=this._filterValidGroupIDList(t);if(0===s.length)return;const n=Math.min(Math.ceil(s.length/10),5);Promise.all(Array.from({length:n},((e,t)=>{const n=10*t,o=Math.min(n+10,s.length);return this._fetchGroupRevokeNotice(s.slice(n,o))}))).catch((e=>console.error(e)))}_fetchGroupRevokeNotice(e){return g(this,void 0,void 0,(function*(){var t;try{const s=yield function(e){return g(this,void 0,void 0,(function*(){const{appStore:t,constants:{OuterConstant:s},common:n}=_o.core,o=t.groupStore.getGroupMap(),i={NotifyReqList:e.map((e=>{const t=o.get(e);return{NotifyType:1,Limit:20,Type:n.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*_o.core.common.timeManager.getServerTimeMs()}}))||[]};return n.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:i})}))}(e);if(s){const e=[];null===(t=null==s?void 0:s.NotifyRspList)||void 0===t||t.forEach((t=>{const{GroupId:s,NotifyMsgList:n}=t,o=this._parseServerRevokeMessageList({groupID:s,serverRevokeMessageList:n});e.push(...o)})),0!==e.length&&(yield this._emitMessageRevokedEvent(e))}}catch(e){console.error(e)}}))}_parseServerRevokeMessageList(e){const{serverRevokeMessageList:t,groupID:s}=e,n=[];return null==t||t.forEach((e=>{const{ClientTime:t,MsgSeq:o,Random:i,RevokerInfo:{Revoker_Account:r="",Reason:a=""}}=e,c=`GROUP${s}`,u=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:o,random:i,clientTime:t,revoker:r,revokeReason:a});n.push(u)})),n}_filterValidGroupIDList(e){const{constants:{OuterConstant:t}}=this._core,s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter((e=>{if(!s.has(e))return!1;const n=s.get(e);return(null==n?void 0:n.type)!==t.GRP_AVCHATROOM&&!(null==n?void 0:n.isSupportTopic)})))||[]}_emitMessageRevokedEvent(e){return g(this,void 0,void 0,(function*(){const{notificationCenter:t,OuterEvent:s}=this._core;yield this._messageHelper.updateRevokerInfo(e),t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:e})}))}}class hi{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new ni(e)}getRoamingMessagesByAnchor(e){return g(this,void 0,void 0,(function*(){var t;try{const{conversationID:s,count:n,messageID:o,time:i,direction:r}=e;let a=i,c="";if(!i){const e=o?this._core.message.messageDataHandler.findMessage(o):null;if(a=(null==e?void 0:e.time)||0,o&&this._historyMessageListFetchAnchors.has(s)){const e=this._historyMessageListFetchAnchors.get(s);a=e.lastMessageTime,c=e.messageKey}}const u=s.replace(Fo,""),l=yield function(e){return g(this,void 0,void 0,(function*(){const{peerAccount:t,count:s,lastMessageTime:n,messageKey:o,direction:i}=e,r={Peer_Account:t,MaxCnt:s,WithRecalledMsg:1,LastMsgTime:n,MsgKey:o,GetDirection:i};return _o.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:r})}))}({count:n,lastMessageTime:a,messageKey:c,peerAccount:u,direction:r});if(l){const{MsgList:e=[],Complete:n,MsgKey:o,LastMsgTime:i}=l;this._historyMessageListFetchAnchors.set(s,{messageKey:o,lastMessageTime:i});const r=[];for(let t=0;t<e.length;t++){const s=e[t],n=this._parseMessage(s);r.push(n)}const a=this._core.message.messageHelper.filterValidMessages(r);return{messageList:a,nextReqMessageIDFromServer:null===(t=a[0])||void 0===t?void 0:t.ID,lastMessageTime:i,hasNoMoreHistoryMessage:1===n}}}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){const t=Fo,s=this._core.message.messageHelper.parseServerPushMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}}var gi=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new di(e),this._c2cMessageHistory=new hi(e),this._messageHelper=new ni(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 g(this,void 0,void 0,(function*(){try{let{conversationID:t,nextReqMessageID:s}=e;const n=xo;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const o=this._core.ssoLog.createSSOLogData({method:"getMessageList"}),i=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:i,targetCount:n})){let e=null;if(t.startsWith($o)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:n,direction:vo.FORWARD}):t.startsWith(Fo)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:n,direction:vo.FORWARD})),e){const{nextReqMessageIDFromServer:n,hasNoMoreHistoryMessage:r,messageList:a}=e,c=this._core.message.messageDataHandler.prependLocalMessageList({messageList:a,conversationID:t});!function(e){const{appStore:t,message:s,OuterConstant:n}=_o.core,o=t.conversationStore.getConversation(e),i=s.messageDataHandler.getLocalMessageList(e);if(!o||0===i.length||e===n.CONV_SYSTEM)return;const r=[];for(let e=0;e<i.length;e++)"in"!==i[e].flow?"out"!==i[e].flow||i[e].isRead||i[e].setIsRead(!0):r.push(i[e]);let a=0;if(o.type===n.CONV_C2C){const e=r.slice(-o.unreadCount).filter((e=>e.isRevoked)).length;a=r.length-o.unreadCount-e}else a=r.length-o.unreadCount;for(let e=0;e<a&&!r[e].isRead;e++)r[e].setIsRead(!0)}(t),yield Vo(t),t.startsWith(Fo)&&(yield qo({messageList:a,conversationID:t}));const u=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,c.length+i),l=u.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(l),r&&this._fetchedCompleteConversations.add(t);const d={nextReqMessageID:r?"":String(n),messageList:u,isCompleted:r},h=u.map((e=>e.sequence));return o.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} \n availableLocalMessagesCount: ${i} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}o.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${i}}`}).end();return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:n})}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(t).end(),console.debug(t)}}))}getMessageListHopping(e){return g(this,void 0,void 0,(function*(){var t,s;const{conversationID:n,sequence:o,time:i,direction:r=vo.FORWARD}=e,{isEmpty:a}=this._core.helper;if(![vo.BACKWARD,vo.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=xo}=e;c=c>xo?xo:c;let u=null;if(n.startsWith($o)){if(u=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:n,sequence:o,count:c,direction:r}),u){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,messageList:i,invisibleSequenceList:c}=u;if(this._core.message.messageDataHandler.storeSparseMessageList(i),r===vo.FORWARD){const t=n&&e<1;return{code:0,data:{messageList:i,isCompleted:t,nextMessageSeq:t?"":e}}}if(r===vo.BACKWARD){if(a(i)&&a(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(t=null==i?void 0:i[i.length-1])||void 0===t?void 0:t.sequence)||0,r=(null===(s=null==c?void 0:c[c.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter((e=>e.sequence>=o)),isCompleted:!n,nextMessageSeq:n?Math.max(e,r)+1:""}}}return{code:0,data:u}}}else if(n.startsWith(Fo)&&(u=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:n,count:c+1,time:i,direction:r}),u)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=u;return s||(r===vo.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}}))}clearHistoryMessage(e){return g(this,void 0,void 0,(function*(){var t;const{appStore:s,common:{ChatError:n,getCurrentUserID:o},OuterConstant:{CONV_C2C:i,CONV_GROUP:r},message:a,apiMap:c,ssoLog:u}=this._core,l=s.conversationStore.getConversation(e);if(!l)throw new n({code:ko});const d=u.createSSOLogData({method:"clearHistoryMessage"});d.setLogInfo({message:`convID:${e}`});const h={fromAccount:o()},{type:p}=l;p===i?(h.type=Go,h.toAccount=e.replace(i,"")):p===r&&(h.type=wo,h.toGroupID=e.replace(r,""));try{yield null===(t=null==c?void 0:c.setMessageRead)||void 0===t?void 0:t.call(c,{conversationID:e});const s=yield function(e){return g(this,void 0,void 0,(function*(){const{fromAccount:t,type:s,toAccount:n,toGroupID:o}=e,i={From_Account:t,Type:s,To_Account:n,ToGroupid:o};return _o.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:i})}))}(h);return s&&(d.end(),a.messageDataHandler.deleteConversationMessageList(e),this._clearedConversations.add(e),this._fetchedCompleteConversations.delete(e),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(e),this._updateConversationLastMessage(e)),{code:0,data:{conversationID:e}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:t});throw d.setError(s).end(),s}}))}_updateConversationLastMessage(e){const{appStore:t}=this._core;t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e),{length:n}=s;if(!t)return n;let o=-1;return(null==e?void 0:e.startsWith(Fo))?o=s.findIndex((e=>e.ID===t)):(null==e?void 0:e.startsWith($o))&&(o=s.findIndex((e=>t.includes("-")?e.ID===t:String(e.sequence)===t))),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return g(this,arguments,void 0,(function*({conversationID:e,nextReqMessageID:t,count:s}){const n=this._core.message.messageDataHandler.getLocalMessageList(e),o=n.length;let i=o,r={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=o;return t?t&&(c=n.findIndex((s=>e.startsWith(Fo)?s.ID===t:String(s.sequence)===t)),a=c>s?c-s:0,i=c):a=o>s?o-s:0,r.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),r.messageList=n.slice(a,c),r.isCompleted=i<=s,e.startsWith(Fo)&&(yield Vo(e),yield qo({messageList:r.messageList,conversationID:e})),r}))}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}};var pi=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"translateText",context:this})}translateText(e){return g(this,void 0,void 0,(function*(){try{const{sourceLanguage:t,sourceTextList:s,targetLanguage:n}=e,o=yield function(e,t){return g(this,void 0,void 0,(function*(){var s,n;const{sourceTextList:o,sourceLanguage:i,targetLanguage:r}=e,{store:a,common:c}=t,u={SourceText:o,Source:i,Target:r,FromAccount:null===(s=a.get("login"))||void 0===s?void 0:s.tinyID,SDKAppID:null===(n=a.get("instance"))||void 0===n?void 0:n.sdkAppId},l=yield c.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:u});if(l){const{CmdErrorCode:e,TargetText:t}=l;return{cmdErrorCode:e,translatedTextList:t}}}))}({sourceLanguage:t,sourceTextList:s,targetLanguage:n},this._core);if(o){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=o;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}}))}};var _i=new class{init(e){this._core=e,e.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(e){return g(this,void 0,void 0,(function*(){var t,s;const{message:n,language:o=Co.ZH_PY}=e;let{url:i}=n.payload||{};const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userID;n.from===r&&"out"===n.flow&&(i=n.payload.remoteAudioUrl),this._validateVoiceFormat(i);const a=(null===(s=Do.exec(i))||void 0===s?void 0:s[1])||"mp3",c=Ro[o]||To;try{const e=yield function(e){var t;const{store:s,common:n}=_o.core,{url:o,format:i,serverLanguageType:r}=e,a={BytesUrl:o,BytesEngServiceType:r,BytesVoiceFormat:i,Uint32Sdkappid:null===(t=s.get("instance"))||void 0===t?void 0:t.sdkAppId,Uint64SourceType:0};return n.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:a})}({url:i,format:a,serverLanguageType:c});if(e){const{CmdErrorCode:t,BytesResult:s}=e;if(0===t.ErrorCode)return{code:0,data:{result:s}};throw{code:t.ErrorCode,message:t.ErrorInfo}}}catch(e){const{code:t,message:s}=e||{},n=new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s});console.error(n),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(n).end()}}))}_validateVoiceFormat(e){if(!Do.test(e))throw new this._core.common.ChatError({code:2119})}};class mi{constructor(e){const{constants:t,common:s,utils:n}=_o.core,{CONV_C2C:o,CONV_GROUP:i}=t.OuterConstant,{ID:r,tinyID:a,from:c,to:u,clientTime:l=s.timeManager.getServerTimeSeconds()||0,random:d,sequence:h,cloudCustomData:g="",nick:p="",avatar:_="",clientSequence:m,conversationType:v,groupID:f,_elements:I,time:S}=e;this.ID=r||`${a}-${l}-${d}`,this.messageRandom=d,this.from=c,this.messageSender=c,this.time=S,this.messageSequence=h,this.clientSequence=m||h,this.clientTime=l,this.cloudCustomData=g,this.messageReceiver=u,this.avatar=_,this.nick=p;const E=n.deepCopyWithMethods(I);E.forEach((e=>{e.payload=e.content,delete e.content})),this.messageBody=E,r?v.startsWith(o)?this.receiverUserID=u:v.startsWith(i)&&(this.receiverGroupID=u):f?(this.receiverGroupID=f,this.messageReceiver=f):u&&(this.receiverUserID=u,this.messageReceiver=u)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map((e=>e.transformToServerFormat({isMergerMessage:!0}))):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class vi{static parseServerPushElement(e){const{MsgContent:t}=e,{MsgList:s=[],CompatibleText:n,AbstractList:o,Title:i,PbMsgKey:r,JsonMsgKey:a}=t||{},c=s.map((e=>Ko(e)));return new vi({messageList:c,title:i,abstractList:o,compatibleText:n,pbDownloadKey:r,downloadKey:a})}constructor(e){this.type=_o.core.constants.OuterConstant.MSG_MERGER;const{messageList:t,title:s,abstractList:n,compatibleText:o,pbDownloadKey:i="",downloadKey:r="",version:a=0,layersOverLimit:c=!1}=e,u=[];t.forEach((e=>{if(e){const t=new mi(e);u.push(t)}})),this.content={messageList:u,title:s,abstractList:n,compatibleText:o,version:a,downloadKey:r,pbDownloadKey:i,layersOverLimit:c}}validateBeforeSend(){const{isEmpty:e}=_o.core.helper;return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{abstractList:n,compatibleText:o,downloadKey:i,layersOverLimit:r,pbDownloadKey:a,title:c,version:u,messageList:l}=s;return{MsgType:this.type,MsgContent:{AbstractList:n,CompatibleText:o,JsonMsgKey:i,LayersOverLimit:r,PbMsgKey:a,Title:c,Version:u,MsgList:jo(l)}}}}var fi=new class{init(e){this._core=e;const{message:t,helper:s,constants:{OuterConstant:n}}=e;t.messageFactory.registerElementClass(n.MSG_MERGER,vi),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===n.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){const{common:t}=this._core;if(!e)return null;const s=new vi(e.payload),n=t.getCurrentUserID(),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return o.setRelayFlag(!0),o.setElement(s),o}sendMessage(e,t){return g(this,void 0,void 0,(function*(){var s,n,o;try{const i=function(e){let t="utf-8";_o.core.helper.IN_BROWSER&&document&&(t=document.charset.toLowerCase());let s,n=0,o=0;if(o=e.length,"utf-8"===t||"utf8"===t)for(let t=0;t<o;t++)s=e.codePointAt(t),s<=127?n+=1:s<=2047?n+=2:s<=65535?n+=3:(n+=4,t++);else if("utf-16"===t||"utf16"===t)for(let t=0;t<o;t++)s=e.codePointAt(t),s<=65535?n+=2:(n+=4,t++);else n=e.replace(/[^\x00-\xff]/g,"aa").length;return n}(JSON.stringify(e));let r=e,a=null;if(i>11264){r=this._core.utils.deepCopyWithMethods(e);try{const{JsonMsgKey:e,PbMsgKey:t}=yield function(e){return g(this,void 0,void 0,(function*(){const{payload:{messageList:t}}=e,s={MsgList:jo(t)};return _o.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:s})}))}(r),{payload:s}=r;a=new vi(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(a)}catch(e){console.error(e)}}const{data:{message:c}}=yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(r,t);return a&&c.setElement(e._elements),{code:0,data:{message:c}}}catch(e){throw console.error(e),e}}))}downloadMergerMessage(e){return g(this,void 0,void 0,(function*(){try{const t=e.payload,{downloadKey:s,pbDownload:n,type:o,messageList:i}=t,r=h(t,["downloadKey","pbDownload","type","messageList"]),a=yield function(e){return g(this,void 0,void 0,(function*(){return _o.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})}))}(s),{MsgList:c}=a||{},u=null==c?void 0:c.map((e=>{const t=Ko(e);return new mi(t)}));return"function"==typeof e.isOnlineMessage?e.setElement({type:e.type,content:Object.assign({messageList:u},r)}):(e.payload.messageList=u,e.payload.downloadKey="",e.payload.pbDownloadKey=""),e}catch(e){console.error(e)}}))}};var Ii=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,_o.init(e),oi.init(e),ai.init(e),li.init(e),gi.init(e),Ho.init(e),pi.init(e),_i.init(e),Wo.init(e),fi.init(e),Jo.init(e),e.helper.registerValidateConfig({auth:ei,params:Zo}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),li.dispose(),gi.dispose(),Wo.dispose(),Jo.dispose()}_reset(){gi.reset()}};var Si=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,t){return g(this,void 0,void 0,(function*(){var s;const{isEmpty:n}=null===(s=this._core)||void 0===s?void 0:s.utils,{downloadUrl:o="",method:i="PUT",url:r,qs:a,headers:c={},resources:u,dataType:l="text",uploadByIP:d,uploadIP:h}=e;let g=r;if(a){const e=this._queryString(a);e&&(g+=`${g.includes("?")?"&":"?"}${e}`)}const p=new XMLHttpRequest;p.open(i.toUpperCase(),g,!0),p.responseType=l;const _=Object.assign({},c);if(d&&h&&(_.host=h),!n(_))for(const e in _)_.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,_[e]);return p.onload=()=>{const s=this._getResponseBody(p,o,d&&h),n=this._buildResponse(p,s);if(200===p.status)t(null,n);else{if(h&&!g.includes(h))return e.url=this._domainName2IP(g,h),e.uploadByIP=!0,this.request(e,t);t({code:p.status,message:JSON.stringify(p.responseText)},n)}},p.onerror=()=>{const e=this._getResponseBody(p,o,d&&h),s=this._buildResponse(p,e),n={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};t(n,s)},e.onProgress&&p.upload&&(p.upload.onprogress=t=>{const{total:s,loaded:n}=t,o=Math.min(Math.floor(100*n/s),100);e.onProgress({total:s,loaded:n,percent:o/100})}),p.send(u),p}))}_buildResponse(e,t){const s={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,n]=e.split(":").map((e=>e.trim()));s[t.toLowerCase()]=n}})),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(e,t="&",s="="){var n;const{isEmpty:o,isPlainObject:i}=null===(n=this._core)||void 0===n?void 0:n.utils;return o(e)?"":i(e)?Object.keys(e).map((n=>{const o=encodeURIComponent(n)+s;return Array.isArray(e[n])?e[n].map((e=>o+encodeURIComponent(e))).join(t):o+encodeURIComponent(e[n])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const Ei=["unknown","image","video","audio","log"];var Ci=new class{init(e){this._core=e}request(e,t){var s;const{MINI_APP_NAMESPACE:n,IN_ALIPAY_MINI_APP:o,IN_UNI_IOS_APP:i}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:r="",headers:a={},url:c,downloadUrl:u=""}=e;let l=c,d=null;const g=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const p=decodeURIComponent(g[3]),_=p.includes("?")?p.split("?")[0]:p||"",m={key:e.fileKey||_,success_action_status:200,"Content-Type":""},v={};if(i){const[e,t]=c.split("?sign=");t&&(l=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let f={url:l,header:a,name:"file",filePath:r,formData:Object.assign(Object.assign({},m),v),timeout:e.timeout||3e5};if(o){const t=h(f,["name"]);f=Object.assign(Object.assign({},t),{fileName:"file",fileType:e.fileType?Ei[e.fileType]:"image"})}return d=n.uploadFile(Object.assign(Object.assign({},f),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})}})),d.onProgressUpdate&&d.onProgressUpdate((t=>{e.onProgress&&e.onProgress({total:t.totalBytesExpectedToSend||0,loaded:t.totalBytesSent||0,percent:t.progress?Math.floor(t.progress)/100:0})})),d}_handleResponse(e){const{downloadUrl:t,response:s,callback:n}=e,o={};if(s.header)for(const e in s.header)s.header.hasOwnProperty(e)&&(o[e.toLowerCase()]=s.header[e]);const i=+s.statusCode;200===i?n(null,{statusCode:i,headers:o,data:Object.assign(Object.assign({},s.data),{location:t})}):n({code:i,message:JSON.stringify(s.data)},{statusCode:i,headers:o,data:void 0})}};function Mi(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function yi(e){const t=e||99999999;return Math.round(Math.random()*t)}function Oi(e,t=!0,s=!0){const n=Date.now();return t?s?n-e+" ms":`${Math.round((n-e)/1e3)} s`:s?n-e:Math.round((n-e)/1e3)}function Ai(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function Ti(e,t){return Math.round(Number(e)*10**t)/10**t}function Ri(e){const t=1024,s=1048576;return e<t?`${e}B`:e<s?`${Math.floor(e/t)}KB`:`${Math.floor(e/s)}MB`}function Di(e){if(e<=1048576){return`${Ti(e/1024,1)}KB/s`}return`${Ti(e/1048576,1)}MB/s`}const bi="TIMImageElem",Li="TIMSoundElem",Ni="TIMFileElem",Pi="TIMVideoFileElem",Gi="RichMediaMessagePlugin",wi=["rich.my-imcloud.com","imrich.qcloud.com"],Ui=1,ki=2,Fi=3;var $i;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}($i||($i={}));const xi={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 qi=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[s,n]=e.split("?");if(!n)return s;const o=n.split("&").reduce(((e,s)=>{const[n,o]=s.split("=");return n&&n!==t&&(e[n]=o||""),e}),{}),i=Object.keys(o).map((e=>`${e}${o[e]?`=${o[e]}`:""}`)).join("&");return i?`${s}?${i}`:s}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(xi).some((t=>t.test(e)))}extractFileFromInput(e){return Mi(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return g(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:n?this._probeImageDimensionsWeb(e):s?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:s}=t;return"0"!==s}getFileDNList(){var e;let t=wi;const s=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:n}=s;if(void 0===n)return t;try{JSON.parse(n).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=wi}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var s;let n=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(s=this._core)||void 0===s?void 0:s.utils.randomString()}`;if(t)return`${n}.${t}`;const o=e.name||e.value||e.url||e.tempFilePath,i=o&&o.slice(o.lastIndexOf(".")+1);return i&&(n=`${n}.${i}`),n}processResourceUrl(e){if(!e)return"";let t=e;const s=this.getFileDownloadProxy(),n=this.getAuthKey(),o=this.getFileDNList();s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s)));const i=n&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){const n=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),o=n&&n[2]||"";if(o.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(o.endsWith(t[e])){s=!0;break}}return s}(t,o);return i&&(t=t.indexOf("?")>-1?`${t}&authKey=${n}`:`${t}?authKey=${n}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}}isEmpty(e){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return s(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:s,IE_VERSION:n}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||s&&9===n}_probeImageDimensionsWeb(e){return new Promise((t=>{const s=new Image,n=()=>{s.onload=null,s.onerror=null,s.src=""};s.onload=()=>{t({width:s.width,height:s.height}),n()},s.onerror=()=>{t({width:0,height:0}),n()},s.src=e}))}};var Vi=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?Ci:Si,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return g(this,void 0,void 0,(function*(){const t=`${Gi} uploadToCOS`,{file:s}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const n=Date.now(),o=yield this._createCosOptions(e),i=yield this._uploadFile(o);this._handleUploadError(i,e);const r=this._createUploadResult(s,i),a=Date.now()-n,c=Ri(s.size),u=`size:${c} time:${a}ms speed:${Di(1e3*s.size/a)}`;return console.log(`${t} ok. name:${s.name} ${u}`),{uploadOptions:o,response:r}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var s,n;const{ChatError:o}=null===(s=this._core)||void 0===s?void 0:s.helper;if(403===e.statusCode)throw Oi(Date.now(),!1),t.url,(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.uploadIP)&&e.data.uploadIP,new o({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:Oi(Date.now(),!1),uploadSpeed:Di(1e3*e.size/Oi(Date.now(),!1))}}_createCosOptions(e){return g(this,void 0,void 0,(function*(){const{fileName:t,resources:s,uploadMethod:n}=this._prepareUploadParams(e),o=this._isC2CConversation(e.message.conversationID)?1:2;try{const i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:n,duration:this.duration,userID:e.message.from,conversationType:o}),{uploadUrl:r,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d}=i,h=!qi.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(r),fileType:this.uploadFileType,fileName:t,resources:s,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,uploadIP:h||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${Gi} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:s,IN_RN_APP:n}=qi.getPlatformFlags(),o=s||n,i=o&&e.message.type!==Ni,{name:r}=t,a=r.slice(r.lastIndexOf(".")),c=`${yi(999999)}${a}`;return{fileName:Ai(i?t.name:c),resources:o?t.url:t,uploadMethod:o?1:0}}_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 g(this,void 0,void 0,(function*(){const t=`${Gi} fetchCosSignatureUrl`,s=qi.isSimpleCos(),n=this._prepareCosRequestData(e),o=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,t,s){return g(this,void 0,void 0,(function*(){try{const{helper:n,channel:o}=s,i=n.generateCosSpecifiedData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(o,n,this._core);this.fetchCosTryCount=0;const i=this._processResponse(e);return console.log(`${t} ok. isSimpleCos:${s} data:`,i),i||{}}catch(s){if(console.error(`${t} failed, error:`,s),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,s}}))}_processResponse(e){var t;const s=qi.isSimpleCos(),n=s?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!n)return{};if(s){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:o,str_download_url:i,str_upload_url:r,str_snapshot_url:a,str_file_key:c}=n;return{uploadIP:e,preSig:t,fileID:s,existFlag:o,downloadUrl:i,uploadUrl:r,requestSnapshotUrl:a,fileKey:c}}const{upload_url:o,download_url:i,snapshot_url:r,thumb_url:a,large_url:c,file_key:u}=n;return{uploadUrl:o,downloadUrl:i,requestSnapshotUrl:r,thumbUrl:a,largeUrl:c,fileKey:u}}_prepareCosRequestData(e){return qi.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:qi.getPlatform(),uint32_sdkappid:qi.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return g(this,void 0,void 0,(function*(){return new Promise(((t,s)=>{this.httpRequest.request(e,((n,o)=>{n&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(n)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(s)):(this.uploadFileTryCount=0,n?s(n):t(o))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,s;try{const n=null===(t=e.error)||void 0===t?void 0:t.Code,o=null===(s=e.error)||void 0===s?void 0:s.Message;return"RequestTimeTooSkewed"===n||"AccessDenied"===n&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(!o)return!1;const i=Date.now(),r=Date.parse(o);return Math.abs(i+this.systemClockOffset-r)>=3e4}_syncSystemClock(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(o){const e=Date.now(),t=Date.parse(o);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=qi.getFileUploadProxy();let s=e;return t&&(s=e.replace(/^https:\/\/[^/]+/,t)),s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const Bi=2108,ji=2251,Ki=2252,Hi=["jpg","jpeg","gif","png","bmp","image","webp"],Wi=20971520,Yi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class zi{constructor(e,t){this.instanceID=yi(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=qi.addAuthToUrl(e.imageUrl||e.url||""),this.url=qi.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=qi.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Ji(e){const{originUrl:t,originWidth:s,originHeight:n,min:o=198}=e,i=parseInt(s)||0,r=parseInt(n)||0,a={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)a.url=t,a.width=i,a.height=r;else{r<=i?(a.width=Math.ceil(i*o/r),a.height=o):(a.width=o,a.height=Math.ceil(r*o/i));const e=t&&t.indexOf("?")>-1?`${t}&`:`${t}?`;a.url=198===o?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===t){return h(a,["url"])}return a}class Qi{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=bi;const{uuid:t,file:s,imageFormat:n,imageInfoArray:o=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(s),this.content={imageFormat:n,uuid:t,imageInfoArray:[]},this.initImageInfoArray(o),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:s,ImageInfoArray:n,UUID:o}=t,i=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(n);return new Qi({imageFormat:s,imageInfoArray:i,uuid:o})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:s,IN_RN_APP:n,IN_BROWSER:o}=qi.getPlatformFlags();return e?((s||n)&&(t=e.url),o&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let s=0;s<3;s++){const n=e[s]||Object.assign({},t),o=new zi(n,this._imageMemoryURL);o.setSizeType(s+1),o.setType(s),this.addImageInfo(o)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[s,...n]=t.imageUrl.split("://"),o=n.join("://");e.includes(s)||t.setImageUrl(`https://${o}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=Yi[e.toUpperCase()]||Yi.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let s;for(let n=0;n<t;n++)s=this.content.imageInfoArray[n],e[n].size&&(s.size=e[n].size),e[n].url&&s.setImageUrl(e[n].url),e[n].width&&(s.width=e[n].width),e[n].height&&(s.height=e[n].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],Ji({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:n,imageFormat:o,imageInfoArray:i}=s;return{MsgType:this.type,MsgContent:{ImageFormat:o,ImageInfoArray:this.parseImageInfoArray(i),UUID:n}}}parseImageInfoArray(e){return e.map((e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:qi.removeAuthToUrl(e.imageUrl)})))}}var Xi=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createImageMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(bi,Qi),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${Gi} createImageMessage options:`,e);const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a=this._processImage(e);e.payload.file=a;const c={imageFormat:Yi.UNKNOWN,uuid:qi.generateUUID(a),file:a,imageInfoArray:[]},u=new Qi(c);return r.setElement(u),this._messageOptionsMap.set(r.clientSequence,e),console.log(`${Gi} createImageMessage OK imageMessage:`,r),o.end(),r}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${Gi} createImageMessage error:`,e),e}}upload(e){return g(this,void 0,void 0,(function*(){console.log(`${Gi} uploadImage message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(s);const n=yield this._performImageUpload(t,e,s),o=this._generateImageInfo(n);return t.updateImageFormat(null==n?void 0:n.fileType),t.updateImageInfoArray(o),e}))}_performImageUpload(e,t,s){return g(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:Ui,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{uploadOptions:i,response:r}=yield Vi.uploadToCOS(o);return this._parseResponse(i,r)}))}_generateImageInfo(e){console.log(`${Gi} generateImageInfo`);const{location:t,fileSize:s,width:n,height:o,smallImageUrl:i,smallImageWidth:r,smallImageHeight:a,largeImageUrl:c,largeImageWidth:u,largeImageHeight:l,imageInfoArray:d}=e,h=qi.addAuthToUrl(t),g={size:s,url:h,width:n,height:o};return(null==d?void 0:d.length)>0?this._processImageInfoArray(d,s):i&&c?[Object.assign({},g),{largeImageUrl:c,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:r,smallImageHeight:a}]:[Object.assign({},g),this._generateThumbInfo(h,n,o,720),this._generateThumbInfo(h,n,o,198)]}_generateThumbInfo(e,t,s,n){return Ji({originUrl:e,originWidth:t,originHeight:s,min:n})}_processImageInfoArray(e,t){let s,n,o;for(const i of e)1===i.type?(n=i,n.size=t):2===i.type?(o=i,o.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},o),Object.assign({},n)]}_parseResponse(e,t){return g(this,void 0,void 0,(function*(){console.log(`${Gi} parseResponse`);try{const{thumbUrl:s,largeUrl:n,downloadUrl:o}=e;s&&n&&(yield this._getImageInfoByUrl(s,t,"thumb"),yield this._getImageInfoByUrl(n,t,"large"));if(qi.isSimpleCos()&&!qi.isPrivateNetWork()&&(yield this._getImageInfoArray(o,t),null==t?void 0:t.uploadIP)){const e=this._extractDomainFromUrl(o);e&&(yield this._getDownloadIP(e,t))}return t}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,t,s){return g(this,void 0,void 0,(function*(){try{const n=qi.addAuthToUrl(e),{width:o=0,height:i=0}=yield qi.probeImageWidthHeight(n);t.width=o,t.height=i,"thumb"===s?(t.smallImageUrl=e,t.smallImageWidth=o,t.smallImageHeight=i):(t.largeImageUrl=e,t.largeImageWidth=o,t.largeImageHeight=i)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:ji});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:n}=e.payload;return n=s?this._processMiniAppImageFile(n):this._processWebImageFile(n),n}catch(e){throw console.warn(`${Gi} _processImage error:`,e),e}}_processMiniAppImageFile(e){Mi(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,n=qi.extractFileFromInput(e);if(!n)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return n}_getDownloadIP(e,t){return g(this,void 0,void 0,(function*(){const s=`${Gi} getDownloadIP domainName: ${e}`;try{const n=yield function(e,t){return g(this,void 0,void 0,(function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_final_ip",i={str_domain:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!n||!n.str_final_ip)return;console.log(`${s} ok. downloadIP:${n}`);const o=t.location.split("/");o[0]=n.str_final_ip,t.location=o.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,t){return g(this,void 0,void 0,(function*(){const s=`${Gi}._getImageInfoArray`;try{const n=yield function(e,t){return g(this,void 0,void 0,(function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_imageinfo",i={str_image_url:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return t.imageInfoArray=this._processImageInfoResponse(n),console.log(`${s} ok`),t}catch(e){throw t.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map((e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format})))}_checkImageType(e){const{utils:t,helper:s}=this._core;let n="";if(t.IN_MINI_APP&&(n=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(n=e.name.slice(e.name.lastIndexOf(".")+1)),Hi.indexOf(n.toLowerCase())<0)throw new s.ChatError({code:Ki})}_checkImageSize(e){const{utils:t,helper:s}=this._core;let n=0;if(n=(t.IN_MINI_APP,e.size),0===n)throw new s.ChatError({code:Bi});if(n>=Wi)throw new s.ChatError({message:`File size exceeds limit: ${Ri(Wi)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Zi=2108,er=2401,tr="2.5.0",sr="1.18.0",nr=104857600;function or(e,t){const s=e.split("."),n=t.split("."),o=Math.max(s.length,n.length);for(;s.length<o;)s.push("0");for(;n.length<o;)n.push("0");for(let e=0;e<o;e++){const t=parseInt(s[e]),o=parseInt(n[e]);if(t>o)return 1;if(t<o)return-1}return 0}class ir{constructor(e){this.type=Ni,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:qi.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:s,Url:n,FileName:o,FileSize:i,UUID:r}=t;return new ir({downloadFlag:s,url:n,fileName:o,fileSize:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:n,downloadFlag:o,fileUrl:i,fileName:r,fileSize:a}=s;return{MsgType:this.type,MsgContent:{Download_Flag:o,Url:qi.removeAuthToUrl(i),FileName:r,FileSize:a,UUID:n}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(qi.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${yi(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 rr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createFileMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Ni,ir),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${Gi} createFileMessage options:`,e),this._checkVersion();const i=this._processFile(e.payload.file);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),c={uuid:qi.generateUUID(i),file:i},u=new ir(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${Gi} createFileMessage success fileMessage:`,a),o.end(),a}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${Gi} createFileMessage error:`,e),e}}upload(e){return g(this,void 0,void 0,(function*(){console.log(`${Gi} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const s=e.getElements()[0],n=yield this._performFileUpload(s,e,t),o=qi.addAuthToUrl(null==n?void 0:n.location);return s.updateFileUrl(o),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:er});if(e.size>nr)throw new s({message:`File size exceeds limit: ${Ri(nr)}`});if(0===e.size)throw new s({code:Zi})}_performFileUpload(e,t,s){return g(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:Ui,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield Vi.uploadToCOS(o);return i}))}_processFile(e){var t,s;const{IN_BROWSER:n,IN_RN_APP:o,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:c}=null===(s=this._core)||void 0===s?void 0:s.helper;if(n||a){const t=qi.extractFileFromInput(e);if(!t)throw new c({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(i||r){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return o?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:s,IN_MINI_APP:n,IN_WX_MINI_APP:o,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:r}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(n){if(!(o||i||r))throw new a({message:"Unsupported mini app environment"});const e=s.getSystemInfoSync().SDKVersion;if(o&&or(e,tr)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${tr} or higher`})}if(i&&or(e,sr)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${sr} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const ar=2108,cr=2352,ur=["mp4","quicktime","mov"],lr=104857600;class dr{constructor(e){this.type=Pi,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:qi.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:qi.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:qi.addAuthToUrl(e.thumbUrl),snapshotUrl:qi.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:s,VideoFormat:n,VideoSecond:o,VideoSize:i,VideoDownloadFlag:r,VideoUUID:a,ThumbUUID:c,ThumbFormat:u,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:h,SnapshotHeight:g,ThumbSize:p,SnapshotSize:_,ThumbDownloadFlag:m,ThumbUrl:v,SnapshotUrl:f}=t;return new dr({videoUrl:s,videoFormat:n,videoSecond:o,videoSize:i,videoDownloadFlag:r,videoUUID:a,thumbUUID:c,thumbFormat:u,thumbWidth:l,snapshotWidth:d,thumbHeight:h,snapshotHeight:g,thumbSize:p,snapshotSize:_,thumbDownloadFlag:m,thumbUrl:v,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:s,snapshotHeight:n}=e;qi.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),qi.isEmpty(s)||(this.content.thumbWidth=this.content.snapshotWidth=Number(s)),qi.isEmpty(n)||(this.content.thumbHeight=this.content.snapshotHeight=Number(n))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{remoteVideoUrl:n,videoFormat:o,videoSecond:i,videoSize:r,videoDownloadFlag:a,videoUUID:c,thumbUUID:u,thumbFormat:l,thumbWidth:d,snapshotWidth:h,thumbHeight:g,snapshotHeight:p,thumbSize:_,snapshotSize:m,thumbDownloadFlag:v,thumbUrl:f,snapshotUrl:I}=s;return{MsgType:this.type,MsgContent:{VideoUrl:qi.removeAuthToUrl(n),VideoFormat:o,VideoSecond:i,VideoSize:r,VideoDownloadFlag:a,VideoUUID:c,ThumbUUID:u,ThumbFormat:l,ThumbWidth:d,SnapshotWidth:h,ThumbHeight:g,SnapshotHeight:p,ThumbSize:_,SnapshotSize:m,ThumbDownloadFlag:v,ThumbUrl:qi.removeAuthToUrl(f),SnapshotUrl:qi.removeAuthToUrl(I)}}}}var hr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createVideoMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Pi,dr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${Gi} createVideoMessage options:`,e);const i=this._processVideo(e);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),c={videoFormat:i.videoFile.type,videoSecond:Ti(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:qi.generateUUID(i.videoFile),thumbUUID:qi.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},u=new dr(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),o.end(),a}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${Gi} createVideoMessage error:`,e),e}}upload(e){return g(this,void 0,void 0,(function*(){console.log(`${Gi} uploadVideo message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(s);const n=yield this._performVideoUpload(t,e,s),{location:o,snapshotInfo:i}=n,r=qi.addAuthToUrl(o);return t.updateVideoUrl(r),qi.isEmpty(i)||t.updateSnapshotInfo(i),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>lr)throw new s({message:`File size exceeds limit: ${Ri(lr)}`});if(0===e.videoFile.size)throw new s({code:ar});if(-1===ur.indexOf(e.videoFile.type))throw new s({code:cr})}_performVideoUpload(e,t,s){return g(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:ki,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i,uploadOptions:r}=yield Vi.uploadToCOS(o);return{snapshotInfo:yield this._getSnapshotInfoByUrl(r.requestSnapshotUrl),location:i.location}}))}_processVideo(e){var t,s;try{const{ChatError:n}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:o,IN_BROWSER:i}=null===(s=this._core)||void 0===s?void 0:s.utils;let{file:r}=e.payload,a={};if(o&&(a=this._processMiniVideoFile(r),r.name=a.name,r.url=a.url),i){const e=qi.extractFileFromInput(r);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});r=e,a=this._processWebVideoFile(r)}return r.videoFile=a,r.thumbUrl="",r.thumbSize=0,r}catch(e){throw console.warn(`${Gi} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,s;const{IN_ALIPAY_MINI_APP:n}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:o}=null===(s=this._core)||void 0===s?void 0:s.helper;if(n)throw new o({message:"VideoUnsupportedInAlipay"});if(Mi(e))throw new o({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:s=1,duration:n=0,type:o}=e,i=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:n,type:i}}_getSnapshotInfoByUrl(e){return g(this,void 0,void 0,(function*(){try{console.log(`${Gi} _getSnapshotInfoByUrl url:`,e);const t={version:1,platform:qi.getPlatform(),cover_name:Ai(yi(99999)),snapshot_url:e},s=yield function(e,t){return g(this,void 0,void 0,(function*(){try{const s="im_cos_msg.video_cover",{helper:n,channel:o}=t,i=n.generateCosSpecifiedData({servcmd:s,data:e}),r=`${i.head.seq}${s}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(t,this._core),{download_url:n}=s||{};if(console.log(`${Gi} _getSnapshotInfoByUrl OK snapshotUrl:`,n),qi.isEmpty(n))return{};const o=qi.addAuthToUrl(n),{width:i=0,height:r=0}=yield qi.probeImageWidthHeight(o);return{snapshotUrl:o,snapshotWidth:i,snapshotHeight:r}}catch(e){throw console.error(`${Gi} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class gr{constructor(e){this.uploadProgress=0,this.type=Li,this.content={downloadFlag:2,second:e.second,size:e.size,url:qi.addAuthToUrl(e.url),remoteAudioUrl:qi.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:s,Download_Flag:n,Second:o,Size:i,UUID:r}=t;return new gr({url:s,downloadFlag:n,second:o,size:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:n,downloadFlag:o,remoteAudioUrl:i,size:r,second:a}=s;return{MsgType:this.type,MsgContent:{Url:qi.removeAuthToUrl(i),Download_Flag:o,Second:a,Size:r,UUID:n}}}}const pr=2108,_r=2300,mr=20971520;var vr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createAudioMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Li,gr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${Gi} createAudioMessage options:`,e);let{file:i}=e.payload;i=this._processAudioFile(e.payload.file),e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),c={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:qi.generateUUID(i)},u=new gr(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),o.end(),a}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${Gi} createAudioMessage error:`,e),e}}upload(e){return g(this,void 0,void 0,(function*(){console.log(`${Gi} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const s=e.getElements()[0],n=yield this._performAudioUpload(s,e,t),o=qi.addAuthToUrl(null==n?void 0:n.location);return s.updateAudioUrl(o),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:_r});if(e.size>mr)throw new s({message:`File size exceeds limit: ${Ri(mr)}`});if(0===e.size)throw new s({code:pr})}_performAudioUpload(e,t,s){return g(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:Fi,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield Vi.uploadToCOS(o);return i}))}_processAudioFile(e){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=null===(t=this._core)||void 0===t?void 0:t.utils;return s?this._processMiniFile(e):n?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const fr={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}},Ir={createImageMessage:fr,createAudioMessage:fr,createVideoMessage:fr,createFileMessage:fr},Sr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Er={[bi]:Xi,[Ni]:rr,[Pi]:hr,[Li]:vr};var Cr=new class{constructor(){this.name="RichMediaMessage"}install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:n,MSG_VIDEO:o}}}=e;Xi.init(e),rr.init(e),hr.init(e),vr.init(e),Vi.init(e),qi.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,n,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Sr,params:Ir})}sendMessage(e,t){return g(this,void 0,void 0,(function*(){var s,n,o;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return g(this,void 0,void 0,(function*(){var t,s;if(!0!==e._relayFlag)try{const t=Er[e.type];if(t){const s=this._core.ssoLog.createSSOLogData({method:"upload"});s.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),s.end()}}catch(n){throw e.status=$i.FAIL,n instanceof Error&&(n.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),null===(s=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===s||s.call(t,n).end(),n}}))}};const Mr=new class{init(e){this.core=e}},yr=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Mr;return s(e)&&e.slice(0,3)===t.CONV_C2C},Or=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Mr;return s(e)&&e.slice(0,5)===t.CONV_GROUP},Ar=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Mr;return s(e)&&e===t.CONV_SYSTEM},Tr=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:Mr.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 Rr(e){const{OuterConstant:t}=Mr.core;let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}function Dr(e){const{OuterConstant:t}=Mr.core;let s;return e.startsWith(t.CONV_C2C)&&(s=e.replace(t.CONV_C2C,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}function br(e,t){const{helper:s}=Mr.core,n=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(`${e} fail:`,n),n}class Lr{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=Tr(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(){const{core:{OuterConstant:e,utils:{isUndefined:t}}}=Mr;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){const{core:{OuterConstant:t,utils:{isUndefined:s}}}=Mr,{nextUnreadCount:n,isFromGetConversations:o,isUnreadC2CMessage:i}=e;s(n)||(this.subType!==t.GRP_AVCHATROOM?o&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=n:this.unreadCount+=n:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=Tr(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{core:{OuterConstant:t}}=Mr,{sequence:s,time:n}=e;return this.type===t.CONV_C2C&&s===this.lastMessage.lastSequence&&n===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&s===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){const{core:{common:{updateGroupAtInfo:t}}}=Mr;t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var Nr,Pr;!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(Nr||(Nr={})),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(Pr||(Pr={}));var Gr;!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"}(Gr||(Gr={}));const wr=0,Ur=1;var kr=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){this._core=e;const{helper:t,notificationCenter:s,appStore:{conversationStore:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},InnerEvent:{SYNC_CONVERSATION_LIST:r,MESSAGE_PUSH:a,NEW_MESSAGE:c,MESSAGE_DELETED:u,MESSAGE_REVOKED:l,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:h,LOGOUT:g,DESTROY:p}}=e;this._conversationStore=n,t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_GROUP_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this);const{InnerEventSubType:{GROUP_AT_TIPS:_}}=s;s.subscribeInnerEvent(r,this._handleConversationSynced,this),s.subscribeInnerEvent(c,this._handleNewMessage,this),s.subscribeInnerEvent(a,_,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(l,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(h,this._handleConversationUpdated,this),s.subscribeInnerEvent(g,this._reset,this),s.subscribeInnerEvent(p,this._dispose,this),console.log(`${this._name}.init`)}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){const{constants:{WORKFLOW_STEP:t}}=this._core,{conversationUpdateFieldList:s=[],groupTipList:n=[],isUnreadC2CMessage:o}=e.result[t.UNREAD_MESSAGE_SYNC]||{};let i=!1;s.forEach((e=>{const{conversationID:t,unreadCount:s}=e,n=this.getLocalConversation(t);n&&n.unreadCount!==s&&(n.updateUnreadCount({nextUnreadCount:s,isUnreadC2CMessage:o}),i=!0)})),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(n)}_handleGroupAtTipsSynced(e){var t;for(let s=0;s<e.length;s++)if(12===e[s].Event){if(null===(t=e[s].GroupTips[0].MsgBody)||void 0===t?void 0:t.TopicId)continue;this._handleNewGroupAtTips(e[s])}}_handleGroupListSyncFinished(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,n=e.result[s.GROUP_LIST_SYNC]||[],{OuterConstant:{CONV_GROUP:o}}=this._core;let i=!1;for(let e=0;e<n.length;e++){const s=n[e],r=`${o}${s.groupID}`;if(!this.hasLocalConversation(r))continue;const a=this.getLocalConversation(r);a.groupProfile=JSON.parse(JSON.stringify(s)),a.lastMessage.lastSequence<s.nextMessageSeq&&(a.lastMessage.lastSequence=s.nextMessageSeq-1),a.subType||(a.subType=s.type),(null===(t=s._groupAtInfoList)||void 0===t?void 0:t.length)>0&&this._handleNewGroupAtTips({GroupTips:s._groupAtInfoList}),i=!0}i&&this.emitConversationListUpdate()}_handleNewMessage(e){const{conversationUpdateFieldList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:o=!0}=e.result||{};if(0===t.length)return;const{common:{isTopic:i}}=this._core;if(i(t[0].conversationID))return;this.updateLocalConversationList({conversationUpdateFieldList:t,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:o});t.filter((e=>this._isConversationNeedShow(e.conversationID))).length>0&&this.emitConversationListUpdate()}_handleNewGroupAtTips(e){const{GroupTips:t=[]}=e;t.forEach((e=>{const{GroupAtTips:t,MsgBody:s,MsgRandom:n,ClientSeq:o}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=n,i.__sequence=o,this._groupAtTipsList.push(i)})),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){const{From_Account:t,GroupId:s,MsgSeq:n,GroupAtType:o}=e;return{from:t,groupID:s,sequence:n,groupAtType:o}}_updateGroupAtInfoList(){if(0===this._groupAtTipsList.length)return;const{common:e,OuterConstant:t}=this._core,s=e.getCurrentUserID();let n=!1;this._groupAtTipsList.forEach((e=>{const{groupID:o,from:i}=e;if(i!==s){const s=this.getLocalConversation(`${t.CONV_GROUP}${o}`);s&&(s.updateGroupAtInfoList(e),n=!0)}})),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(e){var t,s;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const{message:{messageDataHandler:n},OuterConstant:o}=this._core,i=(null==n?void 0:n.getLocalMessageList(e))||[];let r={};for(let e=(i.length||0)-1;e>=0;e--)if(!i[e].isDeleted){r=i[e];break}const a=this.getLocalConversation(e);if(!a)return;let c=!1;a.lastMessage.lastSequence===r.sequence&&a.lastMessage.lastTime===r.time||((null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r))&&(r=void 0),a.updateLastMessage(r),c=!0),e.startsWith(o.CONV_C2C)&&this.updateUnreadCount(e),c&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${e} with lastMessage:`,a.lastMessage))}_handleMessageRevoked(e){const{messageList:t=[],updateUnreadCount:s=!0}=e;if(console.log(`${this._name}._handleMessageRevoked messageList:${t.length}`),0===t.length)return;let n=null,o=!1;t.forEach((e=>{n=this.getLocalConversation(e.conversationID),n&&(s&&n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(e.revoker),o=!0))})),o&&this.emitConversationListUpdate()}_handleMessageModified(e){console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:t,messageList:s}=e,n=this.getLocalConversation(t),{utils:{isEmpty:o},common:{getMessagePreviewText:i}}=this._core;if(o(n))return;const{lastMessage:r}=n;if(r){const e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${t} lastMessage updated`))}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){const{isFromGetConversations:t}=e,{newConversationList:s}=this._getTmpConversationListMapping(e);this._sortConversationList(),t||this._updateNewConversationProfile(s),console.log(`${this._name}.updateLocalConversationList newConversationList: ${s.length}`)}_getTmpConversationListMapping(e){const{OuterConstant:t}=this._core,{conversationUpdateFieldList:s,isFromGetConversations:n,isInstantMessage:o,isUnreadC2CMessage:i=!1,updateUnreadCount:r}=e,a=[],c=null==s?void 0:s.length;for(let e=0;e<c;e++){const c=new Lr(s[e]),{conversationID:u,type:l}=c;if(!Dr(u))if(this.hasLocalConversation(u)){const a=this.getLocalConversation(u);if(n){this.setLocalConversation(u,c),l===t.CONV_C2C?c.unreadCount=(null==a?void 0:a.unreadCount)||0:l===t.CONV_GROUP&&(c.groupProfile=JSON.parse(JSON.stringify(null==a?void 0:a.groupProfile)));continue}this._mergeConversationInfo({conversationID:u,tmpConversation:c,lastMessage:s[e].lastMessage,isFromGetConversations:n,isInstantMessage:o}),this._patchLastMessage({conversationID:u,lastMessage:s[e].lastMessage,isInstantMessage:o}),!0===r&&(null==a||a.updateUnreadCount({nextUnreadCount:c.unreadCount,isFromGetConversations:n,isUnreadC2CMessage:i}))}else a.push(c),this.setLocalConversation(u,c)}return{newConversationList:a}}_mergeConversationInfo(e){const{conversationID:t,tmpConversation:s,lastMessage:n,isFromGetConversations:o,isInstantMessage:i}=e,r=this.getLocalConversation(t),a=["unreadCount","allowType","adminForbidType","payload"];!1===i&&a.push("lastMessage"),o&&a.push("isPinned");const{utils:{isUndefined:c,isEmpty:u},common:{deepMerge:l}}=this._core;c(i)&&n&&null===(null==r?void 0:r.lastMessage.payload)&&(r.lastMessage.payload=n.payload),u(null==r?void 0:r.lastMessage.revoker)||(r.lastMessage.revoker=null);l(r,s,a,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{OuterConstant:t}=this._core,{conversationID:s,lastMessage:n,isInstantMessage:o}=e,i=this.getLocalConversation(s);if(i&&n){const{payload:e,nameCard:s,nick:r,cloudCustomData:a=""}=n;o&&(e&&(i.lastMessage.payload=e),i.type===t.CONV_GROUP&&(i.lastMessage.nameCard=s,i.lastMessage.nick=r)),i.lastMessage.cloudCustomData!==a&&(i.lastMessage.cloudCustomData=a)}}_sortConversationList(){const{utils:{isEmpty:e}}=this._core,t=[...this._conversationStore.getConversationMap()],s=[],n=[],o=[],i=[];t.forEach((t=>{!0===t[1].isPinned?e(t[1].lastMessage.lastTime)?n.push(t):s.push(t):e(t[1].lastMessage.lastTime)?i.push(t):o.push(t)}));const r=s.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n).concat(o.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime))).concat(i);this._updateConversationMapFromList(r)}_updateNewConversationProfile(e){if(0===e.length)return;const t=[],s=[],{OuterConstant:{CONV_GROUP:n,CONV_C2C:o}}=this._core;e.forEach((e=>{const{conversationID:i,type:r}=e;if(r===o){const e=i.replace(o,"");t.push(e)}else if(r===n){const e=i.replace(n,"");s.push(e)}})),t.length>0&&this._updateC2CConversation(t),s.length>0&&this._updateGroupConversation(s)}_updateC2CConversation(e){var t;const{OuterConstant:{CONV_C2C:s},appStore:{userStore:n},user:o}=this._core;let i=!1;null===(t=o.userProfile)||void 0===t||t.getUserProfile({userIDList:e}).then((e=>{((null==e?void 0:e.data)||[]).forEach((e=>{var t;const{userID:o}=e,r=this.getLocalConversation(`${s}${o}`);if(r){const s=(null===(t=n.getFriend(o))||void 0===t?void 0:t.remark)||"";r.remark=s,r.userProfile=e,i=!0}})),i&&this.emitConversationListUpdate()})).catch((e=>{}))}_updateGroupConversation(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core;let n=!1;e.forEach((e=>{const o=s.getGroup(e),i=this.getLocalConversation(`${t}${e}`);o&&i&&(i.groupProfile=o,n=!0)})),n&&this.emitConversationListUpdate()}_isConversationNeedShow(e){const t=this.getLocalConversation(e);if(this._core.utils.isUndefined(t))return!0;const{OuterConstant:s}=this._core,n=t.type===s.CONV_TOPIC,o=t.type===s.CONV_GROUP&&t.subType===s.GRP_ROOM,i=t.type===s.CONV_GROUP&&t.subType===s.GRP_LIVE;return!(n||o||i)}updateUnreadCount(e,t=!0){var s,n;let o=!1;const i=this.getLocalConversation(e),r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageDataHandler)||void 0===n?void 0:n.getLocalMessageList(e);if(!i)return o;const a=i.unreadCount,c=null==r?void 0:r.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;return console.log(`${this._name}._updateUnreadCount conversationID:${e} currentUnreadCount:${a} newUnreadCount:${c}`),a!==c&&(i.unreadCount=c,o=!0,!0===t&&this.emitConversationListUpdate()),o}emitConversationListUpdate(e=!1){e&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:t}}=this._core,s=this.getLocalConversationList();this._emitEvent({name:t,data:s}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(console.log(`${this._name}._emitTotalUnreadCountUpdate from ${this._totalUnreadCount} to ${t}`),this._totalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){const{OuterConstant:e}=this._core,t=this.getLocalConversationList();let s=0;return t.forEach((t=>{t.type!==e.CONV_SYSTEM&&(""!==t.messageRemindType&&t.messageRemindType!==e.MSG_REMIND_ACPT_AND_NOTE||(s+=t.unreadCount))})),s}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter((e=>this._isConversationNeedShow(e.conversationID)))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(const[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach((e=>{const n=this.getLocalConversation(e);(null==n?void 0:n.messageRemindType)!==t&&(n.messageRemindType=t,s=!0)})),console.log(`${this._name}.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:${s}`),s&&this.emitConversationListUpdate()}markMessageAsRead(e){const{message:{messageDataHandler:t}}=this._core,{conversationID:s,lastReadTime:n=0,lastReadSequence:o=0}=e,i=null==t?void 0:t.getLocalMessageList(s);if(0===i.length)return;const{length:r}=i;for(let e=r-1;e>=0;e--){const t=i[e],s=n&&t.time>n,r=o&&t.sequence>o;if(!s&&!r){if("in"===t.flow&&t.isRead)break;t.setIsRead(!0)}}}appendToPinnedConversation(e){const t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex((e=>!1===e[1].isPinned));t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:n,MESSAGE_MODIFIED:o,CONVERSATION_UPDATED:i,LOGOUT:r,DESTROY:a,SYNC_CONVERSATION_LIST:c}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:u}}=e;e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(o,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(c,this._handleConversationSynced,this),e.unSubscribeInnerEvent(r,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}};var Fr=new class{constructor(){this._name="GetConversationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return g(this,void 0,void 0,(function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}}))}_getConversationList(e){const{utils:{isUndefined:t,isArray:s,isPlainObject:n}}=this._core;if(t(e))return kr.getLocalConversationList();if(s(e)){if(0===e.length)return[];return kr.getLocalConversationList().filter((t=>e.includes(t.conversationID)))}if(n(e)){const{type:t,markType:s,groupName:n,hasUnreadCount:o,hasGroupAtInfo:i}=e;return kr.getLocalConversationList().filter((e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,i)))}return[]}_filterType(e,t){const{OuterConstant:s}=this._core;return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){const{utils:{isString:s}}=this._core;return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){const{utils:{isNumber:s}}=this._core;return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}};var $r=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(e){return g(this,void 0,void 0,(function*(){try{const{common:t}=this._core,s=yield function(e,t){return g(this,void 0,void 0,(function*(){const{toAccount:s,userIDList:n}=e,o={To_Account:s,Peer_Account:n};return t.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:o})}))}({toAccount:t.getCurrentUserID(),userIDList:e},this._core),{MuteNotificationsList:n=[]}=s||{};n.forEach((e=>{const{Peer_Account:t,MuteNotifications:s}=e,n=`${this._core.OuterConstant.CONV_C2C}${t}`,o=Rr(s);kr.patchMessageRemindType([n],o)}))}catch(e){console.error(`${this._name}.get fail:`,e)}}))}};var xr=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(e){return g(this,void 0,void 0,(function*(){if(0!==e.length)try{const t=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:n}=e,o={GroupIdList:s,ResponseFilter:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:o})}))}({groupIDList:e,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:s=[]}=t||{};s.forEach((e=>{var t;const{GroupId:s,MemberList:n}=e,o=(null===(t=n[0])||void 0===t?void 0:t.MsgFlag)||"",i=`${this._core.OuterConstant.CONV_GROUP}${s}`;kr.patchMessageRemindType([i],o)}))}catch(e){console.error(`${this._name}.get fail:`,e)}}))}};var qr=new class{constructor(){this._name="GetConversationProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,GRP_AVCHATROOM:n},appStore:{groupStore:o},utils:{isEmpty:i}}=this._core,r={code:0,data:{}};let a=kr.getLocalConversation(e);if(Ar(e))return r.data.conversation=a,r;let c=!1;const u=yr(e)?t:s;if(i(a)&&(c=!0,a=new Lr({conversationID:e,type:u})),console.log(`${this._name}.getConversationProfile conversationID:${e} isNewConversation:${c}`),r.data.conversation=a,null==a?void 0:a.getProfileCompleted())return r;if(u===t){const s=e.replace(t,"");yield this._handleC2CConversation(a,s),c&&(yield $r.get([s]))}if(u===s){const t=e.replace(s,"");if(!o.getGroup(t))return r;yield this._handleGroupConversation(a,t),c&&a.groupProfile.type!==n&&(yield xr.get([t]))}return r}))}_handleC2CConversation(e,t){return g(this,void 0,void 0,(function*(){var s,n;const{user:o,helper:i,utils:{isEmpty:r},appStore:{conversationStore:a,userStore:c}}=this._core,{conversationID:u}=e,l=yield null===(s=o.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:[t]});if(0===(null==l?void 0:l.data.length))throw new i.ChatError({code:Gr.USER_OR_GRP_NOT_FOUND});e.userProfile=null==l?void 0:l.data[0];const d=null===(n=c.getFriend(t))||void 0===n?void 0:n.remark;r(d)||e.remark===d||(e.remark=d),e.setProfileCompleted();const h=kr.hasLocalConversation(u);console.log(`${this._name}._handleC2CConversation conversationID:${u} hasLocalConversation: ${h}`),h?a.updateConversation(u,e):kr.appendToPinnedConversation(e)}))}_handleGroupConversation(e,t){return g(this,void 0,void 0,(function*(){const{apiMap:{getGroupProfile:s},appStore:{conversationStore:n}}=this._core,{conversationID:o}=e,i=yield s({groupID:t});e.groupProfile=null==i?void 0:i.data.group,e.setProfileCompleted();const r=kr.hasLocalConversation(o);console.log(`${this._name}._handleGroupConversation conversationID:${o} hasLocalConversation: ${r}`),r?n.updateConversation(o,e):kr.appendToPinnedConversation(e)}))}};var Vr=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return kr.getTotalUnreadMessageCount()}};var Br=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){this._core=e;const{helper:t,common:{isTopic:s},notificationCenter:n,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{ALL_MESSAGE_READ:i}}=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),n.subscribeInnerEvent(o,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach((e=>{const{ReadC2cMsgNotify:n}=e;if(!t(n)){const{UinPairReadArray:e=[]}=n;e.forEach((e=>{const{From_Account:t,LastReadTime:n}=e,o=`${s.CONV_C2C}${t}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${o} lastReadTime:${n}`),kr.markMessageAsRead({conversationID:o,lastReadTime:n}),kr.updateUnreadCount(o)}))}}))}handleGroupMessageReadSync(e){const{OuterConstant:t,utils:{isUndefined:s}}=this._core;e.forEach((e=>{const{GroupReadInfoArray:n}=e.MsgBody;s(n)||n.forEach((e=>{const{GroupId:s,LastReadMsgSeq:n}=e,o=`${t.CONV_GROUP}${s}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${o} lastReadSequence:${n}`),kr.markMessageAsRead({conversationID:o,lastReadSequence:n}),kr.updateUnreadCount(o),this._clearGroupAtInfoList(o)}))}))}setMessageRead(e){return g(this,void 0,void 0,(function*(){var t,s;const{OuterConstant:n}=this._core,{conversationID:o}=e,i={code:0,data:{}},r=kr.getLocalConversation(o);if(console.log(`${this._name}.setMessageRead conversationID:${o} unreadCount:${(null==r?void 0:r.unreadCount)||0}`),!r)return i;const a=!(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r.groupAtInfoList));if(r.type===n.CONV_GROUP&&a&&this._deleteGroupAtTips(o),0===r.unreadCount)return i;const{ssoLog:c,helper:{ChatError:u}}=this._core,l=c.createSSOLogData({method:"setMessageRead"});l.setLogInfo({message:`conversationID:${o}`});try{if(r.type===n.CONV_C2C){const e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(o,e),l.setLogInfo({moreMessage:`lastMessageTime:${e}`}).end()}if(r.type===n.CONV_GROUP){const e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(o,e),l.setLogInfo({moreMessage:`lastMessageSequence:${e}`}).end()}}catch(e){const{errorCode:t,errorInfo:s}=e,n=new u({functionName:"setMessageRead",code:t,message:s});throw l.setError(n).end(),n}return r.type===n.CONV_SYSTEM&&(r.unreadCount=0),kr.emitConversationListUpdate(),i}))}setAllMessageRead(){return g(this,arguments,void 0,(function*(e={}){const{OuterConstant:{READ_ALL_MSG:t},ssoLog:s}=this._core,n=s.createSSOLogData({method:"setAllMessageRead"});e.scope||(e.scope=t);const{scope:o}=e,i=this._generateSetAllMessageReadRequestData(o);if(i.allC2CMessageReadStatus===wr&&0===i.groupMessageReadInfoList.length)return{code:0};try{const e=yield function(e){return g(this,void 0,void 0,(function*(){const{allC2CMessageReadStatus:t,groupMessageReadInfoList:s}=e,n={C2CReadAllMsg:t,GroupReadInfo:s};return Mr.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:n})}))}(i);if(e){const{GroupReadInfoArray:t,C2CReadAllMsg:s}=e,i=this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:s})>0&&kr.emitConversationListUpdate(),n.setLogInfo({message:`scope:${o} failureGroups:${JSON.stringify(i)}`}).end()}return{code:0}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"setAllMessageRead",code:t});throw n.setError(s).end(),s}}))}_handleAllMessageRead(e){const{GroupReadInfoArray:t,C2CReadAllMsg:s}=e;this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:s})>0&&kr.emitConversationListUpdate()}_updateAllConversationReadStatus(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s},appStore:n}=this._core,o=n.conversationStore.getConversationMap(),{allC2CMessageReadStatus:i}=e;let r=0;for(const[e,n]of o)if(n.unreadCount>=1){if(i===Ur&&n.type===t){const t=this._getLocalMessageMaxTime(n);kr.markMessageAsRead({conversationID:e,lastReadTime:t})}else if(n.type===s){const t=e.replace(s,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){const s=this._serverGroupConversationLastReadSeqMap.get(t);kr.markMessageAsRead({conversationID:e,lastReadSequence:s})}}kr.updateUnreadCount(e,!1)&&(r+=1)}return r}_generateSetAllMessageReadRequestData(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_C2C_MSG:n},appStore:o}=this._core,i={allC2CMessageReadStatus:wr,groupMessageReadInfoList:[]},r=o.conversationStore.getConversationMap();for(const[,o]of r){const{type:r,unreadCount:a}=o;if(this._shouldSetAllMessageRead({scope:e,type:r,unreadCount:a}))if(r===t&&i.allC2CMessageReadStatus===wr){if(i.allC2CMessageReadStatus=Ur,e===n)break}else if(r===s){const e=this._getLocalMessageMaxSequence(o),{groupID:t}=o.groupProfile;i.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return i}_parseGroupReadInfo(e){const{utils:{isUndefined:t}}=this._core,s=[];return null==e||e.forEach((e=>{const{GroupId:n,MsgSeq:o,RetCode:i,LastReadMsgSeq:r}=e;t(i)?this._serverGroupConversationLastReadSeqMap.set(n,r):(this._serverGroupConversationLastReadSeqMap.set(n,o),0!==i&&s.push(`${n}-${o}-${i}`))})),s}_deleteGroupAtTips(e){return g(this,void 0,void 0,(function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${e}`);const t=kr.getLocalConversation(e);if(!t)return;const s=(null==t?void 0:t.groupAtInfoList)||[];if(0!==s.length)try{const{common:{getCurrentUserID:t,isCommunity:n},OuterConstant:{CONV_GROUP:o,CONV_AT_ALL:i}}=this._core;let r=[...s];if(n({groupID:e.replace(o,"")})&&(r=s.filter((e=>!e.atTypeArray.includes(i))),0===r.length))return void this._clearGroupAtInfoList(e,!1);const a=r.map((e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID})));yield function(e,t){return g(this,void 0,void 0,(function*(){const{messageListToDelete:s}=e,n={DelMsgList:s};return t.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:n})}))}({messageListToDelete:a},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${s.length}`),this._clearGroupAtInfoList(e)}catch(e){console.error(`${this._name}._deleteGroupAtTips fail:`,e)}}))}_clearGroupAtInfoList(e,t=!0){const s=kr.getLocalConversation(e);s&&(s.groupAtInfoList.length>0&&(s.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:${t}`)),t&&kr.emitConversationListUpdate())}_getLocalMessageMaxTime(e){var t;const{conversationID:s}=e,n=this._core.message.messageDataHandler.getLocalMessageList(s),o=Math.max(...n.map((e=>e.time)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastTime)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${i} to ${o}`),i=o),i}_getLocalMessageMaxSequence(e){var t;const{conversationID:s}=e,n=this._core.message.messageDataHandler.getLocalMessageList(s),o=Math.max(...n.map((e=>e.sequence)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to ${o}`),i=o),i}_setC2CMessageRead(e,t){return g(this,void 0,void 0,(function*(){try{yield function(e,t){return g(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}`),kr.markMessageAsRead({conversationID:e,lastReadTime:t}),kr.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setC2CMessageRead fail:`,e),e}}))}_setGroupMessageRead(e,t){return g(this,void 0,void 0,(function*(){try{yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,lastMessageSequence:n}=e,o={GroupId:s,MsgReadedSeq:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:o})}))}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${t}`),kr.markMessageAsRead({conversationID:e,lastReadSequence:t}),kr.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setGroupMessageRead fail:`,e),e}}))}_shouldSetAllMessageRead(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:n,READ_ALL_C2C_MSG:o,READ_ALL_GROUP_MSG:i}}=this._core,{type:r,scope:a,unreadCount:c}=e;return!(c<=0)&&(!(r!==t||![n,o].includes(a))||!(r!==s||![n,i].includes(a)))}};var jr=new class{constructor(){this._name="PinConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,t){const{utils:{isArray:s}}=this._core;if(!s(e))return;const{OuterConstant:n}=this._core;let o=!1;e.forEach((e=>{const{Type:s,To_Account:i,GroupId:r}=e;let a;1===s?a=kr.getLocalConversation(`${n.CONV_C2C}${i}`):2===s&&(a=kr.getLocalConversation(`${n.CONV_GROUP}${r}`)),a&&(console.log(`${this._name}.handleConversationPinned conversationID:${a.conversationID} localPinned:${a.isPinned} remotePinned:${t}`),t&&!a.isPinned&&(a.isPinned=!0,o=!0),!t&&a.isPinned&&(a.isPinned=!1,o=!0))})),o&&kr.emitConversationListUpdate(!0)}pinConversation(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:t,common:s,ssoLog:n,helper:{ChatError:o}}=this._core,{conversationID:i,isPinned:r}=e,a={code:0,data:{conversationID:i}},c=kr.getLocalConversation(i);if(c&&c.isPinned===r)return a;if(Ar(i))return c&&(c.isPinned=r),kr.emitConversationListUpdate(!0),a;const u=n.createSSOLogData({method:"pinConversation"});u.setLogInfo({message:`conversationID:${i} isPinned:${r}`});try{let e=null;yr(i)?e={Type:1,To_Account:i.replace(t.CONV_C2C,"")}:Or(i)&&(e={Type:2,GroupId:i.replace(t.CONV_GROUP,"")});const n=yield function(e,t){return g(this,void 0,void 0,(function*(){const{fromAccount:s,operationType:n,itemList:o}=e,i={From_Account:s,OperationType:n,RecentContactItem:o};return t.common.buildAndSendPacket({servcmd:"recentcontact.top",data:i})}))}({fromAccount:s.getCurrentUserID(),operationType:!0===r?1:2,itemList:[e]},this._core);if(u.end(),console.log(`${this._name}.pinConversation ok, conversationID:${i} isPinned:${r}.`),n){if(c)c.isPinned!==r&&(c.isPinned=r);else{const e=new Lr({conversationID:i,type:yr(i)?t.CONV_C2C:t.CONV_GROUP,isPinned:r});kr.setLocalConversation(i,e)}kr.emitConversationListUpdate(!0)}return a}catch(e){const{errorCode:t,errorInfo:s}=e,n=new o({functionName:"pinConversation",code:t,message:s});throw u.setError(n).end(),console.error(`${this._name}.pinConversation fail:`,n),n}}))}};var Kr=new class{constructor(){this._name="DeleteConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){const{utils:{isArray:t}}=this._core;if(!t(e))return;const{OuterConstant:s}=this._core,n=[];e.forEach((e=>{const{Type:t,Peer_Account:o,GroupId:i}=e;1===t&&n.push(`${s.CONV_C2C}${o}`),2===t&&n.push(`${s.CONV_GROUP}${i}`)})),console.log(`${this._name}.handleConversationDeleted conversationIDList:${n}`),this._deleteLocalConversationList(n)}deleteConversation(e){return g(this,void 0,void 0,(function*(){const{utils:{isString:t}}=this._core;if(t(e))return console.log(`${this._name}.deleteConversation conversationID:${e}`),void(yield this._deleteConversation({conversationIDList:[e],flag:Pr.ONLY_CONVERSATIONID}));const s=Object.assign({},e);s.conversationIDList.length>100&&(s.conversationIDList=s.conversationIDList.slice(0,100)),yield this._deleteConversation(s)}))}_deleteConversation(e){return g(this,void 0,void 0,(function*(){const{conversationIDList:t,clearHistoryMessage:s=!0,flag:n=0}=e,{ssoLog:o,helper:{ChatError:i}}=this._core,r=`conversationIDList:${t} clearHistoryMessage:${s}`,a=o.createSSOLogData({method:"deleteConversation"});a.setLogInfo({message:r}),console.log(`${this._name}._deleteConversation ${r}`);try{const e=yield Promise.all([this._deleteConversationFromLocal(t),this._deleteConversationFromServer(t,s)]),o=[...e[0],...e[1]];if(0===o.length)throw new this._core.helper.ChatError({code:Gr.CONV_NOT_FOUND});return a.end(),console.log(`${this._name}._deleteConversation ok.`),{code:0,data:n===Pr.ONLY_CONVERSATIONID?{conversationID:o[0]}:{conversationIDList:o}}}catch(e){const{errorCode:t,errorInfo:s}=e,n=new i({functionName:"deleteConversation",code:t,message:s});throw a.setError(n).end(),console.error(`${this._name}._deleteConversation fail:`,n),n}}))}_deleteConversationFromLocal(e){const{OuterConstant:t}=this._core;return e.filter((e=>{var s;if(!kr.hasLocalConversation(e))return!1;const n=null===(s=kr.getLocalConversation(e))||void 0===s?void 0:s.type;return n!==t.CONV_GROUP||this._hasLocalGroup(e)?n===t.CONV_SYSTEM&&(this._deleteLocalConversation(e),!0):(this._deleteLocalConversation(e),!0)}))}_deleteConversationFromServer(e,t){return g(this,void 0,void 0,(function*(){const{OuterConstant:s,common:n}=this._core,o={fromAccount:n.getCurrentUserID(),conversationList:[],clearHistoryMessage:t?1:0};if(e.forEach((e=>{var t;if(kr.hasLocalConversation(e)){const n=(null===(t=kr.getLocalConversation(e))||void 0===t?void 0:t.type)||"",i=e.replace(n,"");n===s.CONV_C2C?o.conversationList.push({To_Account:i,Type:1}):n===s.CONV_GROUP&&this._hasLocalGroup(e)&&o.conversationList.push({ToGroupid:i,Type:2})}})),0===o.conversationList.length)return[];const i=yield function(e,t){return g(this,void 0,void 0,(function*(){const{fromAccount:s,conversationList:n,clearHistoryMessage:o}=e,i={From_Account:s,ContactItem:n,ClearRamble:o};return t.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:i})}))}(o,this._core);if(i){const{ResultItem:e=[]}=i,t=[];return e.length>0&&e.forEach((e=>{if(0===e.ResultCode){const n=1===e.type?`${s.CONV_C2C}${e.To_Account}`:`${s.CONV_GROUP}${e.ToGroupid}`;t.push(n)}})),this._deleteLocalConversationList(t),t}return[]}))}_deleteLocalConversationList(e){let t=!1;e.forEach((e=>{kr.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)})),console.log(`${this._name}._deleteLocalConversationList isUpdate:${t}`),t&&kr.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){const s=kr.hasLocalConversation(e);console.log(`${this._name}._deleteLocalConversation conversationID:${e} has:${s}`),s&&(kr.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t&&kr.emitConversationListUpdate())}_hasLocalGroup(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,n=e.replace(t,"");return!!s.getGroup(n)}_deleteConversationLocalMessage(e){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${e}`),this._core.message.messageDataHandler.deleteConversationMessageList(e)}};var Hr=new class{constructor(){this._name="SetConversationDraft"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(e){return g(this,void 0,void 0,(function*(){const{conversationID:t,draftText:s}=e;if(console.log(`${this._name} conversationID:${t} draftText:${s}`),!kr.hasLocalConversation(t))throw new this._core.helper.ChatError({code:Gr.CONV_NOT_FOUND});const n=kr.getLocalConversation(t);return null==n||n.setDraftText(s),kr.emitConversationListUpdate(),{code:0,data:{conversation:n}}}))}};var Wr=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(e,t){return g(this,void 0,void 0,(function*(){e.length>30&&(console.warn(`${this._name}.set userIDList length:${e.length} exceeds limit 30`),e.splice(30));const s=function(){const{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=Mr.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[t],n=yield function(e,t){return g(this,void 0,void 0,(function*(){const{userIDList:s,receiveMessageOption:n}=e,o={Peer_Account:s,Mute_Notifications:n};return t.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:o})}))}({userIDList:e,receiveMessageOption:s},this._core),{ErrorList:o=[]}=n||{},i=[];o.forEach((t=>{const{Peer_Account:s,ErrorCode:n}=t;i.push({userID:s,code:n});const o=e.indexOf(s);o>-1&&e.splice(o,1)}));const r=[],a=[],{OuterConstant:c}=this._core;return e.forEach((e=>{a.push(`${c.CONV_C2C}${e}`),r.push({userID:e})})),kr.patchMessageRemindType(a,t),{code:0,data:{successUserIDList:r,failureUserIDList:i}}}))}};var Yr=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(e,t){return g(this,void 0,void 0,(function*(){const{common:{getCurrentUserID:s,isTopic:n},OuterConstant:o}=this._core;if(yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,userID:n,receiveMessageOption:o}=e,i={GroupId:s,Member_Account:n,MsgFlag:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:i})}))}({groupID:e,userID:s(),receiveMessageOption:t},this._core),!n(e)){const s=`${o.CONV_GROUP}${e}`;kr.patchMessageRemindType([s],t)}return{code:0,data:{groupID:e,messageRemindType:t}}}))}};var zr=new class{constructor(){this._name="SetMessageRemindType"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach((e=>{const{MuteNotificationsSync:n}=e;if(!t(n)){const{To_Account:e,MuteNotifications:t}=n,o=e.map((e=>`${s.CONV_C2C}${e}`)),i=Rr(t);console.log(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${o} messageRemindType:${i}`),kr.patchMessageRemindType(o,i)}}))}setMessageRemindType(e){return g(this,void 0,void 0,(function*(){const t="setMessageRemindType",{groupID:s,userIDList:n,messageRemindType:o}=e,{helper:i,utils:{isUndefined:r}}=this._core;try{if(!r(s)){console.log(`${this._name}.${t} groupID:${s} messageRemindType:${o}`);return yield Yr.set(s,o)}if(!r(n)){console.log(`${this._name}.${t} userIDList:${n} messageRemindType:${o}`);return yield Wr.set(n,o)}throw new i.ChatError({functionName:t,message:"userIDList or groupID is required"})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Jr=new class{init(e){console.log("ConversationAction.init"),this._core=e,Fr.init(e),qr.init(e),Vr.init(e),Br.init(e),jr.init(e),Kr.init(e),Hr.init(e),zr.init(e);const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:n}}=this._core,{InnerEventSubType:{CONV_MODIFIED:o,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:r,C2C_REMIND_TYPE_SYNC:a}}=t;t.subscribeInnerEvent(s,o,this._onConversationModified,this),t.subscribeInnerEvent(s,i,this._onC2CMessageReadSync,this),t.subscribeInnerEvent(s,a,this._onC2CMessageRemindTypeSync,this),t.subscribeInnerEvent(s,r,this._onGroupMessageReadSync,this),t.subscribeInnerEvent(n,this._dispose,this)}_onConversationModified(e){const{constants:{ConvModifyPushType:t}}=this._core,{RecentContactMod:s=[]}=e;s.forEach((e=>{const{PushType:s}=e;if(s===t.CONV_DELETED){const{RecentContactList:t}=e.RecentContactDeleteItem;Kr.handleConversationDeleted(t)}if(s===t.CONV_PINED){const{RecentContactList:t}=e.RecentContactTopItem;jr.handleConversationPinned(t,!0)}if(s===t.CONV_UNPINED){const{RecentContactList:t}=e.RecentContactTopItem;jr.handleConversationPinned(t,!1)}}))}_onC2CMessageReadSync(e){const{C2cNotifyMsgArray:t=[]}=e;Br.handleC2CMessageReadSync(t)}_onC2CMessageRemindTypeSync(e){const{C2cNotifyMsgArray:t=[]}=e;zr.handleC2CMessageRemindTypeSync(t)}_onGroupMessageReadSync(e){const{GroupTips:t=[]}=e;Br.handleGroupMessageReadSync(t)}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:o,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:r}}=e;e.unSubscribeInnerEvent(t,n,this._onConversationModified,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,r,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};var Qr=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(e){return g(this,void 0,void 0,(function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:t}}=this._core,{messageRemindType:s=t,isRepeated:n=!0}=e,{startTime:o=0,endTime:i=0}=this._calcStartAndEndTime(e),r=yield function(e){return g(this,void 0,void 0,(function*(){const{common:t}=Mr.core,{startTime:s,endTime:n,isRepeated:o,messageRemindType:i}=e,r={StartTime:s,EndTime:n,IsRepeated:o,Level:i};return t.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:r})}))}({messageRemindType:this._getType(s),startTime:o,endTime:i,isRepeated:n?Nr.ON:Nr.OFF});return{code:0,data:{errorCode:r.ErrorCode,errorInfo:r.ErrorInfo}}}catch(e){br("setAllReceiveMessageOpt",e)}}))}_calcStartAndEndTime(e){const{startHour:t=0,startMinute:s=0,startSecond:n=0,duration:o=0,isRepeated:i=!0}=e,r=new Date,a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),t,s,n),c=Math.round(a.getTime()/1e3);let u=c+o;return i&&o>=86400&&(u=c+86400),{startTime:c,endTime:u}}_getType(e){const{OuterConstant:t}=this._core;return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}};var Xr=new class{init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:n}=e;t.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),s.subscribeInnerEvent(n.MESSAGE_PUSH,s.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){const t=this._handleResult(e),{notificationCenter:s,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:n}}=this._core;s.emitOuterEvent(n,{name:n,data:t})}getAllReceiveMessageOpt(){return g(this,void 0,void 0,(function*(){try{const e=yield function(){return g(this,void 0,void 0,(function*(){const{common:e}=Mr.core,t={To_Account:e.getCurrentUserID()};return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:t})}))}();return{code:0,data:this._handleResult(e)}}catch(e){br("getAllReceiveMessageOpt",e)}}))}_handleResult(e){const{OuterConstant:t}=this._core,{MSG_REMIND_ACPT_AND_NOTE:s,MSG_REMIND_DISCARD:n,MSG_REMIND_ACPT_NOT_NOTE:o}=t,i={0:s,1:n,2:o},{Level:r,StartTime:a,EndTime:c,IsRepeated:u}=e;return{messageRemindType:i[r]||s,startTime:a,endTime:c,isRepeated:u===Nr.ON}}};var Zr=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,Wr.init(e),Yr.init(e),$r.init(e),xr.init(e),Qr.init(e),Xr.init(e)}};const ea=e=>!yr(e)&&!Or(e)&&!Ar(e),ta={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ea(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ea(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ea(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{const{core:{utils:{isArray:t,isObject:s,isString:n}}}=Mr;if(!n(e)&&!s(e))return"options is String or Object.";if(n(e)&&ea(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(ea(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=>!(!yr(e)&&!Or(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}}},sa={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var na=new class{constructor(){this.name="Conversation"}install(e){Mr.init(e),Jr.init(e),Zr.init(e),kr.init(e),e.helper.registerValidateConfig({auth:sa,params:ta})}};const oa=new class{init(e){this.core=e}},ia="AVChatRoom",ra="AV_HISTORY_MSG",aa="GRP_COUNTER",ca="Set",ua="Increase",la="Decrease",da=0,ha=1,ga=2,pa=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],_a=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],ma=["Role","JoinTime","MsgFlag","MsgSeq"],va=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],fa=0,Ia=1,Sa="notStart",Ea="resolved",Ca="rejected",Ma=10018,ya=11e3,Oa=2,Aa=["Owner","Admin","Member"],Ta=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Ra=0,Da=1,ba=2,La=4,Na=1,Pa=2,Ga=3,wa=4,Ua=5,ka=1,Fa=0,$a=4,xa=6,qa=400,Va=300,Ba={from:!0,groupID:!0,groupName:!0,to:!0},ja={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Ka=2,Ha=4,Wa=5,Ya=7,za=8,Ja=15,Qa=20,Xa=21,Za=2600,ec=2602,tc=2603,sc=2620,nc=2621,oc=2623,ic=2660,rc=2661,ac=2681,cc=2683,uc=2684,lc=2685,dc=2687,hc=3122,gc=10018,pc=e=>e===oa.core.OuterConstant.GRP_PUBLIC,_c=e=>e===oa.core.OuterConstant.GRP_AVCHATROOM,mc=(e,t)=>{const{isArray:s}=oa.core.utils;if(!s(e)||!s(t))return!1;let n=!1;return t.forEach((({key:t,value:s})=>{const o=e.find((e=>e.key===t));o?o.value!==s&&(o.value=s,n=!0):(e.push({key:t,value:s}),n=!0)})),n},vc=e=>{const t=[];if(!e)return t;for(let s=0,n=e.length;s<n;s++){const{Key:n,Value:o}=e[s];t.push({key:n,value:o})}return t},fc=e=>{const t=[];for(let s=0,n=e.length;s<n;s++){const{key:n,value:o}=e[s];t.push({Key:n,Value:o})}return t};function Ic(e,t){const{helper:s}=oa.core;if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:hc,replacement1:e})}function Sc(e,t){const{helper:s}=oa.core,n=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(`${e} fail:`,n),n}const Ec=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Cc{constructor(e){this.groupID="",this.name="",this.avatar="",this.type="",this.introduction="",this.notification="",this.ownerID="",this.createTime=0,this.selfInfo={messageRemindType:"",joinTime:"",nameCard:"",role:"",userID:"",memberCustomField:void 0,readedSequence:0,excludedUnreadSequenceList:void 0},this.lastMessage={lastTime:0,lastSequence:0,fromAccount:"",messageForShow:""},this.nextMessageSeq=0,this.memberCount=0,this.maxMemberCount=0,this.joinOption="",this.inviteOption="",this.groupCustomField=[],this.muteAllMembers=!1,this.isSupportTopic=!1,this._lastRevokedTime=0,this._groupAtInfoList=[],this._initGroup(e)}_initGroup(e){const{utils:{isString:t}}=oa.core;for(const s in e)Ec.indexOf(s)<0||("selfInfo"!==s?"isSupportTopic"!==s?"muteAllMembers"===s&&t(e[s])?this.muteAllMembers="On"===e[s]:this[s]=e[s]:this.isSupportTopic=1===e[s]:this.updateSelfInfo(e[s]))}updateGroup(e){const{utils:{isArray:t,isUndefined:s,isNumber:n,isString:o},common:{deepMerge:i}}=oa.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);const r=JSON.parse(JSON.stringify(e));r.lastMsgTime&&(this.lastMessage.lastTime=r.lastMsgTime),o(r.muteAllMembers)&&(r.muteAllMembers="On"===r.muteAllMembers),r.groupCustomField&&mc(this.groupCustomField,r.groupCustomField),s(r.isSupportTopic)||(this.isSupportTopic=n(r.isSupportTopic)?1===r.isSupportTopic:r.isSupportTopic),i(this,r,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(r.members)&&r.members.length>0&&r.members.forEach((e=>{e.userID===this.selfInfo.userID&&i(this.selfInfo,e,["sequence"])}))}updateSelfInfo(e){const{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r}=e,{common:{deepMerge:a}}=oa.core;a(this.selfInfo,{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var Mc=new class{constructor(){this._name="GroupDataHandler"}init(e){this._core=e;const{appStore:{groupStore:t}}=e;this._groupMap=t.getGroupMap(),console.log(`${this._name}.init`)}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){const{common:{getCurrentUserID:t}}=this._core;let s;e.forEach((e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null===(t=this.getLocalGroup(s))||void 0===t||t.updateGroup(e):this._groupMap.set(s,new Cc(e))}));const n=t();for(const[,e]of this._groupMap)e.selfInfo.userID=n,"Owner"===e.selfInfo.role&&(e.ownerID=n)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:e,GRP_LIVE:t}}=this._core;return[...this._groupMap.values()].filter((s=>{const{type:n}=s;return n!==e&&n!==t}))}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,n=`${s}${e}`;if(t.getConversation(n)){const s=this.getLocalGroup(e);t.updateConversation(n,{groupProfile:s})}}reset(){this.clearLocalGroup()}};function yc(e,t){return g(this,void 0,void 0,(function*(){const{type:s,limit:n,offset:o,supportTopic:i=0,memberAccount:r,responseFilter:a}=e,c={Type:s,Limit:n,Offset:o,Member_Account:r,ResponseFilter:a,SupportTopic:i,NeedAppDefineData:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:c})}))}const Oc=function(e){return{code:0,data:e||{}}};var Ac=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Sa,this.PAGING_GRP_COUNT_LIMIT=200}init(e){this._core=e;const{helper:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=e;t.registerApi({apiName:"getGroupList",context:this}),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,n.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return g(this,arguments,void 0,(function*(e=!1){if(e){const e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),Mc.updateLocalGroup(e),Mc.getLocalGroupList()}if(console.log(`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Ca||this._pagingStatus===Sa)return this._syncGroupList().then((()=>{const e=Mc.getLocalGroupList();return Oc({groupList:e,isSyncCompleted:this._isSyncCompleted()})})).catch((e=>{throw console.error(`${this._name}.getGroupList fail:`,e),e}));const t=Mc.getLocalGroupList();return console.log(`${this._name}.getGroupList return group count:${t.length}`),Oc({groupList:t,isSyncCompleted:this._isSyncCompleted()})}))}_syncGroupList(){return g(this,void 0,void 0,(function*(){this._pagingStatus===Sa&&Mc.clearLocalGroup();const e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Ea,this._groupListTreeShaking(t),Mc.updateLocalGroup(t);const s=Mc.getLocalGroupList();return console.log(`${this._name}._syncGroupList ok, count:${s.length}`),Mc.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Ca,console.error(`${this._name}._syncGroupList fail:`,e),e}}))}_pagingGetGroupList(e){return g(this,void 0,void 0,(function*(){const{isCommunityRelay:t=!1,groupList:s}=e;let n,{limit:o,offset:i}=e;const r=[...pa];t&&(n=this._core.OuterConstant.GRP_COMMUNITY,r.push("AtInfoList"));try{const e=yield yc({type:n,limit:o,offset:i,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:r,SelfInfoFilter:[...ma]}},this._core),{GroupIdList:a=[],TotalCount:c=0}=e||{},u=this._convertGroupKey(a);s.push(...u);const l=i+o,d=!(c>l),h=`offset:${i} limit:${o} total:${c} isCompleted:${d} current:${s.length} isCommunityRelay:${t}`;return console.log(`${this._name}._pagingGetGroupList ok. ${h}`),t?d?s:(i=l,this._pagingGetGroupList({isCommunityRelay:!0,limit:o,offset:i,groupList:s})):d?(console.log(`${this._name}._pagingGetGroupList start to get community list`),i=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:o,offset:i,groupList:s})):(i=l,this._pagingGetGroupList({limit:o,offset:i,groupList:s}))}catch(e){if(e.ErrorCode===Ma)return console.warn(`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${o}`),o=50,this._pagingGetGroupList({isCommunityRelay:t,limit:o,offset:i,groupList:s});if(t)return e.code===ya&&console.log(`${this._name}._pagingGetGroupList ok. community unavailable`),s;throw e}}))}_pagingGetJoinedCommunityList(e){return g(this,void 0,void 0,(function*(){const{common:{getCurrentUserID:t},OuterConstant:s}=this._core,{groupList:n}=e;let{limit:o,offset:i}=e;try{const e=yield yc({limit:o,offset:i,type:s.GRP_COMMUNITY,memberAccount:t(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...pa],SelfInfoFilter:[...ma]}},this._core),{GroupIdList:r=[],TotalCount:a=0}=e||{},c=this._convertGroupKey(r);n.push(...c);const u=i+o,l=!(a>u),d=`offset:${i} limit:${o} total:${a} isCompleted:${l} current:${n.length}`;return console.log(`${this._name}._pagingGetJoinedCommunityList ok. ${d}`),l?n:(i=u,this._pagingGetJoinedCommunityList({limit:o,offset:i,groupList:n}))}catch(e){if(e.code===gc)return console.warn(`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${o}`),o=50,this._pagingGetJoinedCommunityList({limit:o,offset:i,groupList:n});throw e}}))}_groupListTreeShaking(e){const t=new Map([...Mc.getLocalGroupList()]);for(let s=0,n=e.length;s<n;s++)t.delete(e[s].groupID);const s=[...t.keys()];for(let e=0,t=s.length;e<t;e++)Mc.deleteLocalGroup(s[e])}_isSyncCompleted(){return this._pagingStatus===Ea}_convertGroupKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,Introduction:c,InviteJoinOption:u,LastInfoTime:l,LastMsgTime:d,MemberNum:h,MaxMemberNum:g,MuteAllMember:p,Name:_,NextMsgSeq:m,Notification:v,Owner_Account:f,Type:I,LastRecallTime:S,SelfInfo:E,AtInfoList:C=[],SupportTopic:M}=e[s],y=vc(n),O=this._convertSelfInfo(E),A=this._convertAtInfoList(a,C);t.push({groupCustomField:y,joinOption:o,createTime:i,avatar:r,groupID:a,introduction:c,inviteOption:u,lastInfoTime:l,lastMsgTime:d,memberCount:h,maxMemberCount:g,muteAllMembers:p,name:_,nextMessageSeq:m,notification:v,ownerID:f,type:I,selfInfo:O,_lastRevokedTime:S,_groupAtInfoList:A,isSupportTopic:M})}return t}_convertSelfInfo(e){const{JoinTime:t,MsgFlag:s,MsgSeq:n,NoUnreadSeqList:o,Role:i}=e;return{joinTime:t,messageRemindType:s,readedSequence:n,excludedUnreadSequenceList:o,role:i}}_convertAtInfoList(e,t){if(0===t.length)return[];const s=[];return t.forEach((t=>{const{AtFlagList:n,AtMsgSeq:o,From_Account:i}=t;s.push({groupID:e,groupAtType:n,sequence:o,from:i})})),s}};var Tc=new class{constructor(){this._name="CreateGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"createGroup",context:this})}createGroup(e){return g(this,void 0,void 0,(function*(){var t;this._preCheckParams(e);const{ssoLog:s,helper:{ChatError:n}}=this._core,o=s.createSSOLogData({method:"createGroup"});try{const{utils:{isEmpty:s},common:{getCurrentUserID:n}}=this._core,i=yield function(e,t){return g(this,void 0,void 0,(function*(){const{name:s,type:n,groupID:o,introduction:i,notification:r,avatar:a,maxMemberNum:c,joinOption:u,inviteOption:l,memberList:d,groupCustomField:h,isSupportTopic:g}=e;let p;d&&(p=d.map((e=>{const{userID:t,memberCustomField:s}=e;return{Member_Account:t,AppMemberDefinedData:s?fc(s):void 0}})));const _={Name:s,Type:n,GroupId:o,Introduction:i,Notification:r,FaceUrl:a,MaxMemberCount:c,ApplyJoinOption:u,InviteJoinOption:l,MemberList:p,AppDefinedData:h,SupportTopic:g,webPushFlag:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:_})}))}(Object.assign(Object.assign({},e),{ownerID:n()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:a=[]}=i||{};o.setLogInfo({message:`groupID:${r}`}).end(),console.log(`${this._name}.createGroup ok, type:${e.type} groupID:${r} overLimitUserIDList:${a}`),s(e.memberList)||s(a)||(e.memberList=null===(t=e.memberList)||void 0===t?void 0:t.filter((e=>a.includes(e.userID)))),Mc.updateLocalGroup([Object.assign(Object.assign({},e),{groupID:r})]);const c=Mc.getLocalGroup(r);return this._notNeedSendCustomMessage(e)||(this._sendCustomMessage(r,e.type),Mc.emitGroupListUpdate()),Oc({group:c})}catch(t){const{errorCode:s,errorInfo:i}=t,r=new n({functionName:"createGroup",code:s,message:i});throw o.setLogInfo({message:`groupID:${e.groupID||""}`}).setError(r).end(),console.error(`${this._name}.createGroup fail:`,r),r}}))}_preCheckParams(e){const{type:t,groupID:s}=e,{utils:{isEmpty:n,isUndefined:o},common:{isCommunity:i}}=this._core,r=!n(s);if(!(()=>{const{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:n,GRP_COMMUNITY:o}=oa.core.OuterConstant;return[e,t,s,n,o]})().includes(t))throw new this._core.helper.ChatError({code:Za});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:ec});o(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||o(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||o(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:ec});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!_c(e)}_canIUseJoinOption(e){return pc(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){const{isSupportTopic:t}=e;return!0===t}_notNeedSendCustomMessage(e){const{type:t,isSupportTopic:s}=e,{OuterConstant:{GRP_AVCHATROOM:n,GRP_COMMUNITY:o}}=this._core;return t===n||t===o&&1===s}_sendCustomMessage(e,t){var s,n,o,i,r,a;const{OuterConstant:c}=this._core;let u="Create Group",l=fa;t===c.GRP_COMMUNITY&&(u="Create Community",l=Ia);const d={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:u,cmd:l,opUser:this._core.store.get("login").userId,version:4})}},h=null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.createCustomMessage(d);null===(a=null===(r=null===(i=this._core)||void 0===i?void 0:i.message)||void 0===r?void 0:r.messageSender)||void 0===a||a.sendMessage(h,{})}};var Rc=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach((e=>{e.localMainSequence=0}))}isGroupAttributesUpdated(e){const{elements:{newGroupProfile:t}}=e,{utils:{isEmpty:s,isUndefined:n}}=this._core;return!n(t)&&!s(t.groupAttributeOption)}handleGroupAttributesUpdated(e){const{groupID:t,groupAttributeOption:s}=e,{serverMainSequence:n,groupAttributeList:o=[],operation:i}=s;console.log(`${this._name}.handleGroupAttributesUpdated groupID:${t} operation:${i}`);const{utils:{isUndefined:r}}=this._core;r(i)||(this.refreshGroupAttributesCache({groupID:t,serverMainSequence:n,groupAttributeList:o,operation:i}),this.emitGroupAttributesUpdated(t))}initGroupAttributesCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupAttributesCache.set(t,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:s,values:new Map}),console.log(`${this._name}.initGroupAttributesCache. groupID:${t} avChatRoomKey:${s}`)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){const{groupID:t,serverMainSequence:s,groupAttributeList:n,operation:o}=e;if(this.hasGroupAttributesCache(t)){const e=this.getGroupAttributesCache(t),{localMainSequence:i}=e;o!==Ua&&s-i!=1||(e.serverMainSequence=s,e.localMainSequence=s,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:o})),s-i>1&&(e.serverMainSequence=s),this._groupAttributesCache.set(t,e),console.log(`${this._name}.refreshGroupAttributesCache. operation:${o} localMainSequence:${i} serverMainSequence:${s}`)}}_updateGroupAttributesCacheValues(e){const{groupAttributes:t,groupAttributeList:s=[],operation:n}=e;n!==Ga?n!==wa?(n===Na&&t.values.clear(),s.forEach((e=>{const{key:s,value:n,sequence:o}=e;t.values.set(s,{value:n,sequence:o})}))):s.forEach((e=>{t.values.delete(e.key)})):t.values.clear()}getGroupAttributesCacheValues(e){var t;const{groupID:s,keyList:n=[]}=e,o={};if(this.hasGroupAttributesCache(s)){const{values:e}=this.getGroupAttributesCache(s);if(0===n.length){for(const s of e.keys())o[s]=(null===(t=e.get(s))||void 0===t?void 0:t.value)||"";return o}return n.forEach((t=>{var s;e.has(t)&&(o[t]=(null===(s=e.get(t))||void 0===s?void 0:s.value)||"")})),o}return o}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t;const s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:n,deletedKeyList:o}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${n.length}, delete count:${o.length}`),0===n.length&&0===o.length||this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:n,deletedKeyList:o}})}_computeValuesChangedData(e){const{utils:{isUndefined:t}}=this._core,s=[],n=[];return Object.keys(e).forEach((t=>{e[t]!==this._groupAttributesCacheValuesCopy[t]&&s.push(t)})),Object.keys(this._groupAttributesCacheValuesCopy).forEach((s=>{t(e[s])&&n.push(s)})),this._groupAttributesCacheValuesCopy={},{updatedKeyList:s,deletedKeyList:n}}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(e){const t=[];return Object.keys(e).forEach((s=>{t.push({key:s,value:e[s]})})),t}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}};var Dc=new class{constructor(){this._name="DismissGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}dismissGroup(e){return g(this,void 0,void 0,(function*(){console.log(`${this._name}.dismissGroup groupID:${e}`);const{ssoLog:t,helper:{ChatError:s}}=this._core,n=t.createSSOLogData({method:"dismissGroup"});n.setLogInfo({message:`groupID:${e}`});try{yield function(e,t){return g(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:s})}))}(e,this._core),n.end(),console.log(`${this._name}.dismissGroup ok.`);const{type:t}=Mc.getLocalGroup(e);return Mc.deleteLocalGroup(e),Mc.emitGroupListUpdate(),Rc.deleteGroupAttributesCache(e),Oc({groupID:e,type:t})}catch(e){const{errorCode:t,errorInfo:o}=e,i=new s({functionName:"dismissGroup",code:t,message:o});throw n.setError(i).end(),console.error(`${this._name}.dismissGroup fail:`,i),i}}))}};var bc=new class{constructor(){this._name="GetGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(e){return g(this,void 0,void 0,(function*(){const{groupID:t,groupCustomFieldFilter:s}=e,n={groupIDList:[t],responseFilter:{GroupBaseInfoFilter:[...pa],AppDefinedDataFilter_Group:s,MemberInfoFilter:[...va]}},{ssoLog:o,helper:{ChatError:i}}=this._core,r=o.createSSOLogData({method:"getGroupProfile"});r.setLogInfo({message:`groupID:${t}`});try{const e=yield this.getGroupProfileAdvance(n),{successGroupList:s,failureGroupList:o}=e;if(o.length>0)throw o[0];let i;return!Mc.hasLocalGroup(t)&&_c(s[0].type)?i=new Cc(s[0]):(Mc.updateLocalGroup(s),i=Mc.getLocalGroup(t)),i.isSupportTopic||Mc.updateConversationGroupProfile(t),r.end(),console.log(`${this._name}.getGroupProfile ok.`),Oc({group:i})}catch(e){const{code:t,message:s}=e,n=new i({functionName:"getGroupProfile",code:t,message:s});throw r.setError(n).end(),console.error(`${this._name}.getGroupProfile fail:`,n),e}}))}getGroupProfileAdvance(e){return g(this,void 0,void 0,(function*(){const{groupIDList:t}=e,{common:{isCommunity:s}}=this._core,n=t.filter((e=>!s({groupID:e}))),o=t.filter((e=>s({groupID:e})));n.length>50&&(n.length=50),o.length>50&&(o.length=50);const i=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:n})),this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:o,isCommunityProfile:!0}))]),r=[],a=[];return i.forEach((e=>{r.push(...e.successGroupList),a.push(...e.failureGroupList)})),{successGroupList:r,failureGroupList:a}}))}_getGroupProfileAdvance(e){return g(this,void 0,void 0,(function*(){const{isCommunityProfile:t=!1}=e,s=h(e,["isCommunityProfile"]);if(0===s.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:n}=e,o={GroupIdList:s,ResponseFilter:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:o})}))}(s,this._core),{GroupInfo:t=[]}=e||{},n=this._convertGroupProfileKey(t),{utils:{isUndefined:o}}=this._core,i=n.filter((e=>o(e.errorCode)||0===e.errorCode)),r=n.filter((e=>e.errorCode&&0!==e.errorCode)).map((e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}})));return console.log(`${this._name}._getGroupProfileAdvance ok, groupID:${s.groupIDList.join(",")}`),{successGroupList:i,failureGroupList:r}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}}))}_convertGroupProfileKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,InfoSeq:c,Introduction:u,InviteJoinOption:l,LastInfoTime:d,LastMsgTime:h,MaxMemberNum:g,MemberNum:p,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,ShutUpAllMember:S,ShutUpUntil:E,Type:C,MemberList:M,ErrorCode:y,ErrorInfo:O}=e[s],A=vc(n),T=this._convertMembers(M);t.push({groupCustomField:A,joinOption:o,createTime:i,avatar:r,groupID:a,infoSequence:c,introduction:u,inviteOption:l,lastInfoTime:d,lastMsgTime:h,maxMemberCount:g,memberCount:p,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,shutUpAllMember:S,muteUntil:E,type:C,members:T,errorCode:y,errorInfo:O})}return t}_convertMembers(e){if(!e)return[];const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,MsgFlag:r,MsgSeq:a,NameCard:c,Role:u}=e[s],l=vc(n);t.push({memberCustomField:l,joinTime:o,userID:i,messageRemindType:r,sequence:a,nameCard:c,role:u})}return t}};var Lc=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:o,groupCounterSeq:i}=this.getLocalGroupCounters(t);if(n>0&&n<i)return;s.forEach((t=>{const{Key:s,Value:n=0}=t;e.set(s,n)})),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:e,avChatRoomKey:o})}}initGroupCountersCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupCountersMap.set(t,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:s})}getLocalCounters(e,t){const s={};if(!this._hasLocalGroupCounters(e))return s;const{counters:n}=this.getLocalGroupCounters(e);if(t.length>0)t.forEach((e=>{n.has(e)&&(s[e]=n.get(e))}));else for(const e of n.keys())s[e]=n.get(e);return s}deleteLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:o}=this.getLocalGroupCounters(t);s.forEach((t=>{e.delete(t.key)})),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:e,avChatRoomKey:o})}}setGroupCounters(e,t){if(!this._hasLocalGroupCounters(e))return;const s=this.getLocalGroupCounters(e),{counters:n}=s;let o=!1;Object.entries(t).forEach((([e,t])=>{n.has(e)&&n.get(e)!==t&&(n.set(e,t),o=!0)})),o&&this._groupCountersMap.set(e,Object.assign(Object.assign({},s),{lastUpdateTime:Date.now(),counters:n}))}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}};var Nc=new class{constructor(){this._name="JoinGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}joinGroup(e){return g(this,void 0,void 0,(function*(){const{groupID:t}=e,{ssoLog:s,ChatError:n,OuterConstant:o}=this._core,i=s.createSSOLogData({method:"joinGroup"});try{if(Mc.hasLocalGroup(t))try{return yield bc.getGroupProfile({groupID:t}),i.setLogInfo({message:`groupID:${t} joinedStatus:${o.JOIN_STATUS_ALREADY_IN_GROUP}`}).end(),Oc({status:o.JOIN_STATUS_ALREADY_IN_GROUP})}catch(s){console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),Mc.deleteLocalGroup(t);const n=yield this._applyJoinGroup(e);return i.setLogInfo({message:`groupID:${t}`}).end(),n}const s=yield this._applyJoinGroup(e);return i.setLogInfo({message:`groupID:${t}`}).end(),s}catch(e){const{errorCode:t,errorInfo:s}=e,o=new n({functionName:"joinGroup",code:t,message:s});throw i.setError(o).end(),console.error(`${this._name}.joinGroup fail:`,e),e}}))}_applyJoinGroup(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:t,helper:s}=this._core,{groupID:n}=e,o=Object.assign({},e),i=s.checkBusinessCapabilityBits(ra);i&&(o.historyMessageFlag=1);const r=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,applyMessage:n,historyMessageFlag:o}=e,i={GroupId:s,ApplyMsg:n,HugeGroupHistoryMsgFlag:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:i})}))}(o,this._core),{Type:a,JoinedStatus:c,LongPollingKey:u,StartSeq:l,HugeGroupFlag:d,AVChatRoomKey:h,RspMsgList:p=[]}=r||{},_=`groupID:${n} joinedStatus:${c} longPollingKey:${u} startSeq:${l} avChatRoomFlag:${d} canGetAVChatRoomHistoryMsg:${i}, historyMessageCount:${p.length}`;if(console.log(`${this._name}._applyJoinGroup ok, ${_}`),c===t.JOIN_STATUS_WAIT_APPROVAL)return Oc({status:t.JOIN_STATUS_WAIT_APPROVAL,group:{groupID:n,type:a}});if(c===t.JOIN_STATUS_SUCCESS){let e=null;try{e=(yield bc.getGroupProfile({groupID:n})).data.group}catch(t){e=new Cc({groupID:n}),console.warn(`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${n}, errorCode:`,null==t?void 0:t.code)}return this._handleJoinResult({group:e,avChatRoomFlag:d,longPollingKey:u,startSequence:l,avChatRoomKey:h,historyMessageList:p})}throw new this._core.helper.ChatError({code:ic})}))}_handleJoinResult(e){const{group:t,avChatRoomFlag:s,avChatRoomKey:n}=e;return 1===s?(Rc.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:n}),Lc.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:n}),Oc(e)):(Mc.updateLocalGroup([t]),Mc.emitGroupListUpdate(),Oc({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}};var Pc=new class{constructor(){this._name="QuitGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}quitGroup(e){return g(this,void 0,void 0,(function*(){if(!Mc.hasLocalGroup(e))throw new this._core.helper.ChatError({code:oc});const{ssoLog:t,helper:{ChatError:s}}=this._core,n=t.createSSOLogData({method:"quitGroup"});n.setLogInfo({message:`groupID:${e}`});try{yield function(e,t){return g(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:s})}))}(e,this._core),n.end(),console.log(`${this._name}.quitGroup ok, groupID:${e}`);const{type:t}=Mc.getLocalGroup(e);return Mc.deleteLocalGroup(e),Mc.emitGroupListUpdate(),Rc.deleteGroupAttributesCache(e),Oc({groupID:e,type:t})}catch(e){const{errorCode:t,errorInfo:o}=e,i=new s({functionName:"quitGroup",code:t,message:o});throw n.setError(i).end(),console.error(`${this._name}.quitGroup fail:`,i),i}}))}};var Gc=new class{constructor(){this._name="SearchGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(e){return g(this,void 0,void 0,(function*(){console.log(`${this._name}.searchGroupByID groupID:${e}`);try{const t=yield function(e,t){return g(this,void 0,void 0,(function*(){const s={GroupIdList:[e],GroupBasePublicInfoFilter:[..._a]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:s})}))}(e,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:n=[],ApplyJoinOption:o,CreateTime:i,FaceUrl:r,Introduction:a,InviteJoinOption:c,MaxMemberNum:u,MemberNum:l,Name:d,Owner_Account:h,Type:p,ErrorCode:_,ErrorInfo:m}=s[0];if(0!==_)throw new this._core.helper.ChatError({code:_,message:m});console.log(`${this._name}.searchGroupByID ok.`);const v=vc(n),f=new Cc({groupID:e,name:d,avatar:r,introduction:a,joinOption:o,inviteOption:c,maxMemberCount:u,memberCount:l,type:p,ownerID:h,createTime:i,groupCustomField:v});return Oc({group:f})}catch(e){throw console.error(`${this._name}.searchGroupByID fail:`,e),e}}))}};var wc=new class{constructor(){this._name="UpdateGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(e){return g(this,void 0,void 0,(function*(){const{groupID:t}=e,{utils:{isUndefined:s}}=this._core;let n=Mc.getLocalGroup(t);if(n){const{type:t}=n;this._canIUseJoinOption(t)||s(e.joinOption)||(console.warn(`${this._name}.updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom`),e.joinOption=void 0)}s(e.muteAllMembers)||(e.muteAllMembers=!0===e.muteAllMembers?"On":"Off");try{return yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,name:n,avatar:o,introduction:i,notification:r,muteAllMembers:a,joinOption:c,inviteOption:u,groupCustomField:l}=e,d={GroupId:s,Name:n,FaceUrl:o,Introduction:i,Notification:r,ShutUpAllMember:a,ApplyJoinOption:c,InviteJoinOption:u,AppDefinedData:l?fc(l):void 0};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:d})}))}(e,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),n?(n.updateGroup(e),Mc.emitGroupListUpdate()):n=new Cc(e),Oc({group:n})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}}))}_canIUseJoinOption(e){return pc(e)||this._core.common.isCommunity({type:e})}};var Uc=new class{constructor(){this._name="ChangeGroupOwner"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(e){return g(this,void 0,void 0,(function*(){const t="changeGroupOwner",{groupID:s,newOwnerID:n}=e,o=Mc.getLocalGroup(s),{helper:i,OuterConstant:r,common:{getCurrentUserID:a}}=this._core;if((null==o?void 0:o.type)===r.GRP_AVCHATROOM)throw new i.ChatError({functionName:t,code:sc});if(n===a())throw new i.ChatError({functionName:t,code:nc});console.log(`${this._name}.${t} groupID:${s} newOwnerID:${n}`);try{return yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,newOwnerID:n}=e,o={GroupId:s,NewOwner_Account:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:o})}))}(e,this._core),console.log(`${this._name}.${t} ok.`),o.ownerID=n,Mc.emitGroupListUpdate(),Oc({group:o})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var kc=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}getGroupOnlineMemberCount(e){return g(this,void 0,void 0,(function*(){const t="getGroupOnlineMemberCount",s=Mc.hasLocalGroup(e);if(console.log(`${this._name}.${t} groupID:${e} hasLocalGroup:${s}`),!s)return Oc({memberCount:0});const n=Date.now();if(this._onlineMemberCountMap.has(e)){const t=this._onlineMemberCountMap.get(e),{lastReqTime:s=0,memberCount:o=0}=t||{};if(n-s<=6e4)return Oc({memberCount:o})}try{const s=yield function(e,t){return g(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})}))}(e,this._core),{OnlineMemberNum:n=0}=s||{};return this._onlineMemberCountMap.set(e,{lastReqTime:Date.now(),memberCount:n}),console.log(`${this._name}.${t} ok. groupID:${e} memberCount:${n}`),Oc({memberCount:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Fc=new class{init(e,t){console.log("GroupAction.init"),Ac.init(e),Tc.init(e),Dc.init(e,t),Nc.init(e,t),Pc.init(e,t),Gc.init(e),bc.init(e),wc.init(e),Uc.init(e),kc.init(e,t)}dismissGroup(e){return Dc.dismissGroup(e)}joinGroup(e){return Nc.joinGroup(e)}quitGroup(e){return Pc.quitGroup(e)}getGroupOnlineMemberCount(e){return kc.getGroupOnlineMemberCount(e)}};var $c=new class{constructor(){this._name="GetGroupApplicationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return g(this,void 0,void 0,(function*(){const e="getGroupApplicationList";try{const t=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);console.log(`${this._name}.${e} ok.`);const s=this._handleGroupApplicationResult([...t[0],...t[1]]);return Oc({applicationList:s})}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${this._name}.${e} fail:`,s),s}}))}_getGroupApplicationList(e){return g(this,void 0,void 0,(function*(){const{type:t,startTime:s=0,limit:n=20}=e||{},{common:o}=this._core;let i;try{i=yield function(e,t){return g(this,void 0,void 0,(function*(){const{type:s,startTime:n,limit:o,handleAccount:i}=e,r={Type:s,StartTime:n,Limit:o,Handle_Account:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:r})}))}({type:t,startTime:s,limit:n,handleAccount:o.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}const{NextStartTime:r=0,PendencyList:a=[]}=i||{};if(0===r)return a;const c=yield this._getGroupApplicationList(Object.assign(Object.assign({},e),{startTime:r}));return[...a,...c]}))}_handleGroupApplicationResult(e){const t=[];return e.forEach((e=>{const s=this._convertApplicationData(e),{handled:n}=s,o=h(s,["handled"]);0===n&&t.push(o)})),t}_convertApplicationData(e){const{Handled:t,AddTime:s,ApplyInviteMsg:n,Authentication:o,FromUserNickName:i,From_Account:r,GroupId:a,GroupName:c,PendencyType:u,To_Account:l}=e;return{handled:t,messageKey:s,applicant:r,applicantNick:i,groupID:a,groupName:c,authentication:o,applicationType:u,userID:l,note:n}}};var xc=new class{constructor(){this._name="HandleGroupApplication"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return g(this,void 0,void 0,(function*(){const t="handleGroupApplication",{application:s}=e,n=this._handleParams(e);try{(null==s?void 0:s.applicationType)===Oa?yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,invitee:a}=e,c={GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,Invited_Account:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:c})}))}(n,this._core):yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,messageKey:a}=e,c={GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,MsgKey:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:c})}))}(n,this._core),console.log(`${this._name}.${t} ok.`);const e=Mc.getLocalGroup(n.groupID);return Oc({group:e})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleParams(e){var t;const{handleAction:s,handleMessage:n,message:o,application:i}=e;let r,a,c,u,l;if(o){const{payload:e}=o||{};r=e.operatorID,a=null===(t=e.groupProfile)||void 0===t?void 0:t.groupID,c=e.authentication,u=e.messageKey}else r=(null==i?void 0:i.applicant)||"",a=(null==i?void 0:i.groupID)||"",c=(null==i?void 0:i.authentication)||"",u=(null==i?void 0:i.messageKey)||0;return(null==i?void 0:i.applicationType)===Oa&&(l=i.userID),{handleAction:s,handleMessage:n,applicant:r,invitee:l,groupID:a,authentication:c,messageKey:u}}};var qc=new class{init(e){console.log("GroupApplication.init"),$c.init(e),xc.init(e)}};let Vc=class{constructor(e){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(e)}updateMember(e){const{core:{utils:{isUndefined:t},common:{deepMerge:s}}}=oa;t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus);const n=[null,void 0,"",0,NaN];e.memberCustomField&&mc(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],n)}};function Bc(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,userID:n,muteTime:o,role:i,nameCard:r,memberCustomField:a}=e;let c;a&&(c=fc(a));const u={GroupId:s,Member_Account:n,ShutUpTime:o,Role:i,NameCard:r,AppMemberDefinedData:c};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:u})}))}var jc=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}getGroupMemberList(e){return g(this,void 0,void 0,(function*(){const t="getGroupMemberList",{groupID:s,offset:n=0,count:o=100,role:i="",filter:r=""}=e;console.log(`${this._name}.${t} groupID:${s} offset:${n} count:${o} role:${i} filter:${r}`);const a=Mc.getLocalGroup(s),c=o>100?100:o,u={groupID:s,offset:n,limit:c,memberRoleFilter:Aa.includes(i)?[i]:void 0,memberInfoFilter:Ta};try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,offset:n,limit:o,memberRoleFilter:i,memberInfoFilter:r}=e,a={GroupId:s,Offset:n,Limit:o,MemberRoleFilter:i,MemberInfoFilter:r};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:a})}))}(u,this._core),{MemberList:o,MemberNum:i,Next:r}=e||{};console.log(`${this._name}.${t} ok, totalMemberCount:${i} next:${r}`);const{utils:{isArray:l,isEmpty:d},common:{isCommunity:h}}=this._core;if(a&&(a.memberCount=i),!l(o)||0===o.length)return Oc({memberList:[],offset:0});let p=n+c;h({groupID:s})&&(p=d(r)?0:r),o.length<c&&(p=0);let _=this._convertMemberInfo(o);_=yield this._patchAvatarAndNick(_);const m=this._generateGroupMember(_);return Oc({memberList:m,offset:p})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],u=vc(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:u})}return t}_patchAvatarAndNick(e){return g(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=new Vc(e[s]);t.push(n)}return t}};var Kc=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(e){return g(this,void 0,void 0,(function*(){const t="getGroupMemberProfile",{groupID:s,userIDList:n,memberCustomFieldFilter:o}=e,i=Mc.getLocalGroup(s),{helper:r,utils:{isArray:a}}=this._core;if(i&&_c(i.type))throw new r.ChatError({functionName:t,replacement1:t,code:dc});n.length>50&&(console.warn(`${this._name}.${t} userIDList length:${n.length} exceeds limit 50`),n.splice(50));try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n,memberInfoFilter:o,memberCustomFieldFilter:i}=e,r={GroupId:s,Member_List_Account:n,MemberInfoFilter:o,AppDefinedDataFilter_GroupMember:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:r})}))}({groupID:s,userIDList:n,memberCustomFieldFilter:o,memberInfoFilter:[...Ta]},this._core);console.log(`${this._name}.${t} ok.`);const{MemberList:i}=e||{};if(!a(i)||0===i.length)return Oc({memberList:[]});let r=this._convertMemberInfo(i);r=yield this._getMemberAvatarAndNick(r);const c=this._generateGroupMember(r);return Oc({memberList:c})}catch(e){const s=new r.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}}))}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],u=vc(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:u})}return t}_getMemberAvatarAndNick(e){return g(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=new Vc(e[s]);t.push(n)}return t}};var Hc=new class{constructor(){this._name="AddGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(e){return g(this,void 0,void 0,(function*(){const t="addGroupMember",{groupID:s,userIDList:n}=e,o=Mc.getLocalGroup(s),{helper:i}=this._core;if(o&&_c(o.type))throw new i.ChatError({functionName:t,code:rc});const r=n.map((e=>({Member_Account:e})));try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n}=e,o={GroupId:s,MemberList:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:o})}))}({groupID:s,userIDList:r},this._core),{MemberList:n=[]}=e||{},{failureUserIDList:i,successUserIDList:a,existedUserIDList:c,overLimitUserIDList:u}=this._handleResult(n);return console.log(`${this._name}.${t} groupID:${s} ok, successUserIDList:${a} failureUserIDList:${i} existedUserIDList:${c} overLimitUserIDList:${u}`),Oc({failureUserIDList:i,successUserIDList:a,existedUserIDList:c,overLimitUserIDList:u,group:o})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleResult(e){const t=[],s=[],n=[],o=[];return e.forEach((e=>{const{Result:i,Member_Account:r}=e;i===Ra?t.push(r):i===Da?s.push(r):i===ba?n.push(r):i===La&&o.push(r)})),{failureUserIDList:t,successUserIDList:s,existedUserIDList:n,overLimitUserIDList:o}}};var Wc=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}deleteGroupMember(e){return g(this,void 0,void 0,(function*(){const t="deleteGroupMember",{groupID:s,userIDList:n}=e,o=Mc.getLocalGroup(s),{helper:i,utils:{isUndefined:r}}=this._core;if(r(o))throw new i.ChatError({functionName:t,code:tc});n.length>20&&(console.warn(`${this._name}.${t} userIDList length:${n.length} exceeds limit 20`),n.splice(20));try{return yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n,reason:o}=e,i={GroupId:s,MemberToDel_Account:n,Reason:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:i})}))}({groupID:s,userIDList:n},this._core),console.log(`${this._name}.${t} ok, groupID:${s} userIDList length:${n.length}`),Oc({group:o,userIDList:n})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Yc=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(e){return g(this,void 0,void 0,(function*(){const t="setGroupMemberMuteTime",{helper:s}=this._core;this._preCheckSettingMuteParams(e);try{yield Bc(e,this._core);const{groupID:s,userID:n,muteTime:o}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} muteTime:${o}`);const i=Mc.getLocalGroup(s),r=new Vc({userID:n,muteTime:o});return Oc({group:i,member:r})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingMuteParams(e){const{userID:t}=e,{store:s,helper:n}=this._core;if(t===s.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:lc})}};var zc=new class{constructor(){this._name="SetGroupMemberRole"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(e){return g(this,void 0,void 0,(function*(){const t="setGroupMemberRole",{helper:s}=this._core;this._preCheckSettingRoleParams(e);try{yield Bc(e,this._core);const{groupID:s,userID:n,role:o}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} role:${o}`);const i=Mc.getLocalGroup(s),r=new Vc({userID:n,role:o});return Oc({group:i,member:r})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingRoleParams(e){var t;const{groupID:s,userID:n,role:o}=e,{store:i,helper:r,OuterConstant:a,common:{isCommunity:c}}=this._core,u=Mc.getLocalGroup(s);if((null===(t=null==u?void 0:u.selfInfo)||void 0===t?void 0:t.role)!==a.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:ac});if(n===i.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:uc});const l=[...Aa];if(c({groupID:s})&&l.push(a.GRP_MBR_ROLE_CUSTOM),!l.includes(o))throw new r.ChatError({functionName:"setGroupMemberRole",code:cc})}};var Jc=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(e){return g(this,void 0,void 0,(function*(){const t="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(e);try{const{groupID:s,userID:o=n(),nameCard:i}=e,r={groupID:s,userID:o,nameCard:i};yield Bc(r,this._core),console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} nameCard:${i}`);const a=Mc.getLocalGroup(s),c=new Vc({userID:o,nameCard:i});return Oc({group:a,member:c})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingNameCardParams(e){const{groupID:t}=e,{helper:s}=this._core,n=Mc.getLocalGroup(t);if(_c(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberNameCard",code:dc})}};var Qc=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(e){return g(this,void 0,void 0,(function*(){const t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingCustomFiledParams(e);try{const{groupID:s,userID:o=n(),memberCustomField:i}=e,r={groupID:s,userID:o,memberCustomField:i};yield Bc(r,this._core),console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} memberCustomField:${JSON.stringify(i)}`);const a=Mc.getLocalGroup(s),c=new Vc({userID:o,memberCustomField:i});return Oc({group:a,member:c})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingCustomFiledParams(e){const{groupID:t}=e,{helper:s}=this._core,n=Mc.getLocalGroup(t);if(_c(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberCustomField",code:dc})}};var Xc=new class{init(e,t){console.log("GroupMember.init"),jc.init(e,t),Kc.init(e),Hc.init(e),Wc.init(e,t),Yc.init(e),zc.init(e),Jc.init(e),Qc.init(e)}getGroupMemberList(e){return jc.getGroupMemberList(e)}deleteGroupMember(e){return Wc.deleteGroupMember(e)}};var Zc=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(e){return g(this,void 0,void 0,(function*(){const t="getGroupCounters";try{Ic(t,aa);const{groupID:s,keyList:n=[]}=e,{avChatRoomKey:o,lastUpdateTime:i}=Lc.getLocalGroupCounters(s);if(!(Date.now()-i>=this._getExpireTime())){return{code:0,data:{counters:Lc.getLocalCounters(s,n)}}}const r=yield function(e){return g(this,void 0,void 0,(function*(){const{groupID:t,GroupCounterKeys:s,avChatRoomKey:n}=e,{common:o}=oa.core,i={GroupId:t,keyList:s,BytesKey:n};return o.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:i})}))}({groupID:s,keyList:n,avChatRoomKey:o}),{GroupCounter:a=[],GroupCounterSeq:c}=r;Lc.updateLocalGroupCounters({groupID:s,counterList:a,groupCounterSeq:c});return{code:0,data:{counters:Lc.getLocalCounters(s,n)}}}catch(e){Sc(t,e)}}))}_getExpireTime(){const{store:e,utils:{isUndefined:t}}=this._core,s=e.get("cloudConfig")||{},{grp_counter_expire_time:n}=s;return t(n)?3e4:Number(n)}};var eu=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"setGroupCounters",context:this}),t.registerApi({apiName:"increaseGroupCounter",context:this}),t.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return g(this,void 0,void 0,(function*(){return this._handleCounterOperation(ca,e)}))}increaseGroupCounter(e){return g(this,void 0,void 0,(function*(){return this._handleCounterOperation(ua,e)}))}decreaseGroupCounter(e){return g(this,void 0,void 0,(function*(){return this._handleCounterOperation(la,e)}))}_handleCounterOperation(e,t){return g(this,void 0,void 0,(function*(){const s=`${e}GroupCounter`;try{Ic(s,aa);const{groupID:n,key:o,value:i=0}=t,{avChatRoomKey:r}=Lc.getLocalGroupCounters(n),a=e===ca?this._convertObjectToList(t.counters):[{Key:o,Value:i}],c=yield this._updateGroupCounters({groupID:n,counterList:a,avChatRoomKey:r,mode:e});return Lc.setGroupCounters(n,c),{code:0,data:{counters:c}}}catch(e){Sc(s,e)}}))}_updateGroupCounters(e){return g(this,void 0,void 0,(function*(){const t=yield function(e){const{groupID:t,counterList:s,mode:n,avChatRoomKey:o}=e,{common:i}=oa.core,r={GroupId:t,GroupCounter:s,Mode:n,BytesKey:o};return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:r})}(e),{GroupCounter:s=[]}=t,n={};return s.forEach((e=>{const{Key:t,Value:s=0}=e;n[t]=s})),n}))}_convertObjectToList(e){return Object.entries(e).map((([e,t])=>({Key:e,Value:t||0})))}};var tu=new class{init(e){this._core=e,Zc.init(e),eu.init(e)}isGroupCounterUpdated(e){const{elements:{groupCounterInfo:t}}=e,{utils:{isEmpty:s}}=this._core;return!s(t)}handleGroupCounterUpdated(e){const{to:t,elements:{groupCounterInfo:s}}=e;s.forEach((e=>{const{type:s,groupCounterSeq:n,counterList:o=[]}=e;s!==da&&s!==ga||this._processAndNotifyCounterUpdate(t,n,o),s===ha&&Lc.deleteLocalGroupCounters({groupID:t,groupCounterSeq:n,counterList:o})}))}_processAndNotifyCounterUpdate(e,t,s){const{OuterEvent:n,notificationCenter:o}=this._core;Lc.updateLocalGroupCounters({groupID:e,groupCounterSeq:t,counterList:s}),s.forEach((({Key:t,Value:s=0})=>{o.emitOuterEvent(n.GROUP_COUNTER_UPDATED,{name:n.GROUP_COUNTER_UPDATED,data:{groupID:e,key:t,value:s}})}))}reset(){Lc.reset()}};var su=new class{constructor(){this._name="InitGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return g(this,void 0,void 0,(function*(){const t="initGroupAttributes",{groupID:s,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:i}=Rc.getGroupAttributesCache(s),r=Rc.convertKeyValueMapToList(n);try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:r})}))}({groupID:s,avChatRoomKey:i,groupAttributeList:r,mainSequence:o},this._core),{AttrMainSeq:a,GroupAttr:c}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${a}`);const u=c.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:n[t],sequence:s}}));return Rc.saveGroupAttributesCacheValuesCopy(s),Rc.refreshGroupAttributesCache({groupID:s,serverMainSequence:a,groupAttributeList:u,operation:Na}),Rc.emitGroupAttributesUpdated(s),Oc({groupAttributes:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var nu=new class{constructor(){this._name="SetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return g(this,void 0,void 0,(function*(){const t="setGroupAttributes",{groupID:s,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:i,values:r}=Rc.getGroupAttributesCache(s),a=Rc.convertKeyValueMapToList(n).map((e=>{var t;const{key:s,value:n}=e;return{key:s,value:n,seq:(null===(t=r.get(e.key))||void 0===t?void 0:t.sequence)||0}}));try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:r})}))}({groupID:s,avChatRoomKey:i,groupAttributeList:a,mainSequence:o},this._core),{AttrMainSeq:r,GroupAttr:c}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${r}`);const u=c.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:n[t],sequence:s}}));return Rc.saveGroupAttributesCacheValuesCopy(s),Rc.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:u,operation:Pa}),Rc.emitGroupAttributesUpdated(s),Oc({groupAttributes:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var ou=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(e){return g(this,void 0,void 0,(function*(){const t="deleteGroupAttributes",{groupID:s,keyList:n=[]}=e;try{let e;e=0===n.length?yield this._clearGroupAttributes(s):yield this._deleteGroupAttributes(s,n);const{resultList:o,serverMainSequence:i,operation:r,groupAttributeList:a}=e||{};return console.log(`${this._name}.${t} ok. groupID:${s} operation: ${r}`),Rc.saveGroupAttributesCacheValuesCopy(s),Rc.refreshGroupAttributesCache({groupID:s,serverMainSequence:i,groupAttributeList:a,operation:r}),Rc.emitGroupAttributesUpdated(s),Oc({keyList:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_deleteGroupAttributes(e,t){return g(this,void 0,void 0,(function*(){const{serverMainSequence:s,avChatRoomKey:n,values:o}=Rc.getGroupAttributesCache(e),i=[],r=[];t.forEach((e=>{if(o.has(e)){const{sequence:t=0}=o.get(e)||{};r.push({key:e,seq:t}),i.push(e)}}));const a=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:r})}))}({groupID:e,avChatRoomKey:n,groupAttributeList:r,mainSequence:s},this._core),{AttrMainSeq:c}=a||{};return{resultList:i,serverMainSequence:c,groupAttributeList:r,operation:wa}}))}_clearGroupAttributes(e){return g(this,void 0,void 0,(function*(){const{serverMainSequence:t,avChatRoomKey:s,values:n}=Rc.getGroupAttributesCache(e),o=[...n.keys()],i=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,avChatRoomKey:o}=e,i={GroupId:s,AttrMainSeq:n,BytesKey:o,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:i})}))}({groupID:e,avChatRoomKey:s,mainSequence:t},this._core),{AttrMainSeq:r}=i||{};return{resultList:o,serverMainSequence:r,operation:Ga}}))}};var iu=new class{constructor(){this._name="GetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(e){return g(this,void 0,void 0,(function*(){const t="getGroupAttributes",{groupID:s}=e,{avChatRoomKey:n,lastUpdateTime:o,localMainSequence:i,serverMainSequence:r}=Rc.getGroupAttributesCache(s),{ssoLog:a,helper:{ChatError:c}}=this._core,u=a.createSSOLogData({method:"getGroupAttributes"});u.setLogInfo({message:`groupID:${s} localMainSequence:${i} serverMainSequence:${r} keyList:${e.keyList}`});if(Date.now()-o>=3e4||i<r)try{const o=yield this.getGroupAttributesFromServer({groupID:s,avChatRoomKey:n}),i=Rc.getGroupAttributesCacheValues(e),{serverGroupAttributeList:r=[]}=o||{};return u.setLogInfo({moreMessage:`from server, count:${r.length}`}).end(),console.log(`${this._name}.${t} from server. groupID:${s}`),Oc({groupAttributes:i})}catch(e){const s=new c({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw u.setError(s).end(),console.error(`${this._name}.${t} fail:`,s),s}const l=Rc.getGroupAttributesCacheValues(e);return u.setLogInfo({moreMessage:"from cache."}).end(),console.log(`${this._name}.${t} from cache. groupID:${s}`),Oc({groupAttributes:l})}))}getGroupAttributesFromServer(e){return g(this,void 0,void 0,(function*(){const{utils:{isUndefined:t}}=this._core,{groupID:s,avChatRoomKey:n}=e,o=t(n)?Fa:ka,i=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,groupType:n,avChatRoomKey:o}=e,i={GroupId:s,GroupType:n,Key:o};return t.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:i})}))}({groupID:s,avChatRoomKey:n,groupType:o},this._core),{AttrMainSeq:r=0,GroupAttrAry:a}=i||{};console.log(`${this._name}._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:${r}`);const c=a.map((e=>{const{key:t,value:s,seq:n}=e;return{key:t,value:s,sequence:n}}));return Rc.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:c,operation:Ua}),{serverGroupAttributeList:a}}))}};var ru=new class{init(e){console.log("GroupAttribute.init"),su.init(e),nu.init(e),ou.init(e),iu.init(e),Rc.init(e)}isGroupAttributesUpdated(e){return Rc.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){const{to:t,elements:{newGroupProfile:s}}=e,{groupAttributeOption:n}=s,{serverMainSequence:o,withChangedAttributeInfo:i}=n,{localMainSequence:r}=Rc.getGroupAttributesCache(t),a=o-r;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:${a}`),0!==a)if(Rc.saveGroupAttributesCacheValuesCopy(t),1!==i||1!==a){if(Rc.hasGroupAttributesCache(t)){const{avChatRoomKey:e}=Rc.getGroupAttributesCache(t);iu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then((()=>{Rc.emitGroupAttributesUpdated(t)})).catch((()=>{}))}}else Rc.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:n})}reset(){Rc.reset()}};function au(e,t="tips"){const{ClientSeq:s,From_Account:n,MsgClientTime:o,MsgPriority:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,TinyId:u,ToGroupId:l,GroupInfo:d,MsgBody:h}=e,g=function(e){const{GroupCode:t,GroupId:s,GroupName:n,GroupType:o,MsgFrom_AccountExtraInfo:i,From_Account:r,To_Account:a}=e;return{groupCode:t,groupID:s,groupName:n,type:o,messageFromAccountExtraInformation:i,from:r,to:a}}(d);return{clientSequence:s,from:n,clientTime:o,priority:i,random:r,sequence:a,time:c,tinyID:u,to:l,groupProfile:g,elements:"tips"===t?cu(h):lu(h)}}function cu(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"MemberNum":t.memberCount=e[s];break;case"OpType":t.operationType=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"List_Account":t.userIDList=e[s];break;case"MsgMemberExtraInfo":t.memberInfoList=e[s].map((e=>uu(e)));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=uu(e[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"GroupIntroduction":t.introduction=e[s];break;case"GroupName":t.groupName=e[s];break;case"GroupFaceUrl":t.avatar=e[s];break;case"GroupNotification":t.notification=e[s];break;case"ApplyJoinOption":t.joinOption=e[s];break;case"InviteJoinOption":t.inviteOption=e[s];break;case"ShutupAll":t.muteAllMembers=e[s];break;case"Owner_Account":t.ownerID=e[s];break;case"GroupAttrOption":t.groupAttributeOption=function(e){const{BytesChangedKeys:t,GroupAttrSeq:s,OpType:n,PushChangedAttrValFlag:o,GroupAttrInfo:i}=e,r=i.map((e=>{const{Key:t,Val:s,SubKeySeq:n}=e;return{key:t,value:s,sequence:n}}));return{changedKeyList:t,groupAttributeList:r,serverMainSequence:s,operation:n,withChangedAttributeInfo:o}}(e[s])}})),t}(e[s]);break;case"MsgMemberInfo":t.msgMemberInfo=e[s].map((e=>function(e){const{ShutupTime:t,User_Account:s}=e;return{muteTime:t,userID:s}}(e)));break;case"OnlineMemberInfo":t.onlineMemberInfo=function(e){const{ExpireTime:t,OnlineMemberNum:s}=e;return{expireTime:t,onlineMemberNum:s}}(e[s]);break;case"GroupCounterInfo":t.groupCounterInfo=function(e){return e.map((e=>{const{GroupCounterSeq:t,GroupCounter:s,Type:n}=e;return{type:n,groupCounterSeq:t,counterList:s}}))}(e[s])}})),t}function uu(e){const{ImageUrl:t,NickName:s,Role:n,UserId:o}=e;return{avatar:t,nick:s,role:n,userID:o}}function lu(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"MsgKey":t.messageKey=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"ReportType":t.operationType=e[s];break;case"Authentication":t.authentication=e[s];break;case"MsgFlag":t.messageRemindType=e[s];break;case"UserDefinedField":t.userDefinedField=e[s];break;case"RemarkInfo":t.remarkInfo=e[s];break;case"BanDuration":t.duration=e[s];break;case"MuteTime":t.muteTime=e[s]}})),t}class du{constructor(e){this.type=oa.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=cu(e);return new du(t)}_initContent(e){Object.keys(e).forEach((t=>{switch(t){case"groupProfile":this._initGroupProfile(e[t]);break;case"operatorInfo":this._initOperatorInfo(e[t]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(e[t]);break;case"newGroupProfile":this._initNewGroupProfile(e[t]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[t]=e[t]}})),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];Ba[n]&&(this.content.groupProfile[n]=e[n])}}_initOperatorInfo(e){this.content.operatorInfo={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];this.content.operatorInfo[n]=e[n]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach((t=>{e.forEach((e=>{t.userID===e.userID&&Object.assign(t,e)}))})):this.content.memberList=e}_initNewGroupProfile(e){this.content.newGroupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];"muteAllMembers"!==n?this.content.newGroupProfile[n]=e[n]:this.content.newGroupProfile.muteAllMembers=1===e.muteAllMembers}}}var hu=new class{constructor(){this._name="GroupTipsNotification"}init(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=e,{message:{messageFactory:o},OuterConstant:i}=e;null==o||o.registerElementClass(i.MSG_GRP_TIP,du),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this)}onNewGroupTips(e){const{messageList:t,conversationUpdateFieldList:s}=this._handleGroupTips(e),{notificationCenter:n,OuterEvent:o,appStore:i}=this._core;null==s||s.forEach((e=>{const{conversationID:t,lastMessage:s,unreadCount:n}=e;i.conversationStore.updateConversation(t,{lastMessage:s,unreadCount:n})})),t.length>0&&(n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:t}),this._handleGroupTipMessage(t))}_handleGroupTips(e,t=!0){const{Event:s,GroupTips:n}=e,o=new Map,i=[],r=[];for(let e=0,i=n.length;e<i;e++){const i=au(n[e],"tips");if(s===xa){if(ru.isGroupAttributesUpdated(i)){ru.handleGroupAttributesUpdated(i);continue}if(tu.isGroupCounterUpdated(i)){tu.handleGroupCounterUpdated(i);continue}}const{groupProfile:{groupID:a}}=i;if(!Mc.hasLocalGroup(a))continue;const c=this._assembleMessage(i);if(s===xa&&(c._onlineOnlyFlag=!0,r.push(c)),s===$a){if(!this._core.message.messageDataHandler.storeConversationMessage(c)&&t)continue;r.push(c)}this._handleConversationOptions(o,c)}return i.push(...o.values()),{conversationUpdateFieldList:i,messageList:r}}_assembleMessage(e){const{OuterConstant:t,message:{messageFactory:s}}=this._core;e.flow="in",e.conversationType=t.CONV_GROUP;const n=s.createMessage(e);this._patchNickAndAvatar(e.elements,n);const o=new du(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));return n.setElement(o),n.isSystemMessage=!1,n}_patchNickAndAvatar(e,t){const{utils:{isEmpty:s},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:n}}=this._core,{operationType:o,memberInfoList:i,operatorInfo:r}=e;let a={};if(s(i)?s(r)||(a=r):o!==n.JOINED&&o!==n.KICKED&&o!==n.ADMIN_SET&&o!==n.ADMIN_CANCELED||(a=Object.assign({},i[0])),!s(a)){const{nick:e="",avatar:s=""}=a;t.nick=e,t.avatar=s}}_handleConversationOptions(e,t){const{common:{getMessagePreviewText:s},utils:{isObject:n}}=this._core,{conversationID:o,conversationType:i}=t;let r;if(e.has(o))r=e.get(o),"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||r.unreadCount++),r.type=i,r.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1)),r={conversationID:o,unreadCount:e,type:i,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}n(r.lastMessage)&&(r.lastMessage.messageForShow=s(r.lastMessage.type,r.lastMessage.payload)),e.set(o,r)}_handleGroupTipMessage(e){const{OuterConstant:{GROUP_TIPS_OPERATION_TYPE:t}}=this._core;e.forEach((e=>{const{operationType:s}=e.payload;switch(s){case t.JOINED:this._handleNewMemberJoined(e);break;case t.QUITTED:this._handleMemberQuitted(e);break;case t.KICKED:this._handleMemberKicked(e);break;case t.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}}))}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){var t;const{newGroupProfile:s,groupProfile:n,operatorInfo:o}=e.payload,{groupID:i}=n,r=Mc.getLocalGroup(i);Object.keys(s).forEach((e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(i,s);break;case"groupName":r.name=s[e];break;default:r[e]=s[e]}}));const{utils:{isUndefined:a}}=this._core;a(o)||(null===(t=null==r?void 0:r.selfInfo)||void 0===t?void 0:t.userID)!==o.userID||Object.keys(o).forEach((e=>{"nameCard"===e&&r.updateSelfInfo({nameCard:o[e]}),"role"===e&&this._updateSelfRole(r,o[e])})),Mc.emitGroupListUpdate(),Mc.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){const{common:s,OuterConstant:n}=this._core,o=Mc.getLocalGroup(e),i=s.getCurrentUserID(),{ownerID:r}=t;i===r&&o.updateGroup({ownerID:r,selfInfo:{role:n.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){const{OuterConstant:s}=this._core;let n=s.GRP_MBR_ROLE_MEMBER;t===qa?n=s.GRP_MBR_ROLE_OWNER:t===Va&&(n=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:n})}_handleGroupMemberCountUpdated(e){const{memberCount:t,groupProfile:{groupID:s}}=e.payload,n=Mc.getLocalGroup(s),{utils:{isNumber:o}}=this._core;n&&o(t)&&n.memberCount!==t&&(n.memberCount=t,Mc.emitGroupListUpdate(),Mc.updateConversationGroupProfile(s))}_handleGroupTipsRecover(e){const{utils:{isArray:t}}=this._core,{groupTipList:s}=(null==e?void 0:e.result)||{};t(s)&&s.forEach((e=>{const{messageList:t}=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1);this._handleGroupTipMessage(t)}))}};class gu{constructor(e){this.type=oa.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=lu(e);return new gu(t)}_initContent(e){Object.keys(e).forEach((t=>{switch(t){case"remarkInfo":this.content.handleMessage=e[t];break;case"groupProfile":this._initGroupProfile(e[t]);break;case"memberInfoList":break;default:this.content[t]=e[t]}}))}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];ja[n]&&(this.content.groupProfile[n]=e[n])}}}var pu=new class{constructor(){this._name="GroupSystemNotification"}init(e){this._core=e;const{message:{messageFactory:t},OuterConstant:{MSG_GRP_SYS_NOTICE:s}}=e;null==t||t.registerElementClass(s,gu)}onNewGroupSystemNotification(e){const{GroupTips:t=[],isInstantMessage:s=!0}=e;console.log(`${this._name}.onNewGroupSystemNotification count:${t.length} isInstantMessage:${s}`);const{conversationUpdateFieldList:n,messageList:o}=this._handleGroupSystemNotification(t,s),{notificationCenter:i,OuterEvent:r}=this._core;n.length>0&&this._handleGroupSysTemMessage(s,o),!0===s&&o.length>0&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:o})}_handleGroupSystemNotification(e,t){const s=[];let n={};for(let o=0;o<e.length;o++){const i=au(e[o],"system"),{elements:{operationType:r}}=i;if(r===Ja)continue;const a=this._assembleMessage(i);this._core.message.messageDataHandler.storeConversationMessage(a)&&(s.push(a),n=this._handleConversationOptions(a,t))}return n.lastMessage=s[s.length-1],{conversationUpdateFieldList:s.length>0?[n]:[],messageList:s}}_assembleMessage(e){const{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:n}}=this._core;e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM;const o=t.createMessage(e),i=new gu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));o.setElement(i),o.isSystemMessage=!0;const r=1===o.sequence&&1===o.random,a=2===o.sequence&&2===o.random;return(r||a)&&(o.sequence=n(),o.random=n(),o.generateMessageID()),o}_handleConversationOptions(e,t){const{OuterConstant:s}=this._core,n={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&n.unreadCount++,n}_handleGroupSysTemMessage(e,t){e&&t.forEach((e=>{const{operationType:t}=e.payload;switch(t){case Ka:this._handleGroupJoinResult(e);break;case Ha:this._handleMemberKicked(e);break;case Wa:this._handleGroupDismissed(e);break;case Ya:this._handleGroupInvitedResult(e);break;case za:this._handleGroupQuitResult(e);break;case Qa:this._handleMessageRemindTypeSynced(e);break;case Xa:this._handleAVChatRoomMemberBanned(e)}}))}_handleGroupJoinResult(e){const{groupProfile:t}=e.payload,{groupID:s,type:n}=t,o=Mc.hasLocalGroup(s);console.log(`${this._name}._handleGroupJoinResult groupID:${s} type:${n} hasLocalGroup:${o}`),o||_c(n)||(Mc.updateLocalGroup([Object.assign({},t)]),Mc.emitGroupListUpdate())}_handleMemberKicked(e){const{groupProfile:{groupID:t,type:s}}=e.payload;Mc.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupDismissed(e){const{groupProfile:{groupID:t,type:s}}=e.payload;Mc.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupInvitedResult(e){const{groupProfile:t}=e.payload,{groupID:s}=t,n=Mc.hasLocalGroup(s);console.log(`${this._name}._handleGroupInvitedResult groupID:${s} hasLocalGroup:${n}`),n||(Mc.updateLocalGroup([Object.assign({},t)]),Mc.emitGroupListUpdate())}_handleGroupQuitResult(e){const{groupProfile:{groupID:t,type:s}}=e.payload,n=Mc.hasLocalGroup(t);console.log(`${this._name}._handleGroupQuitResult groupID:${t} type:${s} hasLocalGroup:${n}`),n&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleMessageRemindTypeSynced(e){const{groupProfile:{groupID:t},messageRemindType:s}=e.payload;this._updateConversationProfile(t,{messageRemindType:s})}_handleAVChatRoomMemberBanned(e){const{groupProfile:{groupID:t,type:s}}=e.payload;this._deleteLocalGroup(t,s)}_deleteLocalGroup(e,t){if(_c(t)){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`)}Mc.deleteLocalGroup(e),Mc.emitGroupListUpdate()}_updateConversationProfile(e,t){const{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:n}}=this._core,o=`${n}${e}`;s.getConversation(o)&&s.updateConversation(o,t)}};var _u=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),hu.init(e),pu.init(e);const{notificationCenter:t,InnerEvent:s}=e,{InnerEventSubType:n}=t;t.subscribeInnerEvent(s.MESSAGE_PUSH,n.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),t.subscribeInnerEvent(s.MESSAGE_PUSH,n.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){hu.onNewGroupTips(e)}_onNewGroupSystemNotification(e){pu.onNewGroupSystemNotification(e)}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const mu={required:!0,rules:["string"],allowEmpty:!1},vu={required:!0,rules:["number"],allowEmpty:!1},fu={required:!0,rules:["array"],allowEmpty:!1},Iu={required:!0,rules:["object"],allowEmpty:!1},Su={createGroup:{name:mu,type:mu},dismissGroup:[Object.assign({key:"groupID"},mu)],joinGroup:{groupID:mu,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},mu)],searchGroupByID:[Object.assign({key:"groupID"},mu)],getGroupProfile:{groupID:mu,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:mu,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:mu,newOwnerID:mu},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},mu)],handleGroupApplication:{handleAction:mu},getGroupMemberList:{groupID:mu},getGroupMemberProfile:{groupID:mu,userIDList:fu,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:mu,userIDList:fu},deleteGroupMember:{groupID:mu,userIDList:fu},setGroupMemberMuteTime:{groupID:mu,userID:mu,muteTime:Object.assign(Object.assign({},vu),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:mu,userID:mu,role:mu},setGroupMemberNameCard:{groupID:mu,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:mu},setGroupMemberCustomField:{groupID:mu,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:fu},markGroupMemberList:{groupID:mu,markType:Object.assign(Object.assign({},vu),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:fu},initGroupAttributes:{groupID:mu,groupAttributes:Iu},setGroupAttributes:{groupID:mu,groupAttributes:Iu},deleteGroupAttributes:{groupID:mu,keyList:Object.assign(Object.assign({},fu),{allowEmpty:!0})},getGroupAttributes:{groupID:mu,keyList:Object.assign(Object.assign({},fu),{allowEmpty:!0})},getGroupCounters:{groupID:mu,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:mu,counters:Iu},increaseGroupCounter:{groupID:mu,key:mu,value:vu},decreaseGroupCounter:{groupID:mu,key:mu,value:vu}},Eu={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 Cu=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Mc,this.groupAction=Fc,this.groupAttribute=ru,this.groupMember=Xc,this.name="Group"}install(e,t=[]){this._core=e,oa.init(e),Mc.init(e),Fc.init(e,this),Xc.init(e,this),qc.init(e),tu.init(e),ru.init(e),_u.init(e),e.helper.registerValidateConfig({auth:Eu,params:Su}),this._installSubPlugins(t);const{notificationCenter:s,InnerEvent:n}=e;s.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){const{utils:{isArray:t}}=this._core;e&&t(e)&&e.forEach((e=>{var t;this._installedSubPlugins.includes(e.name)||(null===(t=e.install)||void 0===t||t.call(e,this._core,this),this._installedSubPlugins.push(e.name))}))}_reset(){Mc.reset(),ru.reset(),tu.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Mu=new class{init(e){this.core=e}};const yu="AV_MBR_LIST",Ou="AV_BAN_MBR",Au={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},Tu={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},Ru=60,Du=2603,bu=2686,Lu=2688,Nu=3122;class Pu{constructor(e){const{core:t,manager:s,groupID:n,getRequestParams:o,onSuccess:i,onFail:r}=e;this._name="Polling",this._core=t,this._manager=s,this._timeoutID=-1,this._isRunning=!1,this._groupID=n,this._getRequestParams=o,this._onSuccess=i,this._onFail=r}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getPollingInterval()}`)}isRunning(){return this._isRunning}_request(){return g(this,void 0,void 0,(function*(){try{const e=this._getRequestParams(this._groupID),t=yield function(e,t){return g(this,void 0,void 0,(function*(){const{longPollingKey:s,startSequence:n,startBroadcastSeq:o,simplifiedMessage:i}=e,r={Key:s,StartSeq:n,StartBroadcastSeq:o,DownsizeFlag:i,USP:1,HoldTime:90};return t.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:r})}))}(e,this._core);this._onSuccess(this._groupID,t);const s=this._manager.getPollingInterval();this._runNextPolling(s)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}}))}_runNextPolling(e){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(`${this._name}.stop`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class Gu{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){const e=(null===(t=this._map.entries().next().value)||void 0===t?void 0:t[0])||"";this._map.delete(e)}this._map.set(e,1)}has(e){return this._map.has(e)}delete(e){this.has(e)&&this._map.delete(e)}clear(){this._map.clear()}}const wu=e=>e===Au.GROUP_TIPS_HAS_NO_ROAMING||e===Au.GROUP_TIPS_HAS_ROAMING,Uu=e=>e===Au.GROUP_SYSTEM_MESSAGE;function ku(e){const t=function(e){const{E:t,MCT:s,MR:n,MP:o,MTS:i,GId:r,MS:a,CCD:c,F_Account:u,IsSys:l,GInf:d,MsgBody:g}=e,p=h(e,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:t,MsgClientTime:s,MsgRandom:n,MsgPriority:o,MsgTimeStamp:i,ToGroupId:r,MsgSeq:a,CloudCustomData:c,From_Account:u,IsSystemMsg:l,GroupInfo:Fu(d),MsgBody:$u(g)},p)}(e);return function(e){const{Event:t}=e;(wu(t)||Uu(t))&&(e.From_Account=e.From_Account||"@TIM#SYSTEM");s=t,(s===Au.BROADCAST_MESSAGE||(e=>e===Au.NORMAL_MESSAGE)(t))&&function(e){const{core:{OuterConstant:t}}=Mu;e.CloudCustomData=e.CloudCustomData||"",e.MsgBody=e.MsgBody.map((e=>{if(e.MsgType===t.MSG_CUSTOM){const{content:t={}}=e;e.content=Object.assign({Data:"",Desc:"",Ext:""},t)}return e}))}(e);var s;wu(t)&&function(e){const{GroupJoinType:t,MsgOperatorMemberExtraInfo:s={},MsgMemberExtraInfo:n,Operator_Account:o,List_Account:i,OpType:r}=e.MsgBody||{};"number"==typeof t||1!==r&&2!==r||(e.MsgBody.GroupJoinType=2===r?0:1);n||(e.MsgBody.MsgMemberExtraInfo=i.map((e=>({UserId:e}))));1!==r||n||(e.MsgBody.MsgMemberExtraInfo=[{UserId:s.UserId}]);e.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:o,ImageUrl:"",NickName:""},s)}(e);Uu(t)&&function(e){const{MsgOperatorMemberExtraInfo:t={},Operator_Account:s}=e.MsgBody||{};e.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:s,ImageUrl:"",NickName:""},t),e.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*e.MsgTimeStamp},e.MsgBody),e.MsgBody=Object.keys(e.MsgBody).filter((e=>"MsgOperatorMemberExtraInfo"!==e)).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:e.MsgBody[s]})),{})}(e)}(t),t}function Fu(e){const t=e||{},{GN:s,GT:n,F_Hd:o,F_NN:i}=t,r=h(t,["GN","GT","F_Hd","F_NN"]),a=Object.assign({GroupName:s,GroupType:n},r);return o&&(a.From_AccountHeadurl=o),i&&(a.From_AccountNick=i),a}function $u(e){let t=e;Array.isArray(e)||(t=[e]);const s=t.map((e=>{const{O_Account:t,Opt:s,L_Account:n,RT:o,UDF:i,OpInf:r,OnlineInf:a,MsgMemberExtraInfo:c}=e,u=h(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),l=Object.assign({Operator_Account:t,OpType:s,List_Account:n,ReportType:o,UserDefinedField:i},u);return r&&(l.MsgOperatorMemberExtraInfo=function(e){const{Img:t,NN:s}=e,n=h(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},n)}(r)),c&&(l.MsgMemberExtraInfo=function(e){return e.map((e=>{const{Img:t,NN:s}=e,n=h(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},n)}))}(c)),a&&(l.OnlineMemberInfo=function(e){const{ET:t,Num:s}=e;return{ExpireTime:t,OnlineMemberNum:s}}(a)),l}));return Array.isArray(e)?s:s[0]}var xu=new class{constructor(){this._name="MessageParser",this._sequenceList=new Gu(200),this._messageIDList=new Gu(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(e,t,s=!1){this._sortServerMessageList({groupID:e,serverMessageList:t,isHistoryMessage:s});const n=this._handleMessageList(e,t);if(0===n.length)return;if(!s){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,o=(e=>{const{core:{common:{getMessagePreviewText:t}}}=Mu;return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(n[n.length-1]);t.updateConversation(`${s}${e}`,{lastMessage:o})}this._checkMessageStacked(n);const o=n.filter((e=>!0===e.isModified)),i=n.filter((e=>!1===e.isModified)),{OuterEvent:{MESSAGE_RECEIVED:r,MESSAGE_MODIFIED:a}}=this._core;o.length>0&&this._emitEvent({name:a,data:o}),i.length>0&&this._emitEvent({name:r,data:i})}_sortServerMessageList(e){const{groupID:t,serverMessageList:s,isHistoryMessage:n}=e;let o=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!n?(s.sort(((e,t)=>e.MS-t.MS)),o=s.map((e=>e.MS))):(s.sort(((e,t)=>e.MsgSeq-t.MsgSeq)),o=s.map((e=>e.MsgSeq))),console.log(`${this._name}._sortServerMessageList groupID:${t} count:${o.length} sequenceList:${o}`),o.length=0}_handleMessageList(e,t){const{message:{messageDataHandler:s,messageHelper:n}}=this._core,o=this._avChatRoomHandler.isPollingSimplifiedMessage(),i=[],r=t.length;for(let a=0;a<r;a++){let r=t[a];if(o&&(r=ku(r)),Uu(r.Event)&&Object.values(Tu).includes(r.MsgBody.ReportType)){this._onGroupDismissed(e);break}if(null===this._filterMessageItem(r))continue;this._patchMessageType(r);const c=n.parseServerGroupMessage(r),u=this._createMessage(c);wu(r.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(c)?this._avChatRoomHandler.handleGroupAttributesUpdated(c):null!==this._filterDuplicateMessage(u)&&(s.isMessageSentByCurrentInstance(u)||(1===c.isModified&&(u.isModified=!0),wu(r.Event)&&this._updateLocalOnlineMemberCountFromTips(r),i.push(u)))}return i}_patchMessageType(e){const{OuterConstant:t}=this._core;wu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),Uu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){const{Event:t}=e;return Object.values(Au).includes(t)?(e=>e===Au.MESSAGE_REVOKED)(t)?(this._handleMessageRevoked(e),null):(e=>e===Au.LIVE_CUSTOM_DATA)(t)?(this._onLiveCustomData(e),null):(e=>e===Au.MESSAGE_REACTION)(t)?null:e:(console.warn(`${this._name}.onMessageReceived unknown event:${t}`),null)}_createMessage(e){const{message:{messageFactory:t},OuterConstant:s}=this._core;let n=s.CONV_GROUP;e.event===Au.GROUP_SYSTEM_MESSAGE&&(n=s.CONV_SYSTEM);const o=!!e.isSystemMessage,i=t.createMessage(Object.assign(Object.assign({},e),{conversationType:n,isSystemMessage:o,flow:"in"}));return i.setElement(e.elements),i}_filterDuplicateMessage(e){const{common:t}=this._core;if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}const s=this._messageIDList.has(e.ID);return s?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:${s}`),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){const{OuterConstant:t,OuterEvent:{MESSAGE_REVOKED:s}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:o},RevokerInfo:{Revoker_Account:i,Reason:r=""}}=e,a=[];o.forEach((e=>{const{TinyId:s,MsgClientTime:o,Random:c,MsgSeq:u}=e,l={conversationID:`${t.CONV_GROUP}${n}`,ID:`${s}-${o}-${c}`,revoker:i,revokeReason:r,revokerInfo:{userID:i,nick:"",avatar:""},sequence:u};a.push(l)})),0!==a.length&&this._emitEvent({name:s,data:a})}_onLiveCustomData(e){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:t}}=this._core,{ToGroupId:s,MsgSeq:n,MsgTimeStamp:o,MsgBody:i}=e,r=(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:r}),console.log(`${this._name}._onLiveCustomData groupID:${s} sequence:${n} time:${o} data:${r}`)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){const{length:t}=e;if(t>=100&&this._reportMessageStackedCount<5){const e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.createSSOLogData({method:"MessageStacked"}).setLogInfo({message:`count:${t} groupID:${e.join(",")}`}).end(),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(e){const{message:{messageHelper:t},OuterEvent:{MESSAGE_RECEIVED:s}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),o=[],i=e.length;for(let s=0;s<i;s++){let i=e[s];n&&(i=ku(i));const r=t.parseServerGroupMessage(i);if(!Object.values(Au).includes(i.Event)){console.warn(`${this._name}.onBroadcastMessageReceived unknown event:${i.Event}`);continue}const a=this._createMessage(r);a.isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(o.push(a),this._broadcastMessageIDMap.set(a.ID,1))}o.length>0&&this._emitEvent({name:s,data:o})}_updateLocalOnlineMemberCountFromTips(e){const{utils:{isEmpty:t}}=this._core,{ToGroupId:s,MsgBody:{OnlineMemberInfo:n}}=e;if(t(n))return;const{OnlineMemberNum:o=0,ExpireTime:i=Ru}=n,r=Date.now();let a=this._avChatRoomHandler.getLocalOnlineMemberCount(s);t(a)?a={lastReqTime:0,lastSyncTime:0,latestUpdateTime:r,memberCount:o,expireTime:i}:(a.latestUpdateTime=r,a.memberCount=o),this._avChatRoomHandler.updateLocalOnlineMemberCount(s,a)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const qu=e=>{const{core:{store:t}}=Mu;return(t.get("cloudConfig")||{})[e]},Vu=e=>{const{core:{utils:{isUndefined:t}}}=Mu;return!t(e)},Bu=()=>{const e=qu("polling_interval");return Vu(e)?parseInt(e,10):300},ju=()=>{const e=qu("polling_simplified_msg");return Vu(e)?parseInt(e,10):0};var Ku=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingInterval=300,this._pollingNoMessageCount=0,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,xu.init(e,this),console.log("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){const{OuterConstant:{GRP_AVCHATROOM:t}}=this._core,{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){const{MsgBody:n,GroupInfo:{GroupId:o,GroupType:i}}=s[e],r=Object.values(Tu).includes(n.ReportType);i===t&&r&&this.reset(o)}}getPollingInterval(){return this._pollingInterval}isPollingSimplifiedMessage(){return 0!==ju()}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 e=[];return this._joinedGroupMap.size>0&&(e=[...this._joinedGroupMap.values()].filter((e=>e.type===TYPES.GRP_LIVE))),e}handleJoinGroupResult(e){return g(this,void 0,void 0,(function*(){const{utils:{isUndefined:t},OuterConstant:{CONV_GROUP:s},apiMap:{getConversationProfile:n},OuterConstant:o}=this._core,{longPollingKey:i,group:r,historyMessageList:a}=e,{groupID:c}=r;return yield this._preCheck(r),this._joinedGroupMap.set(c,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),n(`${s}${c}`),a.length>0&&xu.onMessageReceived(c,a,!0),t(i)?{status:o.JOIN_STATUS_SUCCESS,group:r}:this.startMessageLongPolling(e)}))}_preCheck(e){return g(this,void 0,void 0,(function*(){const{common:t,OuterConstant:s,helper:n,apiMap:{quitGroup:o}}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const e=qu("polling_count_limit");return Vu(e)&&e>0?parseInt(e,10):20})())throw new n.ChatError({code:Lu,message:"the count of longPolling exceeds the max limit"});return}if(0===this._joinedAVChatRoomCount())return;if(e.type===s.GRP_LIVE)return;const[i,r]=this._joinedGroupMap.entries().next().value;r.selfInfo.role===s.GRP_MBR_ROLE_OWNER?this._parentPlugin.groupDataHandler.deleteLocalGroup(i):yield o(i),this.reset(i)}))}startMessageLongPolling(e){const{OuterConstant:t}=this._core,{longPollingKey:s,startSequence:n=1,group:o}=e,{groupID:i}=o;return this._pollingRequestInfoMap.set(i,{longPollingKey:s,startSequence:n}),this._pollingInterval=Bu(),this._startPolling(i),{status:t.JOIN_STATUS_SUCCESS,group:o}}_startPolling(e){if(console.log(`${this._name}._startPolling groupID:${e}`),this._pollingInstanceMap.has(e)){const t=this._pollingInstanceMap.get(e);return void((null==t?void 0:t.isRunning())||null==t||t.start())}const t=new Pu({core:this._core,manager:this,groupID:e,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});t.start(),this._pollingInstanceMap.set(e,t)}_handleRequestParams(e){const{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:ju()}:{longPollingKey:t,startSequence:s,simplifiedMessage:ju()}}_handleSuccess(e,t){const{ErrorCode:s}=t;if(0===s)this._hasJoinedAVChatRoom(e)&&this._handleResponseData(e,t);else{const{longPollingKey:t,startSequence:n}=this._pollingRequestInfoMap.get(e)||{};console.warn(`${this._name}._handleSuccess groupID:${e} key:${t} startSeq:${n} errorCode:${s}`)}}_handleResponseData(e,t){const{Key:s,NextSeq:n,NextBroadcastSeq:o,RspMsgList:i=[],RspBroadcastMsgList:r=[]}=t;s&&n&&this._pollingRequestInfoMap.set(e,{longPollingKey:s,startSequence:n}),o&&o>this._startBroadcastSequence&&(this._startBroadcastSequence=o),i.length>0?(0!==this._pollingNoMessageCount&&(this._pollingNoMessageCount=0,this._pollingInterval=Bu()),xu.onMessageReceived(e,i)):(this._pollingNoMessageCount+=1,this._pollingNoMessageCount===(()=>{const e=qu("polling_no_msg_count");return Vu(e)?parseInt(e,10):20})()&&(this._pollingInterval=Bu()+(()=>{const e=qu("polling_interval_plus");return Vu(e)?parseInt(e,10):2e3})())),r.length>0&&xu.onBroadcastMessageReceived(r)}_handleFailure(e,t){console.warn(`${this._name}._handleFailure groupID:${e} error:`,t)}_joinedAVChatRoomCount(){const{OuterConstant:e}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=this.getJoinedGroups().filter((t=>t.type===e.GRP_AVCHATROOM))),t.length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}_stopPolling(e){if(e){console.log(`${this._name}._stopPolling groupID:${e}`);const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`);const n=this._pollingInstanceMap.get(e);return null==n||n.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),void this._onlineMemberCountMap.delete(e)}console.log(`${this._name}._stopPolling all`);for(const e of this._pollingInstanceMap.values())e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear()}reset(e){this._stopPolling(e),this._pollingInterval=300,this._pollingNoMessageCount=0,this._startBroadcastSequence=1,xu.reset()}};var Hu=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}joinGroup(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.joinGroup(e),{data:{group:{type:n}}}=s;return n===t.GRP_AVCHATROOM?Ku.handleJoinGroupResult(s.data):s}))}};var Wu=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}quitGroup(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.quitGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&Ku.reset(e),s}))}};var Yu=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}dismissGroup(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.dismissGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&Ku.reset(e),s}))}};var zu=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupMemberList(e){return g(this,void 0,void 0,(function*(){const{appStore:{groupStore:t},helper:s,OuterConstant:n}=this._core,{groupID:o}=e,i=t.getGroup(o);if((null==i?void 0:i.type)===n.GRP_AVCHATROOM){if(s.checkBusinessCapabilityBits(yu))return this._getGroupMemberList(e)}return this._parentPlugin.groupMember.getGroupMemberList(e)}))}_getGroupMemberList(e){return g(this,void 0,void 0,(function*(){const t="_getGroupMemberList",{helper:s}=this._core;try{const s=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,offset:n=0}=e,o={GroupId:s,Timestamp:n};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:o})}))}(e,this._core),{MemberList:n=[],NextTimestamp:o=0}=s||{},i=this._handleMemberList(n);return console.log(`${this._name}.${t} ok, groupID:${e.groupID} count:${i.length} nextOffset:${o}`),{code:0,data:{memberList:i,offset:o}}}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_handleMemberList(e){return e.map((e=>{const{Member_Account:t,NickName:s="",Avatar:n="",Remark:o="",JoinTime:i=0,Marks:r=[]}=e;return{userID:t,nick:s,avatar:n,remark:o,joinTime:i,marks:r,isOnline:!0}}))}};var Ju=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(e){return g(this,void 0,void 0,(function*(){const{appStore:{groupStore:t},OuterConstant:s}=this._core,n=t.getGroup(e);return n?n.type===s.GRP_AVCHATROOM?this._getOnlineMemberCount(e):this._parentPlugin.groupAction.getGroupOnlineMemberCount(e):{code:0,data:{memberCount:0}}}))}_getOnlineMemberCount(e){return g(this,void 0,void 0,(function*(){const t="_getOnlineMemberCount",{utils:{isEmpty:s}}=this._core,n=Ku.getLocalOnlineMemberCount(e);if(s(n)||this._isExpired(e)){const{memberCount:s=0}=yield this._getOnlineMemberCountFromServer(e);return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${s} from server.`),{code:0,data:{memberCount:s}}}return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${n.memberCount} from local.`),{code:0,data:{memberCount:n.memberCount}}}))}_isExpired(e){const t=Ku.getLocalOnlineMemberCount(e),s=Date.now(),n=s-t.lastSyncTime>1e3*t.expireTime,o=s-t.latestUpdateTime>1e4,i=s-t.lastReqTime>3e3;return n&&o&&i}_getOnlineMemberCountFromServer(e){return g(this,void 0,void 0,(function*(){const t="_getOnlineMemberCountFromServer";try{const t=yield function(e,t){return g(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})}))}(e,this._core),{OnlineMemberNum:s=0,ExpireTime:n=Ru}=t||{},o=Date.now(),i={lastSyncTime:o,latestUpdateTime:o,lastReqTime:o,memberCount:s,expireTime:n};return Ku.updateLocalOnlineMemberCount(e,i),{memberCount:s}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Qu=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}deleteGroupMember(e){return g(this,void 0,void 0,(function*(){const t="deleteGroupMember",{appStore:{groupStore:s},utils:{isUndefined:n},helper:o,OuterConstant:i}=this._core,{groupID:r}=e,a=s.getGroup(r);if(n(a))throw new o.ChatError({functionName:t,code:Du});if(a.type===i.GRP_AVCHATROOM){if(o.checkBusinessCapabilityBits(Ou))return this._deleteGroupMember(e);throw new o.ChatError({functionName:t,code:Nu})}return this._parentPlugin.groupMember.deleteGroupMember(e)}))}_deleteGroupMember(e){return g(this,void 0,void 0,(function*(){const t="_deleteGroupMember",{appStore:{groupStore:s},helper:n}=this._core,{groupID:o,duration:i=0,userIDList:r}=e;if(0===i)throw new n.ChatError({functionName:t,code:bu});try{yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n,duration:o,reason:i}=e,r={GroupId:s,Members_Account:n,Duration:o,Description:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:r})}))}(e,this._core),console.log(`${this._name}.${t} ok, groupID:${o}`);return{code:0,data:{group:s.getGroup(o),userIDList:r}}}catch(e){const s=new n.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}}))}};var Xu=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return g(this,void 0,void 0,(function*(){const t="markGroupMemberList",{groupID:s,markType:n,enableMark:o,userIDList:i=[]}=e,r=this._generateRequestData(e);try{const e=yield function(e,t){return g(this,void 0,void 0,(function*(){const{groupID:s,operationType:n,memberList:o}=e,i={GroupId:s,CommandType:n,MemberList:o};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:i})}))}(r,this._core),{MemberList:a=[]}=e||{},{successUserIDList:c,failureUserIDList:u}=this._handleResult(a,i);return console.log(`${this._name}.${t} ok, groupID:${s} markType:${n} enableMark:${o} success:${c.length} fail:${u.length}`),{code:0,data:{successUserIDList:c,failureUserIDList:u}}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_generateRequestData(e){const{groupID:t,markType:s,enableMark:n,userIDList:o=[]}=e,i=!0===n?1:2,r=[...o];r.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`);return{groupID:t,operationType:i,memberList:r.map((e=>({Member_Account:e,Marks:[s]})))}}_handleResult(e,t){const s=[],n=[];return e.length===t.length?(s.push(...t),{successUserIDList:s,failureUserIDList:n}):(t.forEach((t=>{e.find((e=>e.Member_Account===t))?s.push(t):n.push(t)})),{successUserIDList:s,failureUserIDList:n})}};var Zu=new class{init(e,t){console.log("AVChatRoomAction.init"),Hu.init(e,t),Wu.init(e,t),Yu.init(e,t),zu.init(e,t),Ju.init(e,t),Qu.init(e,t),Xu.init(e)}};var el=new class{constructor(){this._name="LiveHandler"}init(e){this._core=e;const{helper:t}=e;t.registerExperimentalAPI("startMessageLongPolling",this),t.registerExperimentalAPI("stopMessageLongPolling",this),console.log("LiveHandler.init")}startMessageLongPolling(e){const{common:t,utils:{isEmpty:s},OuterConstant:n}=this._core,{groupID:o,longPollingKey:i,longPollingSequence:r=1}=e;if(s(i))return console.warn(`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Ku.hasPollingInstance(o)&&this.stopMessageLongPolling({groupID:o});const a=Ku.getJoinedLiveList();!t.isUnlimitedAVChatRoom()&&a.length>0&&this.stopMessageLongPolling({groupID:a[0]});const c={groupID:o,type:n.GRP_LIVE};return console.log(`${this._name}.startMessageLongPolling groupID:${o} longPollingKey:${i} longPollingSequence:${r}`),Ku.startMessageLongPolling({group:c,longPollingKey:i,startSequence:r})}stopMessageLongPolling(e){const{groupID:t}=e;return Ku.reset(t),console.log(`${this._name}.stopMessageLongPolling ok, groupID:${t}`),Promise.resolve({groupID:t})}};var tl=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,Mu.init(e),Ku.init(e,t),Zu.init(e,t),el.init(e);const{notificationCenter:s,InnerEvent:n}=e,{InnerEventSubType:o}=s;s.subscribeInnerEvent(n.MESSAGE_PUSH,o.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Ku.onAVChatRoomSystemNotification(e)}_reset(){Ku.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const sl=new class{init(e){this.core=e}};const nl="message",ol="user",il={OR:"or",AND:"and"},rl=20,al=20,cl=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")},ll={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||(!![il.OR,il.AND].includes(e)||"keywordListMatchType should be OR or AND")},dl={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&e>=1&&e<=100||"count must be a number between 1 and 100"},hl={required:!1,rules:["string"],allowEmpty:!0},gl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=sl.core;if(!Array.isArray(e))return"groupTypeList should be an array";const s=[t.GRP_PUBLIC,t.GRP_COMMUNITY,t.GRP_WORK,t.GRP_MEETING];let n=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){n=!0;break}return!n||"groupTypeList should be supported group type"}},pl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=sl.core,s=[t.MSG_TEXT,t.MSG_IMAGE,t.MSG_AUDIO,t.MSG_FILE,t.MSG_VIDEO,t.MSG_LOCATION,t.MSG_CUSTOM,t.MSG_MERGER];let n=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){n=!0;break}return!n||"messageTypeList should be supported message type"}},_l={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=sl.core;return!(!(null==e?void 0:e.startsWith(t.CONV_C2C))&&!(null==e?void 0:e.startsWith(t.CONV_GROUP))&&e!==t.CONV_SYSTEM)||"conversationID is invalid"}},ml=e=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:t=>"number"==typeof t&&t>=0||`${e} should be a number >= 0';`}),vl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=sl.core;return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},fl={searchCloudMessages:{keywordList:ul,keywordListMatchType:ll,cursor:hl,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:pl,conversationID:_l,timePosition:ml("timePosition"),timePeriod:ml("timePeriod")},searchCloudUsers:{keywordList:ul,keywordListMatchType:ll,cursor:hl,count:dl,miniBirthday:ml("miniBirthday"),maxBirthday:ml("maxBirthday"),gender:vl},searchCloudGroupMembers:{keywordList:ul,keywordListMatchType:ll,cursor:hl,count:dl,groupTypeList:gl,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ul,keywordListMatchType:ll,cursor:hl,count:dl,groupTypeList:gl}},Il={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Sl=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,sl.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:Il,params:fl})}searchCloudMessages(e){return g(this,void 0,void 0,(function*(){try{const{OuterConstant:t,helper:s,ssoLog:n}=this._core,o=n.createSSOLogData({method:"searchCloudMessages"}),{conversationID:i,timePeriod:r,timePosition:a}=e,c=h(e,["conversationID","timePeriod","timePosition"]),u=Object.assign({count:100},c);i&&(i.startsWith(t.CONV_C2C)?u.account=i.replace(t.CONV_C2C,""):i.startsWith(t.CONV_GROUP)&&(u.groupID=i.replace(t.CONV_GROUP,""))),this._setTimeRangeParams(u,{timePeriod:r,timePosition:a});const l=yield function(e){return g(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:n,senderUserIDList:o,messageTypeList:i,endTime:r,startTime:a,cursor:c,account:u,groupID:l}=e,d={Count:t,KeywordList:s,MatchType:n,SendUserIDList:o,MsgTypeList:i,EndTime:r,StartTime:a,Cursor:c,PeerAccount:u,GroupID:l};return sl.core.common.buildAndSendPacket({servcmd:"message_search.query",data:d})}))}(u);if(!l)return{code:0,data:{}};const{ErrorCode:d,ErrorInfo:p,TotalCount:_,Cursor:m="",ConversationMsgs:v=[]}=l;if(0!==d)throw{errorCode:d,errorInfo:p};const f=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} res: totalCount:${_}`;o.setLogInfo({message:f}).end();const I=v.map((n=>{const{MsgList:o,Count:i,GroupID:r,UserID:a}=n,c=r?`${t.CONV_GROUP}${r}`:`${t.CONV_C2C}${a}`;if(this._isSearchingAllConversations(e)&&i>1)return{conversationID:c,messageCount:i,messageList:[]};const u=o.map((e=>s.isEmpty(r)?function(e,t){const s=t.OuterConstant.CONV_C2C,n=t.message.messageHelper.parseServerPushMessage(e),o=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return o.setElement(n.elements),o}(e,this._core):function(e,t){const s=t.OuterConstant.CONV_GROUP,n=t.message.messageHelper.parseServerGroupMessage(e),o=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return o.setElement(n.elements),o}(e,this._core)));return{conversationID:c,messageCount:i,messageList:u}}));return{code:0,data:{searchResultList:I,cursor:m,totalCount:_}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:nl,functionName:"searchCloudMessages"})}}))}searchCloudUsers(e){return g(this,void 0,void 0,(function*(){var t;try{const s=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:n,count:o=al}=e,i=h(e,["keywordListMatchType","count"]),r=Object.assign({count:o,keywordListMatchType:n===il.AND?1:0},i);this._setBirthdayRangeParams(r,e);const a=yield function(e){return g(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:n,miniBirthday:o,maxBirthday:i,cursor:r,gender:a}=e,c={Count:t,Keywords:s,KeywordMatchType:n,Cursor:r,UserBirthStart:o,UserBirthEnd:i,Gender:a};return sl.core.common.buildAndSendPacket({servcmd:"user_search.query",data:c})}))}(r);if(!a)return{error:0,data:{}};const{ErrorCode:c,ErrorInfo:u,TotalCount:l,Cursor:d="",Users:p=[]}=a;if(0!==c)throw{errorCode:c,errorInfo:u};const _=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${l}`;s.setLogInfo({message:_}).end();const m=[];for(let e=0,s=p.length;e<s;e++){const{UserID:s,ProfileItems:n}=p[e];if(s===this._core.OuterConstant.USER_NOT_FOUND||""===s)continue;const o=n.map((e=>({tag:e.Tag,value:e.StrValue}))),i=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,o);m.push(i)}return{code:0,data:{searchResultList:m,cursor:d,totalCount:l}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ol,functionName:"searchCloudUsers"})}}))}searchCloudGroupMembers(e){return g(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:s=cl,keywordListMatchType:n}=e,o=h(e,["count","keywordListMatchType"]),i=Object.assign({count:s,keywordListMatchType:n===il.AND?1:0},o),r=yield function(e){return g(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:n,groupTypeList:o,cursor:i,groupIDList:r}=e,a={Count:t,Keywords:s,KeywordMatchType:n,Cursor:i,GroupType:o,GroupIdList:r};return sl.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:a})}))}(i);if(!r)return{code:0,data:{}};const{ErrorCode:a,ErrorInfo:c,GroupMembers:u=[],Cursor:l,TotalCount:d}=r;if(0!==a)throw{errorCode:a,errorInfo:c};const p=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${d}`;t.setLogInfo({message:p}).end();const _=new Map;return u.forEach((e=>{const{GroupID:t,GroupName:s,GroupType:n,GroupFaceUrl:o,GroupMemberUserName:i,GroupMemberUserID:r,GroupMemberNameCard:a,GroupMemberAvatar:c=""}=e,u={groupID:t,name:s,type:n,avatar:o},l={userID:r,nick:i,nameCard:a,avatar:c};if(_.has(t)){const e=_.get(t);e.memberList.push(l),_.set(t,e)}else _.set(t,{groupInfo:u,memberList:[l]})})),{code:0,data:{searchResultList:[..._.values()],cursor:l,totalCount:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ol,functionName:"searchCloudGroupMembers"})}}))}searchCloudGroups(e){return g(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:s=rl,keywordListMatchType:n}=e,o=h(e,["count","keywordListMatchType"]),i=Object.assign({count:s,keywordListMatchType:n===il.AND?1:0},o),r=yield function(e){return g(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:n,groupTypeList:o,cursor:i}=e,r={Count:t,Keywords:s,KeywordMatchType:n,Cursor:i,GroupType:o};return sl.core.common.buildAndSendPacket({servcmd:"group_search.query",data:r})}))}(i);if(!r)return{code:0,data:{}};const{ErrorCode:a,ErrorInfo:c,Groups:u,Cursor:l,TotalCount:d}=r;if(0!==a)throw{errorCode:a,errorInfo:c};const p=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${d}`;t.setLogInfo({message:p}).end();return{code:0,data:{searchResultList:(null==u?void 0:u.map((e=>function(e){const{GroupFaceUrl:t,GroupID:s,GroupIntroduction:n,GroupMemberNum:o,GroupName:i,GroupOwnerTinyID:r,GroupOwnerUserID:a,GroupOwnerUserName:c,GroupType:u,GroupAddOption:l,GroupInviteOption:d}=e;return{avatar:t,groupID:s,introduction:n,memberCount:o,name:i,ownerTinyID:r,ownerID:a,ownerNick:c,type:u,joinOption:l,inviteOption:d}}(e))))||[],cursor:l,totalCount:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ol,functionName:"searchCloudGroups"})}}))}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&t>0&&(e.startTime=s&&s>0?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&s>0&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s,functionName:n}){const{ssoLog:o,helper:i}=this._core;let r=e;60020===e?r="SearchUnable":s!==nl&&27003===e?r="SearchParamsError":s!==nl&&60018===e&&(r="SearchOverLimit");const a=new i.ChatError({code:r,message:t});throw o.getSSOLogData(n).setError(a).end(),a}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){const{miniBirthday:s,maxBirthday:n}=t;void 0!==s&&(e.miniBirthday=s,void 0===n&&(e.maxBirthday=4294967295)),void 0!==n&&(e.maxBirthday=n)}};function El(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}const Cl="qualityStat",Ml="im-ssolog-quality-stat";var yl;!function(e){e[e.ONLINE=8]="ONLINE"}(yl||(yl={}));const Ol="networkRTT",Al="messageE2EDelay",Tl="sendMessageC2C",Rl="sendMessageGroup",Dl="sendMessageGroupAV",bl="sendMessageRichMedia",Ll="cosUpload",Nl="messageReceivedGroup",Pl="messageReceivedGroupAVPush",Gl="messageReceivedGroupAVPull",wl={[Ol]:2,[Al]:3,[Tl]:4,[Rl]:5,[Dl]:6,[bl]:7,[Nl]:8,[Pl]:9,[Gl]:10,[Ll]:11},Ul=[Tl,Rl,Dl,bl,Ll],kl=[Nl,Pl,Gl],Fl=[Ol,Al,Tl,Rl,Dl,bl,Ll,Nl,Pl,Gl],$l={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},xl="quality_stat";var ql=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values($l))}init(e){this._core=e,Object.values(Ul).forEach((e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})}))}dispatchSendStats(e){const{name:t,message:s,error:n,startTs:o}=e,{SEND_MESSAGE_STAT:i}=this._core.constants;switch(t){case i.TOTAL_COUNT:this._handleTotalCount(s);break;case i.SUCCESS_COUNT:this._handleSuccessCount(s);break;case i.FAILED_COUNT:this._handleFailedCount(s,n);break;case i.SEND_COST:this._handleSendCost(s,o)}}getStatResult(e){const t=this._messageStatsMap.get(e);if(!t||0===t.totalCount)return null;const{totalCount:s,successCount:n,failedCountOfUserSide:o}=t,i=El(n/s*100,2),r=n+o,a=El(r/s*100,2),c=this._calcAverageValue(t,e);return this._resetStat(e),{total_count:s,success_count_business:n,percent_business:i,success_count_platform:r,percent_platform:a,average_value:c}}_handleTotalCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.totalCount++}_handleSuccessCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.successCount++}_handleFailedCount(e,t){var s;const n=null!==(s=null==t?void 0:t.code)&&void 0!==s?s:null==t?void 0:t.errorCode;if(this._isUserSideError(n)){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.failedCountOfUserSide++}}_handleSendCost(e,t){const s=this._getSendMessageSpecifiedKey(e),n=s&&this._messageStatsMap.get(s);n&&(n.costSum+=Date.now()-t,n.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||e>=120001&&e<=13e4||e>=10100&&e<=10200}_getSendMessageSpecifiedKey(e){const{MSG_IMAGE:t,MSG_AUDIO:s,MSG_VIDEO:n,MSG_FILE:o,CONV_C2C:i,CONV_GROUP:r,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([t,s,n,o].includes(e.type))return bl;if(e.conversationType===i)return Tl;if(e.conversationType===r){const{groupStore:t}=this._core.appStore,s=t.getGroup(e.to);if(!s)return;const{type:n}=s;return n===a?Dl:Rl}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Ll?Math.round(1e3*e.fileSizeSum/e.costSum):Math.round(e.costSum/e.costCount)}_resetStat(e){const t=this._messageStatsMap.get(e);t&&(t.totalCount=0,t.successCount=0,t.failedCountOfUserSide=0,t.costSum=0,t.costCount=0,t.fileSizeSum=0)}};var Vl=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){this._core=e;const{OuterEvent:t,notificationCenter:s}=e;this._initStatsMap(),s.subscribeOuterEvent(t.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){const t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:n}}=this._core;if(s(t)||!this._currentCycleStats.has(t))return void console.warn(`${Cl}.addMessageSequence invalid key:`,t);const{conversationID:o,sequence:i}=e,r=o.replace(n,""),a=this._lastCycleStats.get(t);if(0===a.size||!a.has(r))return void this._addToCurrentCycle(t,r,i);const c=a.get(r);i>c.minSeq&&i<c.maxSeq?this._insertToLastCycle(i,c):this._addToCurrentCycle(t,r,i)}getStatResult(e){const t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let s=0,n=0;return t.forEach((e=>{const{sortedSequences:t,minSeq:o,maxSeq:i}=e;t.length>0&&(n+=t.length,s+=i-o+1)})),0===s?null:(this._transferCycleDataOptimized(e),{total_count:s,success_count_business:n,percent_business:El(n/s*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(kl).forEach((e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)}))}_onMessageReceived(e){const{data:t=[]}=e;t.forEach((e=>{this.addMessageSequence(e)}))}_transferCycleDataOptimized(e){const t=this._currentCycleStats.get(e);if(!t)return;const s=new Map;t.forEach(((e,t)=>{const n=e.dirty?[...e.sortedSequences].sort(((e,t)=>e-t)):e.sortedSequences;s.set(t,{sortedSequences:n,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})})),this._lastCycleStats.set(e,s),this._currentCycleStats.set(e,new Map)}_getReceivedMessageSpecifiedKey(e){const{OuterConstant:{CONV_GROUP:t,GRP_AVCHATROOM:s}}=this._core;if(e.conversationType===t&&!0!==(null==e?void 0:e._onlineOnlyFlag)){const{groupStore:t}=this._core.appStore,n=t.getGroup(e.to);if(!n)return null;const{type:o}=n;return o===s?Gl:Nl}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort(((e,t)=>e-t)),t.dirty=!1);const s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,n=e.length-1;for(;s<=n;){const o=Math.floor((s+n)/2);if(e[o]===t)return o;e[o]<t?s=o+1:n=o-1}return s}_addToCurrentCycle(e,t,s){let n=this._currentCycleStats.get(e).get(t);n?(n.sortedSequences.push(s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s),n.dirty=!0):(n={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,n))}};var Bl=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){this._core=e;const{OuterEvent:{MESSAGE_RECEIVED:t},notificationCenter:s}=e;s.subscribeOuterEvent(t,this._onMessageReceived,this)}addMessageDelay(e){const{timeManager:t}=this._core.common,s=t.getServerTimeSeconds()-e;s>0&&(this._totalDelay+=s,this._totalCount++,s<=1?this._countLessThan1s++:s<=3&&this._countLessThan3s++)}getStatResult(){if(0===this._totalCount)return null;const e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),e}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){const{data:t=[]}=e,{OuterConstant:{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:n}}=this._core,o=[s,n];t.forEach((e=>{!o.includes(e.type)&&e.clientTime>0&&this.addMessageDelay(e.clientTime)}))}_calculateAverageDelay(e){return 0===e?0:El(this._totalDelay/e,1)}_calculatePercentage(e,t){return El(e/t*100,2)}};var jl=new class{init(e){this.core=e}};var Kl=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:o,DESTROY:i},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:a}}=e;jl.init(e),ql.init(e),Vl.init(e),Bl.init(e),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(n,this._handleQualityStat,this),s.subscribeInnerEvent(o,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){console.log(`${Cl}.handleLoginSuccess`);const{store:e,helper:t,utils:{isUndefined:s}}=this._core,n=e.get("cloudConfig")||{},{q_rpt_interval:o}=n,i=s(o)?12e4:Number(o);t.taskScheduler.addTask({id:xl,intervalMs:i,callback:this.report,context:this})}report(){this._wholePeriod=!0;const e=[...Fl.map((e=>{const t=this._buildQualityReportItem(e);return t?Object.assign(Object.assign({},t),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null})).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){const{constants:{QUALITY_METRICS:t}}=this._core,{label:s,data:n}=e;s===t.MESSAGE_SEND_SUCCESS_RATE&&ql.dispatchSendStats(n)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},n=e.get("instance")||{},{sdkAppId:o}=n,{q_rpt_sdkappid_bl:i=[]}=s;if(t.isEmpty(i))return;return i.split(",").map((e=>Number(e))).includes(o)}_isTinyIDInWhitelist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},n=e.get("login")||{},o=Number(n.tinyID),{q_rpt_tinyid_wl:i=[]}=s;if(!t.isEmpty(i))return i.split(",").includes(o)}_buildQualityReportItem(e){const t=this._getStatResultByKey(e);if(null===t)return null;const s={quality_type:wl[e],timestamp:Date.now(),network_type:yl.ONLINE,extension:""};return Object.assign(Object.assign({},s),t)}_getStatResultByKey(e){switch(e){case Al:return Bl.getStatResult();case Tl:case Rl:case Dl:case bl:case Ll:return ql.getStatResult(e);case Nl:case Pl:case Gl:return Vl.getStatResult(e);default:return null}}_uploadQualityReports(e){return g(this,void 0,void 0,(function*(){try{const t={header:this._core.common.getCommonHead(),quality:e};yield function(e){const{common:t,channel:s}=jl.core,n="imopenstat.tim_web_report_v2",o=t.generateSSOLogProtocolData({servcmd:n,data:e}),i=`${o.head.seq}${n}`;s.sendPacket(o,{requestId:i})}(t),this._reportIndex++,this._wholePeriod=!1}catch(t){console.warn("doReport failed. error:",t),this._pendingReports=this._pendingReports.concat(e),this._cacheFailedLogs()}}))}_cacheFailedLogs(){const e=this._pendingReports,t=`${Cl}._cacheFailedLogs`;let s=[...this._failedLogsCache.get(Ml)||[],...e];s.length>10&&(s=s.slice(s.length-10),console.log(`${t} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(Ml,s),console.log(`${t} count: ${s.length}`),this._pendingReports=[]}_reset(){const{helper:e}=this._core;e.taskScheduler.removeTask(xl)}_dispose(){const{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:n}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(n,this._dispose,this),this._reset(),Bl.dispose(),Vl.dispose()}};const Hl=1,Wl=300;var Yl=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n,InnerEvent:o}}=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(o.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){const{conversationList:t}=(null==e?void 0:e.result)||{},{OuterConstant:s,utils:{isArray:n}}=this._core;if(n(t)){const e=t.filter((e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM));return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return g(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=[],n=[];return yield Promise.all(null==e?void 0:e.map((e=>g(this,void 0,void 0,(function*(){const{groupProfile:{groupID:o}={},lastMessage:{lastSequence:i}={}}=e,r=`${t.CONV_GROUP}${o}`;let a=this._getLocalLastMessageSequence(r);this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:i})&&(yield this._recoverHistoryForConversation({conversationID:r,localLastMessageSequence:a,serverLastMessageSequence:i,groupTipList:n})),s.push(r.replace(t.CONV_GROUP,""))}))))),{recoverRevokeNoticeGroupIDList:s,groupTipList:n}}))}_recoverHistoryForConversation(e){return g(this,arguments,void 0,(function*({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:n}){try{const{utils:{isArray:o,isObject:i,isEmpty:r},OuterEvent:a,OuterConstant:c,notificationCenter:u,message:l,appStore:d,common:{getMessagePreviewText:h}}=this._core,g=s-t,p=Math.min(20,g),_={},m=yield l.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:e,sequence:t+p,direction:c.Direction.FORWARD,count:p}),{nextReqMessageIDFromServer:v,hasNoMoreHistoryMessage:f,messageList:I,serverGroupTipList:S}=m;o(S)&&n.push(...S);const E=f&&v<0,C=[];if(o(I)&&(I.forEach((e=>{l.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===c.CONV_SYSTEM&&(e.isSystemMessage=!1);l.messageDataHandler.storeConversationMessage(e)&&!r(e.payload)&&(C.push(e),e._isExcludedFromLastMessage||(_.lastMessage=Object.assign({},e)))})),C.length>0&&u.emitOuterEvent(a.MESSAGE_RECEIVED,{name:a.MESSAGE_RECEIVED,data:C})),!E&&I.length>0){const t=I[I.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:n})}i(_.lastMessage)&&(_.lastMessage.messageForShow=h(_.lastMessage.type,_.lastMessage.payload),d.conversationStore.updateConversation(e,_))}catch(t){console.debug("Recovery failed for conversation:",e,t)}}))}_updateLastMessageSequenceMapOnDisconnect(){const{message:e}=this._core,t=e.messageDataHandler.getContinuousMessagesByConversation();for(const[e,s]of t){if(e.startsWith("C2C"))continue;const t=Array.from(s.values());if((null==t?void 0:t.length)>0){const s=t[t.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(e,s)}}}_getLocalLastMessageSequence(e){const{message:t}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=t.messageDataHandler.getLocalMessageList(e),n=s[s.length-1];return null==n?void 0:n.sequence}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const n=s-t;return 0!==s&&t>0&&(n>=Hl&&n<Wl)}};let zl=_s.STANDARD,Jl=[];zl=_s.STANDARD,Jl=[Mn,Cn,Tn,Un,$n,Kl,Yl,Ii,Cr,na,Cu,tl,Sl,po];var Ql=Object.freeze({__proto__:null,ChatError:Fs,WorkflowManager:zs,buildAndSendPacket:tn,get builtInPlugins(){return Jl},checkBusinessCapabilityBits:Ys,deepMerge:cn,getCurrentUserID:rn,getErrorMessage:ks,getMessagePreviewText:un,isC2CConv:e=>_(e)&&e.slice(0,3)===rs.CONV_C2C,isCommunity:Qs,isGroupConv:e=>_(e)&&e.slice(0,5)===rs.CONV_GROUP,isTopic:Xs,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=Vt.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:Js,registerInterceptor:Hs,registerValidateConfig:Ws,requireAuth:$s,get sdkEdition(){return zl},updateGroupAtInfo:(e,t)=>{const{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=gs;if(function(e,t){const{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=gs,{groupID:i,sequence:r}=e;let a=!1;if(!Qs({groupID:i}))return a;return t.forEach((t=>{t.messageSequence===r&&(t.atTypeArray.includes(s)&&e.groupAtType.includes(n)&&(t.atTypeArray=[o]),t.atTypeArray.includes(n)&&e.groupAtType.includes(s)&&(t.atTypeArray=[o],t.__random=e.__random,t.__sequence=e.__sequence),a=!0)})),a}(e,t))return;let i=[...e.groupAtType];i.includes(s)&&i.includes(n)&&(i=[o]);const r={from:e.from,groupID:e.groupID,topicID:e.topicID,messageSequence:e.sequence,atTypeArray:i,__random:e.__random,__sequence:e.__sequence};t.push(r)},validateAndExecute:Ks,validateParameters:xs});class Xl{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Xl._instance||(Xl._instance=new Xl),Xl._instance}static setInstance(e){Xl._instance=e}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(e,t){let s=[];s=v(e)?e:[e];const n=s.findIndex((e=>"AVChatRoom"===(null==e?void 0:e.name))),o=n>-1?s.splice(n,1):[];s.forEach((e=>{this._isPluginInstalled(e.name)||(e&&Bt(e.install)?(t.add(e.name),Bt(e.getInstalledSubPlugins)?e.install(od.getInstance().exposeApiForPlugin(),o):e.install(od.getInstance().exposeApiForPlugin()),Bt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Bt(e)?(t.add(e.name),e(od.getInstance().exposeApiForPlugin()),Bt(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=Vt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}}var Zl=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}){const{emit:n,needSort:o}=s,i=this._conversationMap.get(e);i&&!me(t)&&(Object.keys(t).forEach((e=>{i[e]=t[e]})),n&&Vt.notificationCenter.emitInnerEvent(zt.CONVERSATION_UPDATED,{needSort:o}))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),Vt.notificationCenter.emitInnerEvent(zt.CONVERSATION_UPDATED))}};var ed=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const s=this._groupMap.get(e);s&&!me(t)&&Object.keys(t).forEach((e=>{s[e]=t[e]}))}};var td=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,s){var n;const{operation:o,updateUnreadCount:i=!0}=s,r=h(s,["operation","updateUnreadCount"]),a=[];for(const s of t){const t=null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.get(s);if(!t)return!1;Object.keys(r).forEach((e=>{t[e]=r[e]})),a.push(t)}return this._emitMessageStoreOperationEvent(o,{conversationID:e,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){var t;return[...(null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){const{conversationID:s}=t;Xs(s)?Vt.notificationCenter.emitInnerEvent(ns[e],t):Vt.notificationCenter.emitInnerEvent(e,t)}};var sd=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)}},nd=Object.freeze({__proto__:null,conversationStore:Zl,groupStore:ed,messageStore:td,userStore:sd});class od{static getInstance(){return od._instance||(od._instance=new od),od._instance}static setInstance(e){od._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this)},this._apiHandlersMap={},this._apiMap={on:Vt.notificationCenter.subscribeOuterEvent.bind(Vt.notificationCenter),off:Vt.notificationCenter.unSubscribeOuterEvent.bind(Vt.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Xl.getInstance().installExternalPlugin.bind(Xl.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){console.log("registerPlugin",e)}statKeyFeatureUsage(e){console.log("statTUIKeyFeatures",e)}setLogLevel(e){console.log("setLogLevel",e),Vt&&"function"==typeof Vt.setLogLevel&&(null==Vt||Vt.setLogLevel(e))}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){const{apiName:t,context:s,methodName:n=t,matcher:o}=e;this._apiHandlersMap[t]||(this._apiHandlersMap[t]=[]),this._apiHandlersMap[t].push({context:s,methodName:n,matcher:o}),this._apiMap[t]&&1!==this._apiHandlersMap[t].length||(this._apiMap[t]=(...e)=>{Ks(n,e);const s=this._apiHandlersMap[t];for(const t of s)if(!t.matcher||t.matcher(e))return t.context[t.methodName].bind(t.context)(...e)})}registerExperimentalAPI(e,t,s){const n=s||e;this._experimentalApiMap[e]=t[n].bind(t)}destroy(){return g(this,void 0,void 0,(function*(){var e,t;try{(null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield this._apiMap.logout()),Vt.notificationCenter.emitInnerEvent(zt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{Vt.notificationCenter.emitOuterEvent(Wt.SDK_DESTROY,{SDKAppID:null===(t=Vt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Js.clear(),Xl.getInstance().clear(),zs.getInstance().destroy(),Vt.destroy()}}))}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:zt,InnerEventSubType:Vt.notificationCenter.InnerEventSubType,OuterEvent:Wt,OuterConstant:gs,SignalingEvent:Jt,helper:Object.assign(Object.assign(Object.assign({},Vt.utils),Vt.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Hs,registerValidateConfig:Ws,checkBusinessCapabilityBits:Ys,registerWorkflowStep:zs.getInstance().registerWorkflowStep.bind(zs.getInstance()),ChatError:Fs}),apiMap:this._apiMap},Vt),{constants:Object.assign(Object.assign({},Es),Vt.constants),common:Object.assign(Object.assign(Object.assign({},Ql),Vt.common),{workflowManager:zs.getInstance()}),utils:Vt.utils,appStore:nd})}callExperimentalAPI(e,t){return this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new Fs({code:ps.INVALID_OPERATION}))}}class id{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=Vt;t.set("login",{isReady:!1}),od.getInstance().registerApi({apiName:"login",context:this}),od.getInstance().registerApi({apiName:"logout",context:this}),od.getInstance().registerApi({apiName:"getLoginUser",context:this}),od.getInstance().registerApi({apiName:"isReady",context:this}),e.subscribeInnerEvent(zt.RECONNECTED,this._reLogin,this),Vt.notificationCenter.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}login(e){return g(this,void 0,void 0,(function*(){const t=this._getUiPlatform(),{sdkEdition:s}=Vt.store.get("instance")||{},n=Vt.ssoLog.createSSOLogData({method:"login",eventType:4,uiPlatform:t,message:s});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Fs({functionName:"login",code:ps.REPEAT_LOGIN});const t=yield this._performLogin(e);return this._validateAfterLogin(t),this._handleLoginSuccess(t),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,{code:0,data:t}}catch(e){const{errorCode:t}=e;t!==ps.REPEAT_LOGIN&&(this._latestLoginAt=0);const s=new Fs({functionName:"login",code:t});throw n.setError(s).end(!0),s}}))}_getUiPlatform(){var e;const{store:t}=Vt,s=null===(e=t.get("instance"))||void 0===e?void 0:e.scene;if("string"==typeof s){const e=Number(s);return isNaN(e)?void 0:e}}_reLogin(){return g(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=Vt.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Us();if(s){const{instanceID:n,customStatus:o}=s;Vt.store.set("login",{statusInstanceId:n}),zs.getInstance().executeWorkflow(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:o,statusType:os.USER_STATUS_ONLINE});const i=`socketId:${null===(e=Vt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${n}`;t.setLogInfo({message:i}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return g(this,arguments,void 0,(function*(e=Cs.USER_INITIATED){const t=Vt.ssoLog.createSSOLogData({method:"logout"});t.setLogInfo({moreMessage:`identifier:${rn()}`});try{yield this._performLogout(e),t.end(!0),Vt.ssoLog.uploadSSOLogData()}catch(e){const{errorCode:t}=e,s=new Fs({functionName:"logout",code:t});this._handleLogoutError(s)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?rn():""}isReady(){var e;return null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){Vt.store.set("login",{isReady:!0}),setTimeout((()=>{Vt.notificationCenter.emitOuterEvent(Wt.SDK_READY,{name:Wt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){Vt.store.set("login",{isReady:!1}),Vt.notificationCenter.emitOuterEvent(Wt.SDK_NOT_READY,{name:Wt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s;const n="login";if(!e)throw new Fs({functionName:n,message:"login response is empty"});const{tinyID:o,a2Key:i}=e||{},r=Vt.ssoLog.getSSOLogData(n);if(!o){const e=new Fs({functionName:n,code:ps.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!i){const e=new Fs({functionName:n,code:ps.NO_A2KEY});throw null===(s=null==r?void 0:r.setError)||void 0===s||s.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:ks({code:"RepeatLogin",replacement1:null===(e=Vt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return g(this,void 0,void 0,(function*(){const{userID:t,userSig:s}=e;return Vt.store.set("login",{userId:t,userSig:s}),this._latestLoginAt=Date.now(),Us()}))}_ensureAsyncComplete(){return g(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=Vt.common,{helloInterval:s,timeStamp:n,customStatus:o,purchaseBits:i}=e,r=1e3*n;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=s||120,this._updateLoginStore(e),Vt.user.userStatus.setCustomStatus(o),zs.getInstance().executeWorkflow(ms.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),Vt.common.taskScheduler.addTask({id:As,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return g(this,void 0,void 0,(function*(){const{logoutReason:t}=e,s="im_open_status.wslogout",n=Vt.common.generateProtocolData({servcmd:s,data:{wslogout_type:t,isWebUniapp:0}}),o=`${n.head.seq}${s}`;return yield Vt.channel.sendPacket(n,{requestId:o})}))}({logoutReason:e})}_handleLogoutError(e){Vt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),zs.getInstance().reset(),Vt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:s,instanceID:n,authKey:o}=e;Vt.store.set("login",{a2Key:t,tinyID:s,statusInstanceId:n,authKey:o,isLoggedIn:!0})}_logLoginSuccess(e){var t;const s=Vt.ssoLog.getSSOLogData("login"),{helloInterval:n,instanceID:o,timeStamp:i,customStatus:r}=e,a=null===(t=Vt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=Vt.common.timeManager.getTimeOffsetWithServer(),{appId:u,href:l}=Vt.store.get("instance")||{},d=`login._logLoginSuccess socketID:${a} scene: helloInterval:${n} instanceID:${o}\n timeStamp:${i} offset:${c} customStatus:${r} href: ${l} appId: ${u}`;console.log(`login ok. ${d}`),s.updateLogCreatedAtByTimeOffset(),s.setLogInfo({moreMessage:d}).end()}_sendOnlinePresenceRequest(){return g(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=Vt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),s=`${t.head.seq}${e}`;return Vt.channel.sendPacket(t,{requestId:s})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_isLoginIn(){var e;return!0===(null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),Vt.common.taskScheduler.removeTask(As),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,Vt.store.clear("login"),Vt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}}const rd={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},ad={logout:!0};class cd{constructor(){this.loginAction=new id,this.kickedOutHandler=new ws,this.loginAction.init(),this.kickedOutHandler.init(),Ws({auth:ad,params:rd})}}var ud,ld,dd;!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"}(ld||(ld={})),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"}(dd||(dd={}));const hd={1:ld.MSG_PRIORITY_HIGH,2:ld.MSG_PRIORITY_NORMAL,3:ld.MSG_PRIORITY_LOW,4:ld.MSG_PRIORITY_LOWEST},gd=0,pd=1;var _d;!function(e){e.IN="in",e.OUT="out"}(_d||(_d={}));const md=2,vd={};function fd(e){if(!e)return 0;if(void 0===vd[e]){const t=new Date,s=`3${t.getHours()}`.slice(-2),n=`0${t.getMinutes()}`.slice(-2),o=`0${t.getSeconds()}`.slice(-2);vd[e]=parseInt([s,n,o,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${vd[e]}`)}else vd[e]+=1;return vd[e]}class Id{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=ld.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=Vt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:s,currentUser:n,needReadReceipt:o,isSupportExtension:i,customModerationConfigurationId:r,to:a,from:c,nick:u="",avatar:l="",time:d,messageControlInfo:h,tinyID:g,cloudCustomData:p="",messageLifeTime:_,messageVersion:m=0,conversationType:v,sequence:f,checkResult:I=0,isPlaceMessage:S=0,messageFlagBits:E,receiverList:C,isSystemMessage:M=!1,status:y=Zt.SUCCESS,revokeReason:O="",conversationSubType:A,clientSequence:T,protocol:R="JSON",revokerInfo:D={userID:"",nick:"",avatar:""},readReceiptInfo:b={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:L,groupProfile:N,atUserList:P,flow:G,isRead:w=!1}=e;var U;this.clientTime=t,this.senderTinyID=s||g,this.needReadReceipt=!0===o||1===o,this.isSupportExtension=!0===i||1===i,this._cmConfigID=r,this.to=a,this.nick=u,this.avatar=l,this.protocol=R,this.random=void 0===L?(U=U||99999999,Math.round(Math.random()*U)):L,this.time=d||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!(null==h?void 0:h.excludedFromLastMessage),this._isExcludedFromUnreadCount=!!(null==h?void 0:h.excludedFromUnreadCount),this.isModified=!!m,this.cloudCustomData=p,this.messageLifeTime=_,this.from=c||null,this.sequence=f||0,this.conversationType=v||ud.CONV_C2C,this.hasRiskContent=I>1,this.version=m,this.isPlaceMessage=S,this.isRevoked=2===S||8===E,this.isSystemMessage=M,this.readReceiptInfo=b,this.revokeReason=O,this.revokerInfo=D,this._receiverList=C,this.conversationSubType=A,this.revoker=(null==D?void 0:D.revoker)||"",this.clientSequence=T||f||0,this.status=y,this.atUserList=P||[],this.flow=G,this.isRead=w,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(N)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map((e=>e.transformToServerFormat())):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,s;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(s=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===s?void 0:s.call(t):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:s=0}=e;this.conversationType===ud.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=s)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:s,MsgFrom_AccountExtraInfo:n}=e,{NameCard:o}=n||{};"string"==typeof t&&(this.nick=t),"string"==typeof s&&(this.avatar=s),"string"==typeof o&&(this.nameCard=o)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const s=this.conversationType;s!==ud.CONV_SYSTEM?(t=s===ud.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${s}${t}`:null):this.conversationID=ud.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=fd(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 Sd{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:s,Ext:n,Desc:o}=t;return new Sd({data:s,description:o,extension:n})}constructor(e){this.type=dd.MSG_CUSTOM;const{data:t="",description:s="",extension:n=""}=e;this.content={data:t,description:s,extension:n}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{data:n,description:o,extension:i}=s;return{MsgType:this.type,MsgContent:{Data:n,Ext:i,Desc:o}}}validateBeforeSend(){const{isEmpty:e}=Vt.utils,t=[this.content.data,this.content.description,this.content.extension].some((t=>!e(t)));return{isValid:t,error:t?null:{message:"content can not be empty"}}}}class Ed{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:s}=t;return new Ed({text:s})}constructor(e){this.type=Xt.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e,t;return(null===(t=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===t?void 0:t.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{text:n}=s;return{MsgType:this.type,MsgContent:{Text:n}}}}var Cd=new class{constructor(){this._elementClassMap={[dd.MSG_CUSTOM]:Sd,[dd.MSG_TEXT]:Ed}}init(){od.getInstance().registerApi({apiName:"createCustomMessage",context:this}),od.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var s;void 0!==(s=t).prototype&&"constructor"in s.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:s=_d.OUT}=e,{userId:n}=Vt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:s,currentUser:n})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:n})&&(e.flow=_d.OUT);const o=Object.assign(Object.assign({},e),{currentUser:n});return new Id(o)}createCustomMessage(e){const t=rn(),s=this.createMessage(Object.assign(Object.assign({},e),{from:t})),n=this._elementClassMap[dd.MSG_CUSTOM];if(!s)return null;if(n){const t=new n(e.payload);s.setElement(t)}return s}createTextMessage(e){var t;if(!e)return null;const s="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",n=new Ed({text:s}),o=rn(),i=Vt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}_updateWithSenderInfo(e){const{nick:t,avatar:s}=e,{userId:n,tinyID:o}=Vt.store.get("login")||{},i=sd.getUserProfile(n);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||o||"",e.from=n,e.status=Zt.UNSENT,e.flow=_d.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===_d.IN}_isSendByCurrentInstance(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===_d.OUT}};const Md={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}},yd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Od={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Ad(e,t){return Object.keys(t).forEach((s=>{const{range:n,defaultValue:o}=t[s];e[s]=n.includes(e[s])?e[s]:o})),e}function Td(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function Rd(e){const{androidInfo:t={},androidOPPOChannelID:s=""}=e,n=t.OPPOChannelID||s,o=Ad(t,yd),{sound:i="",FCMChannelID:r=""}=o,a=h(o,["sound","FCMChannelID"]);return Object.assign(Object.assign({},a),{Sound:Td(i),OPPOChannelID:n,GoogleChannelID:r})}function Dd(e){const{apnsInfo:t={},ignoreIOSBadge:s=!1,disableVoipPush:n}=e,o=Ad(t,Od),{ignoreIOSBadge:i,disableVoipPush:r,enableIOSBackgroundNotification:a}=o,c=h(o,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),u=!0===i||!0===s?1:0;let l;return p(n)||(l=!1===n?1:0),p(r)||(l=!1===r?1:0),Object.assign(Object.assign({},c),{BadgeMode:u,IsVoipPush:l,ContentAvailable:a?1:0})}function bd(e){return Vt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:Dd(e),AndroidInfo:Rd(e)}:Md}function Ld(e){const{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:n,IsPeerRead:o,IsSyncMsg:i,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:u,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e;let S,{From_Account:E,To_Account:C}=e;if(1===i){const e=C;C=E,E=e}if(I){const{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===n,isSyncMessage:i,clientTime:a,messageLifeTime:c,random:u,sequence:l,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:g,to:C,tinyID:p,checkResult:_,cloudCustomData:m,revokerInfo:S,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:o,elements:wd(r)}}function Nd(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:u}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,to:a,elements:wd(s),messageVersion:c,cloudCustomData:u}}function Pd(e){const{ClientSeq:t,From_Account:s,GroupInfo:n,MsgBody:o,MsgClientTime:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:u,SupportMessageExtension:l,TinyId:d,CloudCustomData:h,MsgVersion:g,MsgCheckResult:p,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e;let I,S=ld.MSG_PRIORITY_NORMAL;if(Object.keys(hd).includes(String(e.MsgPriority))&&(S=hd[e.MsgPriority]),v){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}const E=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===gd?t.push(e.GroupAt_Account):e.GroupAtAllFlag===pd&&t.push(gs.MSG_AT_ALL)}));return t}(f);return{clientSequence:t,from:s,groupProfile:n,clientTime:i,priority:S,random:r,sequence:a,time:c,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:l,tinyID:d,cloudCustomData:h,messageVersion:g,messageCheckResult:p,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:E,elements:wd(o),to:Gd(e)}}function Gd(e){const{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=Vt,{ToGroupId:n,GroupInfo:{MillionGroupFlag:o=0,TopicId:i}={}}=e;return o!==s||t(i)?n:i}function wd(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=Vt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=Vt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function Ud(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:u,CloudCustomData:l}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,groupID:a,topicID:c,elements:wd(s),messageVersion:u,cloudCustomData:l}}function kd({conversationUpdateFields:e,message:t}){const{conversationID:s,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,u=!r&&i===_d.IN;e.has(s)?(e.get(s).lastMessage=c,u&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:n,subType:o,unreadCount:u?1:0,lastMessage:c})}function Fd(e){return e.filter((e=>{const t=!me(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);if(!t){Vt.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return t&&!s}))}var $d=Object.freeze({__proto__:null,autoIncrementIndex:fd,filterValidMessages:Fd,parseServerGroupMessage:Pd,parseServerPushC2CModifyMessage:Nd,parseServerPushGroupModifyMessage:Ud,parseServerPushMessage:Ld,parseServerPushMessageElement:wd,updateConversationFields:kd});const{isPlainObject:xd}=Vt.utils;function qd(e,t={}){const{onlineUserOnly:s,messageControlInfo:n}=t;let{offlinePushInfo:o}=t;e.conversationType===ud.CONV_C2C&&!0===s&&(o?o.disablePush=!0:o={disablePush:!0});let i="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(i=e.cloudCustomData);const r=[];if(n&&xd(n)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=n;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===s&&r.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:o}}function Vd(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(!t&&!s)return;const n=[];return t&&n.push("ForbidBeforeSendMsgCallback"),s&&n.push("ForbidAfterSendMsgCallback"),n}function Bd(e,t){return g(this,void 0,void 0,(function*(){const s=e.conversationType===ud.CONV_GROUP?function(e,t){var s;const n=qd(e,t),{onlineUserOnly:o,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=n,c=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let u;return v(e._receiverList)&&e._receiverList.length>0&&(u=e._receiverList,e._receiverList.length>50&&(u=e._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(s=Vt.store.get("login"))||void 0===s?void 0:s.userId,GroupId:e.to,MsgBody:c,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:o?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:bd(a),SendMsgControl:o?void 0:r,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:Vd(t)}}}(e,t):function(e,t){var s;const n=qd(e,t),{onlineUserOnly:o,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=n,c=!0===o?0:void 0,u=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(s=Vt.store.get("login"))||void 0===s?void 0:s.userId,To_Account:e.to,MsgBody:u,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:bd(a),forbidCallbackControl:Vd(t)}}}(e,t),n=yield tn(s);return n?{time:n.MsgTime,messageDropReason:n.MsgDropReason,sequence:n.MsgSeq}:null}))}const{isPlainObject:Kd}=Vt.utils,{MSG_AUDIO:Hd,MSG_FILE:Wd,MSG_IMAGE:Yd,MSG_VIDEO:zd,MSG_MERGER:Jd}=gs;class Qd{init(){od.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![Hd,Wd,Yd,zd,Jd].includes(e[0].type)})}sendMessage(e,t){return g(this,void 0,void 0,(function*(){const s=Vt.ssoLog.createSSOLogData({method:"sendMessage"}),{TOTAL_COUNT:n,SEND_COST:o,SUCCESS_COUNT:i,FAILED_COUNT:r}=Ss;if(!(e instanceof Id)){const e=new Fs({code:ps.MSG_INSTANCE_REQUIRED});throw s.setError(e).end(),e}const a=e.validateBeforeSend();if(!a.isValid){const{code:e,message:t=""}=a.error||{},n=new Fs({code:e,message:t});throw s.setError(n).end(),n}this._reportMessageSendQuality({name:n,message:e});let c=!1;const{messageDataHandler:u}=Vt.message||{};try{const{messageControlInfo:s}=t||{};let n=null;u.addRandomOfSentMessage(e.random);const r=Date.now();if(e.conversationType===ud.CONV_C2C?(c=!0===(null==t?void 0:t.onlineUserOnly),n=yield Bd(e,t)):e.conversationType===ud.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(e),n=yield Bd(e,t)),n){const{messageDropReason:t,sequence:a,time:l}=n;if(this._updateNickAndAvatarOfSentMessageByMe(e),t&&this._logRateLimitInfo(e,a),this._reportMessageSendQuality({name:i,message:e}),this._reportMessageSendQuality({name:o,message:e,startTs:r}),!0===e.isResend){const t=u.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),u.deleteConversationMessage(t))}return e.status=Zt.SUCCESS,e.time=l,e.conversationType===ud.CONV_GROUP&&(e.sequence=a),c?e._onlineOnlyFlag=!0:(u.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),{code:0,data:{message:e}}}}catch(t){e.status=Zt.FAIL,u.removeRandomOfSentMessage(e.random);const{errorCode:s,errorMessage:n="",errorInfo:o=n}=t||{};this._hasRiskContent(s)&&(e.hasRiskContent=!0),c||this._isRejectedByRestApi(s)||u.storeConversationMessage(e),this._reportMessageSendQuality({name:r,message:e,error:t});const i=new Fs({code:s,message:o,data:{message:e}});throw this._logSendMessageError({message:e,error:i}),i}}))}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_logSendMessageError({message:e,error:t}){const s=Vt.ssoLog.createSSOLogData({method:"sendMessage"});let n=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(Vt.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;n+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;n+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}s.setLogInfo({message:n}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:n}=e,o=Xs(s)?zt.TOPIC_NEW_MESSAGE:zt.NEW_MESSAGE;Vt.notificationCenter.emitInnerEvent(o,{result:{conversationUpdateFieldList:[{conversationID:s,type:n,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Kd(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const s=Vt.ssoLog.createSSOLogData({method:"messageDropReason"}),n=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;s.setLogInfo({message:n}).end(),console.warn(`sendMessage ${n}`)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=Vt.message||{};let s=!1;const{conversationID:n}=e,o=t.getLatestMsgSentByMe(n);if(o){const{nick:i,avatar:r}=o;i===e.nick&&r===e.avatar||(s=!0),s&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(e){return g(this,void 0,void 0,(function*(){var t,s,n;const{to:o,from:i}=e;let r=o,a=ed.getGroup(r);if(Qs({groupID:r})&&(null==a?void 0:a.isSupportTopic))throw new Fs({code:ps.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Xs(o)&&([r]=o.split(ls.TOPIC),a=ed.getGroup(r)),!a&&"function"==typeof(null===(t=od.getInstance().getApiMap())||void 0===t?void 0:t.getGroupProfile)){const e=yield od.getInstance().getApiMap().getGroupProfile({groupID:r});if((null===(n=null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.group)||void 0===n?void 0:n.type)===gs.GRP_AVCHATROOM){const e=ks({code:ps.MSG_SEND_FAIL_NOT_IN_AV,replacement1:i,replacement2:r});throw new Fs({code:ps.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0}))}_reportMessageSendQuality(e){Vt.notificationCenter.emitInnerEvent(zt.QUALITY_STAT,{label:Is.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class Xd{constructor(e){this.value=e,this.next=null}}class Zd{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();const t=new Xd(e);this.head?(this.tail.next=t,this.tail=t):(this.head=t,this.tail=t),this.size+=1}delete(e){if(!this.head)return;if(this.head.value===e)return void(this.head=this.head.next);let t=this.head;for(;t.next;){if(t.next.value===e)return void(t.next=t.next.next);t=t.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-=1)}peek(){var e;return null===(e=this.head)||void 0===e?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 eh=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Zd(100),Vt.notificationCenter.subscribeInnerEvent(zt.LOGOUT,this._reset,this),Vt.notificationCenter.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}get _messagesByConversation(){return td.getMessages()}storeConversationMessage(e,t=!1){const{conversationID:s}=e;if(!s)return!1;if(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),this._shouldSkipStoreMessage(e,t))return!1;const n=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(s).set(n,e),this._updateLatestMessageMap(e),!0}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const s=this._getUniqueIdOfMessage(e),n=this._messagesByConversation.get(e.conversationID);if(null==n?void 0:n.has(s)){const e=null==n?void 0:n.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:s=""}=e,n=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(s)&&(null===(t=this._messagesByConversation.get(s))||void 0===t||t.delete(n))}modifyConversationMessage(e,t){var s;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(e,n);if(o){const{messageVersion:n,elements:i,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:${n}`),o.version<n){const t=this._getUniqueIdOfMessage(o),a=ve(i);return(null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.has(t))?td.updateMessage(e,[t],{isModified:!0,version:n,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:es.modify}):(o.version=n,o._elements=a,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=r,o.isModified=!0,o.hasRiskContent=c),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var s;if(this._messagesByConversation.has(e))return null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(t);if(this._sparseMessagesByConversation.has(e)){const s=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<s.length;e++)if(this._getUniqueIdOfMessage(s[e])===t)return s[e]}return null}findMessage(e){let t=null;const s=Array.from(this._messagesByConversation.values());for(const n of s){if(t=Array.from(n.values()).find((t=>t.ID===e))||null,t)break}if(!t){const s=Array.from(this._sparseMessagesByConversation.values());for(const n of s)if(t=n.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:e,sequence:t,random:s,revoker:n}){const o=this._messagesByConversation.get(e);let i=null;if(o){const r=Array.from(o.values());if(i=this._findMessageBySequenceAndRandom({messageList:r,random:s,sequence:t}),i){const t=this._getUniqueIdOfMessage(i);return td.updateMessage(e,[t],{isRevoked:!0,revoker:n,operation:es.revoke}),i}}if(this._sparseMessagesByConversation.has(e)){const o=Array.from(this._sparseMessagesByConversation.get(e).values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:s,sequence:t}),i)return i.isRevoked=!0,i.revoker=n,i}}_findMessageBySequenceAndRandom({messageList:e,sequence:t,random:s}){for(let n=0;n<e.length;n+=1){const o=e[n];if(o.sequence===t&&(p(s)||o.random===s))return o}return null}prependLocalMessageList(e){const{messageList:t,conversationID:s}=e;if(0===t.length)return[];const n=[],o=[],i=this._messagesByConversation.get(s)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);i.has(t)||(n.push(e),o.push([t,e]))}if(o.length>0){const e=new Map([...o,...i.entries()]);this._messagesByConversation.set(s,e),this._updateLatestMessageSentByMe(s),this._updateLatestMessageSentByPeer(s)}return n}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],s=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const n=this._sparseMessagesByConversation.get(t);for(let t=0;t<s;t++){const s=e[t];n.has(s.ID)||n.set(s.ID,s)}}_updateLatestMessageSentByMe(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length)for(let t=s.length-1;t>=0;t--)if("out"===s[t].flow){this._setLatestMsgSentByMe(e,s[t]);break}}_updateLatestMessageSentByPeer(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length&&e.startsWith("C2C"))for(let t=s.length-1;t>=0;t--)if("in"===s[t].flow){this._setLatestMsgSentByPeer(e,s[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:s,random:n,sequence:o,time:i}=e;return`${t}-${s}-${n}-${o}-${i}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:s,latestNick:n,isSentByMe:o=!0}=e,i=this._messagesByConversation.get(t);if(!i)return;const r=Array.from(i.values()),a=o?"out":"in";r.forEach((e=>{const{nick:t,avatar:o,flow:i}=e;i===a&&(t!==n&&(e.nick=n),o!==s&&(e.avatar=s))}))}isInMessageList(e){var t;const{conversationID:s}=e;if(!s)return!1;if(!this._messagesByConversation.has(s))return!1;const n=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(s))||void 0===t?void 0:t.has(n)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){const t=this._messagesByConversation.get(e);return t?[...t.values()]:[]}getSparseMessageList(e){const t=this._sparseMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),Vt.notificationCenter.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),Vt.notificationCenter.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}};function th(e,t){const s=Zl.getConversation(e);if(null==s?void 0:s.lastMessage){const{lastMessage:n}=s,{lastTime:o,lastSequence:i,version:r}=n,{time:a,sequence:c,messageVersion:u,elements:l,cloudCustomData:d}=t;o===a&&i===c&&r!==u&&(n.type=l[0].type,n.payload=l[0].content,n.messageForShow=un(n.type,n.payload),n.cloudCustomData=d,n.version=u,Zl.updateConversation(e,{lastMessage:n}))}}class sh{init(){od.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(e){return g(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:s,payload:n,sequence:o,conversationType:i,random:r,time:a,from:c,type:u}=e;if(!this._canModifyMessageElement(u))return void t.setLogInfo({message:`can not modify message element. message type: ${u}`}).end();const l=e.getElements();l.length>1&&(l[0].type=u,l[0].content=n);try{let n=null,u=null;if(t.setLogInfo({message:`to:${s}`}),i===ud.CONV_C2C?n=yield function(e){return g(this,void 0,void 0,(function*(){const{from:t,to:s,version:n=0,sequence:o,random:i,time:r,type:a,cloudCustomData:c}=e,u={From_Account:t,To_Account:s,MsgVersion:n,MsgSeq:o,MsgRandom:i,MsgTime:r,MsgType:a,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:c},l=yield tn({servcmd:"openim.modify_c2c_msg",data:u});if(l){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=l;return{elements:wd(e),messageVersion:t,cloudCustomData:s}}}))}(e):i===ud.CONV_GROUP&&(n=yield function(e){return g(this,void 0,void 0,(function*(){const{to:t,version:s=0,sequence:n,cloudCustomData:o}=e,i={GroupId:t,MsgVersion:s,MsgSeq:n,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:o},r=yield tn({servcmd:"openim.modify_group_msg",data:i});if(r){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=r;return{elements:wd(e),messageVersion:t,cloudCustomData:s}}}))}(e)),n){t.end();let l=`${i}${s}`;return s===rn()&&i===ud.CONV_C2C&&(l=`${i}${c}`),u={conversationType:i,from:c,to:s,time:a,random:r,sequence:o,elements:null==n?void 0:n.elements,cloudCustomData:null==n?void 0:n.cloudCustomData,messageVersion:null==n?void 0:n.messageVersion,conversationID:l},this._handleModifyMessageSuccess(u),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e||{},s=new Fs({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}))}_logModifyMessageError(e){Vt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:s,message:n}=Vt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Vt.notificationCenter.emitOuterEvent(Wt.MESSAGE_MODIFIED,{name:Wt.MESSAGE_MODIFIED,data:[n]}),Vt.notificationCenter.emitInnerEvent(zt.MESSAGE_MODIFIED,{conversationID:t,message:n}),th(t,e)}_canModifyMessageElement(e){return[dd.MSG_TEXT,dd.MSG_CUSTOM,dd.MSG_LOCATION,dd.MSG_FACE].includes(e)}}class nh{init(){const{notificationCenter:e}=Vt,{InnerEventSubType:t}=e;zs.getInstance().registerWorkflowStep(ms.RECEIVE_C2C_NEW_MESSAGE,vs.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),zs.getInstance().registerWorkflowStep(ms.RECEIVE_C2C_NEW_MESSAGE,vs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,vs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){zs.getInstance().executeWorkflow(ms.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:s}=Vt.message||{},n=[],o=new Map;return t.C2cMsgArray.forEach((e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||n.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&kd({conversationUpdateFields:o,message:t}),s.isMessageSentByCurrentInstance(t)&&!i||n.push(t)}})),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[vs.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(s)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[vs.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(s)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified))))||[];t.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const s=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));s.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:s})}_generateC2CMessage(e){const t=ud.CONV_C2C,s=Ld(e),n=Vt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:_d.IN})),{elements:o}=s;return n.setElement(o),n}_updateMessageProfile(e){var t;const{messageDataHandler:s}=Vt.message||{},n=null===(t=Vt.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a=""}=e;if(o!==n){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:n,avatar:o}=t;p(i)||p(r)?(e.nick=_(n)?n:e.nick,e.avatar=_(o)?o:e.avatar):i===n&&r===o||(s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:i,avatar:r}))}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:s,avatar:n}=e,o=Zl.getConversation(t),{userProfile:i={}}=o||{};i.avatar===n&&i.nick===s||Zl.updateConversation(t,{userProfile:Object.assign(Object.assign({},i),{nick:s,avatar:n})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=Vt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),Vt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),th(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const s=ud.CONV_C2C;let n=Nd(e);const{to:o,from:i}=n;let r=`${s}${o}`;o===(null===(t=Vt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${s}${i}`),n=Object.assign({conversationType:s,conversationID:r},n),this._updateMessageListDueToModify(n)}))}_dispose(){const{notificationCenter:e}=Vt,{InnerEventSubType:t}=e;Vt.notificationCenter.unSubscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Vt.notificationCenter.unSubscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Vt.notificationCenter.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}}class oh{init(){const{notificationCenter:e}=Vt,{InnerEventSubType:t}=e;zs.getInstance().registerWorkflowStep(ms.RECEIVE_GROUP_NEW_MESSAGE,vs.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),zs.getInstance().registerWorkflowStep(ms.RECEIVE_GROUP_NEW_MESSAGE,vs.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&zs.getInstance().executeWorkflow(ms.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:s}=Vt.message,n=[],o=new Map,i=null==t?void 0:t.GroupMsgArray;return null==i||i.forEach((e=>{if(1===e.GroupInfo.NotVisible)return;const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||n.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&(n.push(t),kd({conversationUpdateFields:o,message:t}))}})),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEvents(e){var t;const{messages:s}=(null===(t=e.result)||void 0===t?void 0:t[vs.HANDLE_GROUP_NEW_MESSAGE])||{},n=(null==s?void 0:s.filter((e=>!0===(null==e?void 0:e.isModified))))||[];n.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:n});const o=(null==s?void 0:s.filter((e=>!(null==e?void 0:e.isModified))))||[];o.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:o})}_generateGroupMessage(e){const t=ud.CONV_GROUP,s=Pd(e),n=Vt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:_d.IN})),{elements:o}=s;return n.setElement(o),n}updateMessageProfile(e){var t;const{messageDataHandler:s}=Vt.message||{},n=null===(t=Vt.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a="",_elements:c}=e;if(o===n){const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}else if(o===gs.CONV_SYSTEM){const{operationType:t,memberInfoList:s,operatorInfo:n}=c;let o={};if(me(s)?me(n)||(o=n):[ds.JOINED,ds.KICKED,ds.ADMIN_SET,ds.ADMIN_CANCELED].includes(t)&&(o=Object.assign({},s[0])),!me(o)){const{nick:t="",avatar:s=""}=o;e.nick=t,e.avatar=s}}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=Vt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),th(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach((e=>{const t=ud.CONV_GROUP;let s=Ud(e);const{topicID:n,groupID:o}=s,i=n||o,r=`${t}${i}`;s=Object.assign({conversationType:t,conversationID:r,to:i},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=Vt,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}}=e;e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var t,s;const{GroupId:n,GroupType:o}=(null===(s=null===(t=null==e?void 0:e.GroupMsgArray)||void 0===t?void 0:t[0])||void 0===s?void 0:s.GroupInfo)||{},i=o===us.GRP_AVCHATROOM;return!(!ed.getGroup(n)&&i)}}var ih=new class{constructor(){this.c2cMessageReceiver=new nh,this.groupMessageReceiver=new oh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const rh={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e)}}};const ah={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var ch=new class{getGroupRoamingMessagesByAnchor(e){return g(this,void 0,void 0,(function*(){try{const t=Vt.ssoLog.createSSOLogData({method:"getGroupRoamingMessagesByAnchor"}),{conversationID:s,count:n,direction:o,sequence:i}=e,r=s.replace(rs.CONV_GROUP,""),a=[];let c=i;if(o===ts.BACKWARD){if("number"!=typeof i)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};c=i+n-1}const u=yield function(e){return g(this,void 0,void 0,(function*(){const{groupID:t,count:s,messageSequence:n}=e,o={GroupId:t,ReqMsgNumber:s,WithRecalledMsg:1,Version:1};return n&&(o.ReqMsgSeq=n),yield tn({servcmd:"group_open_http_svc.group_msg_get",data:o})}))}({groupID:r,count:n,messageSequence:c});if(u){const{RspMsgList:e=[],NextReqMsgSeq:s=0,IsFinished:n,InvisibleMsgSeq:l}=u;t.setLogInfo({message:`groupID:${r} sequence:${i} reqSeq:${c} direction:${o}\n complete:${n} nextSequence:${s} remoteMsgCount:${e.length} invisibleSequenceList:${l}`}).end();const d=[];for(let t=0;t<e.length;t++){const s=e[t];s.From_Account===gs.CONV_SYSTEM&&a.push(s);const n=this._parseMessage(s);d.push(n)}d.reverse();let h=n===md;o===ts.BACKWARD&&(h=d[d.length-1].sequence>=i);return{messageList:Fd(d),invisibleSequenceList:l,nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:h,serverGroupTipList:a}}}catch(e){const t=new Fs({code:null==e?void 0:e.code});Vt.ssoLog.getSSOLogData("getGroupRoamingMessagesByAnchor").setError(t).end()}}))}_parseMessage(e){const t=rs.CONV_GROUP;4===e.Event&&(e.MsgBody.MsgType=gs.MSG_GRP_TIP);const s=Pd(e),n=Cd.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}};class uh{constructor(){this.messageHelper=$d,this.messageFactory=Cd,this.messageSender=new Qd,this.messageAction=new sh,this.messageReceiver=ih,this.messageDataHandler=eh,this.messageHistory=ch,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),Ws({auth:ah,params:rh})}}const lh="User",dh="Tag_Profile_IM_",hh=100,gh={NICK:`${dh}Nick`,GENDER:`${dh}Gender`,BIRTHDAY:`${dh}BirthDay`,LOCATION:`${dh}Location`,SELFSIGNATURE:`${dh}SelfSignature`,ALLOWTYPE:`${dh}AllowType`,LANGUAGE:`${dh}Language`,AVATAR:`${dh}Image`,MESSAGESETTINGS:`${dh}MsgSettings`,ADMINFORBIDTYPE:`${dh}AdminForbidType`,LEVEL:`${dh}Level`,ROLE:`${dh}Role`},ph="USER_STATUS",_h=1,mh={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:[]},vh=new Map([[gh.NICK,"nick"],[gh.GENDER,"gender"],[gh.BIRTHDAY,"birthday"],[gh.LOCATION,"location"],[gh.SELFSIGNATURE,"selfSignature"],[gh.ALLOWTYPE,"allowType"],[gh.LANGUAGE,"language"],[gh.AVATAR,"avatar"],[gh.MESSAGESETTINGS,"messageSettings"],[gh.ADMINFORBIDTYPE,"adminForbidType"],[gh.LEVEL,"level"],[gh.ROLE,"role"]]);var fh=new class{createProfile(e,t){const s={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:n}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?s.profileCustomField.push({key:t,value:n}):vh.has(t)&&(s[vh.get(t)]=n)})),Object.assign(Object.assign({},mh),s)}parseProfileItem(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.Value})})),t}parseProfileList(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.ValueBytes})})),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach((s=>{t.push({tag:gh[s.toUpperCase()],value:e[s]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:s,value:n}=e;if(vh.has(s)){const e=vh.get(s);t[e]=n}})),t}};const{generateProtocolData:Ih}=Vt.common;function Sh(e){return g(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",s={From_Account:rn(),UserItem:[]};e.forEach((e=>{s.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const n=Ih({servcmd:t,data:s}),o=`${n.head.seq}${t}`,i=yield Vt.channel.sendPacket(n,{requestId:o});if(i)return function(e){const{ActionStatus:t,ErrorCode:s,ErrorDisplay:n,ErrorInfo:o,UserProfileItem:i}=e,r=[];return i.map((e=>{const{To_Account:t,CustomSequence:s,ResultCode:n,ResultInfo:o,StandardSequence:i,ProfileItem:a}=e,c=fh.parseProfileItem(a);r.push({userId:t,customSequence:s,resultCode:n,resultInfo:o,standardSequence:i,profileItem:c})})),{actionStatus:t,errorCode:s,errorDisplay:n,errorInfo:o,userProfile:r}}(i)}))}function Eh(e){return sd.getFriendMap().has(e)}const{isEmpty:Ch}=Vt.utils;class Mh{init(){od.getInstance().registerApi({apiName:"getMyProfile",context:this}),od.getInstance().registerApi({apiName:"getUserProfile",context:this}),od.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=fh.createProfile.bind(fh);const{notificationCenter:e}=Vt;zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_LOGIN,vs.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(zt.LOGOUT,this._reset,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}getMyProfile(){return g(this,void 0,void 0,(function*(){const e=Vt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=rn(),s=yield Sh([t]);if(s){const e=this._handleProfileFormResponse(s)[0];return sd.getUserProfileMap().set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:s,errorInfo:n}=t,o=new Fs({functionName:"getMyProfile",code:s,message:n});throw e.setError(o).end(),t}}))}getUserProfile(e){return g(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:s}=e;s.length>hh&&(s=s.slice(0,hh));const{userIdListToRequest:n,userIdListToCache:o}=this._filterRequestAndCacheUsers(s),i=[];o.forEach((e=>{const t=sd.getUserProfile(e);i.push(t)}));const r=`userIDList.length:${s.length}`;if(0===n.length)return t.setLogInfo({message:r}).end(),{code:0,data:i};const a=yield Sh(n);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{Eh(e.userID)&&sd.getUserProfileMap().set(e.userID,e)}));const s=e.concat(i);return t.setLogInfo({message:r}).end(),{code:0,data:s}}}catch(e){const{errorCode:s}=e,n=new Fs({functionName:"getUserProfile",code:s});throw t.setError(n).end(),n}}))}getMyProfileCacheThenServer(){return g(this,void 0,void 0,(function*(){const e=rn(),t=sd.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return g(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"updateMyProfile"}),s=rn(),n={};for(const t in e)void 0!==e[t]&&(n[t]=e[t]);const o=fh.convertParamsToProfile(n);try{const e={From_Account:s,ProfileItem:o};t.setLogInfo({message:JSON.stringify(o)}),yield function(e){return g(this,void 0,void 0,(function*(){const t="profile.portrait_set",s=Ih({servcmd:t,data:e}),n=`${s.head.seq}${t}`,o=yield Vt.channel.sendPacket(s,{requestId:n});if(o){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:n}=o;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:n}}}))}(e);const i=sd.getUserProfile(s);let r;r=i?Object.assign(Object.assign({},i),n):fh.createProfile(s,o);return!jt(i,r,["lastUpdatedTime","profileCustomField"])&&Vt.notificationCenter.emitOuterEvent(Wt.PROFILE_UPDATED,{name:Wt.PROFILE_UPDATED,data:[r]}),r.lastUpdatedTime=Date.now(),sd.getUserProfileMap().set(s,r),t.end(),{code:0,data:r}}catch(e){const{errorCode:s,errorInfo:n}=e,o=new Fs({functionName:"updateMyProfile",code:s,message:n});throw t.setError(o).end(),o}}))}updateMyNickAndAvatar(e){return g(this,void 0,void 0,(function*(){const t=rn(),s=Date.now(),n=sd.getUserProfile(t);let o={};o=n?Object.assign(n,e):fh.createProfile(t,e),o.lastUpdatedTime=s,sd.getUserProfileMap().set(t,o)}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:s,ProfileList:n}=e;return{userId:t,pushType:s,profileList:fh.parseProfileList(n)}}(e.ProfileDataMod[0]);if(Ch(t))return;const{isProfileUpdated:s,profile:n}=this._handleProfileModified(t);s&&(Vt.notificationCenter.emitInnerEvent(zt.PROFILE_UPDATE,{name:zt.PROFILE_UPDATE,data:[n]}),Vt.notificationCenter.emitOuterEvent(Wt.PROFILE_UPDATED,{name:Wt.PROFILE_UPDATED,data:[n]}))}_dispose(){const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:s}=e,n=sd.getUserProfile(t);if(!n||!Eh(t))return{isProfileUpdated:!1,profile:null};const o=fh.normalizeProfileFields(s),i=Object.keys(o).some((e=>n[e]!==o[e]));if(!i)return{isProfileUpdated:!1,profile:n};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},n),o),{lastUpdatedTime:r});return sd.getUserProfileMap().set(t,a),Zl.updateConversation(`C2C${t}`,{userProfile:a}),{isProfileUpdated:i,profile:a}}_filterRequestAndCacheUsers(e){const t=[],s=[];return e.forEach((e=>{const n=sd.getUserProfileMap().has(e);Eh(e)&&n?s.push(e):t.push(e)})),{userIdListToRequest:t,userIdListToCache:s}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const s=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Ch(e.profileItem))),n=Date.now();return s.map((e=>{const t=fh.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=n,t}))}_reset(){sd.getUserProfileMap().clear()}}const yh=new Map,Oh=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Oh.length;e<t;e++)yh.set(e,Oh[e]);function Ah(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let s="";if(t.length%4==1)return"";for(let e,n,o=0,i=0;n=t.charAt(i++);~n&&(e=o%4?64*e+n:n,o++%4)?s+=String.fromCharCode(255&e>>(-2*o&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);try{return decodeURIComponent(escape(s))}catch(e){return console.warn(e),""}}const{isEmpty:Th}=Vt.utils,{generateProtocolData:Rh}=Vt.common;function Dh(e){return g(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",s=Rh({servcmd:t,data:{To_Account:e}}),n=`${s.head.seq}${t}`,o=yield Vt.channel.sendPacket(s,{requestId:n});if(o)return function(e){const{ErrorCode:t,ErrorInfo:s,ErrorList:n=[],UserStatusList:o=[]}=e,i=o.map((e=>{const{To_Account:t,Status:s,CustomStatus:n}=e;return{userID:t,statusType:s,customStatus:Ah(n)}})),r=n.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:Th(s)?t:s,code:n,message:o}}));return{errorCode:t,errorInfo:s,successUserList:i,failureUserList:r}}(o)}))}class bh{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=Vt;od.getInstance().registerApi({apiName:"getUserStatus",context:this}),od.getInstance().registerApi({apiName:"setSelfStatus",context:this}),od.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),od.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,vs.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(zt.LOGOUT,this._reset,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}setSelfStatus(e){return g(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"setSelfStatus"}),s=rn(),{customStatus:n}=e;try{return yield function(e){return g(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",s=Rh({servcmd:t,data:{CustomStatus:e}}),n=`${s.head.seq}${t}`,o=yield Vt.channel.sendPacket(s,{requestId:n});if(o){const{ErrorCode:e,ErrorInfo:t}=o;return{errorCode:e,errorInfo:t}}}))}(n),this._customStatus=n,t.setLogInfo({message:`customStatus: ${n}`}).end(),{code:0,data:{userID:s,statusType:_h,customStatus:n}}}catch(e){const{errorCode:s,errorInfo:n}=e,o=new Fs({functionName:"setSelfStatus",code:s,message:n});throw t.setError(o).end(),o}}))}getUserStatus(e){return g(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:s=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${s.length}`}),this._isOnlyMeInArray(s)?this._getMyStatus():this._getUserStatus(s)}))}setCustomStatus(e){const t=Ah(e);this._customStatus=t}subscribeUserStatus(e){return g(this,void 0,void 0,(function*(){try{console.log(`${lh} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const s=this._getMaxUserCount("subscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return g(this,void 0,void 0,(function*(){const{channel:t}=Vt,s="im_open_status.ws_status_subscribe",n=Rh({servcmd:s,data:{To_Account:e}}),o=`${n.head.seq}${s}`;return yield t.sendPacket(n,{requestId:o})}))}(n);return{code:0,data:{failureUserList:this._parseResponse(o)}}}catch(e){throw console.error(`${lh} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return g(this,void 0,void 0,(function*(){try{console.log(`${lh} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,s=this._getMaxUserCount("unsubscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return g(this,void 0,void 0,(function*(){const{channel:t}=Vt,s="im_open_status.ws_status_unsubscribe";let n={};n=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const o=Rh({servcmd:s,data:n}),i=`${o.head.seq}${s}`;return yield t.sendPacket(o,{requestId:i})}))}(n);return{code:0,data:{failureUserList:this._parseResponse(o)}}}catch(e){throw console.error(`${lh} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},s=t.map((e=>{const{To_Account:t,Status:s,CustomStatus:n}=e;return{userID:t,statusType:s,customStatus:Ah(n)}}));this._emitUserStatusUpdatedEvent(s)}_onReOnline(e){const t=Ah(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const s={userID:rn(),statusType:_h,customStatus:t};this._emitUserStatusUpdatedEvent(s)}_emitUserStatusUpdatedEvent(e){Vt.notificationCenter.emitOuterEvent(Wt.USER_STATUS_UPDATED,{name:Wt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){const{ErrorList:t=[]}=e;return t.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:Vt.utils.isEmpty(s)?t:s,code:n,message:o}}))}_checkBusinessCapabilityBits(e){if(!Vt.store.get("commercialConfig").get(ph))throw new Fs({functionName:e,code:ps.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=Vt.store.get("cloudConfig")||{},s={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:hh},unsubscribe:{key:"status_unsub_count",default:hh}},{key:n,default:o}=s[e],i=t[n]||o;return parseInt(i,10)}_getMyStatus(){const e=Vt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:rn(),statusType:_h,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return g(this,void 0,void 0,(function*(){const t=Vt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const s=this._getMaxUserCount("query"),n=this._sliceUserIDList(e,s),o=yield Dh(n),{successUserList:i,failureUserList:r}=o||{};return t.end(),{code:0,data:{successUserList:i,failureUserList:r}}}catch(e){const{errorCode:s}=e,n=new Fs({functionName:"getUserStatus",code:s});throw t.setError(n).end(),n}}))}_isOnlyMeInArray(e){const t=rn();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const Lh={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}},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}}},Nh={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Ph{constructor(){this.userProfile=new Mh,this.userStatus=new bh,this.userProfile.init(),this.userStatus.init(),Ws({auth:Nh,params:Lh})}}function Gh(e){const t=[];if(!_(e))return t;const s=e.length;if(0===s)return t;for(let n=s-1;n>=0;n--)"1"===e[n]&&t.push(2**(s-n-1));return t}var wh,Uh,kh;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(wh||(wh={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(Uh||(Uh={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(kh||(kh={}));class Fh{constructor(){this._name="SyncConversationHandler",this._pagingStatus=wh.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:e}=Vt;zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,vs.CONVERSATION_RECOVER,this._syncConversationList,this),zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_LOGIN,vs.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(zt.LOGOUT,this._reset,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this),console.log(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===wh.RESOLVED}_syncConversationListAfterLogin(){return g(this,void 0,void 0,(function*(){return this._pagingStatus=wh.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()}))}_syncConversationList(){return g(this,void 0,void 0,(function*(){const{ssoLog:e}=Vt,t=e.createSSOLogData({method:"syncConversationList"});try{const e=yield this._pagingGetConversationList(!0);this._pagingStatus=wh.RESOLVED;const{conversationList:s=[]}=e||{};return t.setLogInfo({message:`count:${s.length}`}).end(),console.log(`${this._name}._syncConversationList ok, count:${s.length}`),e}catch(e){const{errorCode:s,errorInfo:n}=e,o=new Fs({functionName:"syncConversationList",code:s,message:n});t.setError(o).end(),console.error(`${this._name}._syncConversationList fail:`,o)}}))}_pagingGetConversationList(e){return g(this,void 0,void 0,(function*(){try{const t=[];this._pagingStatus=wh.PENDING;const s=yield function(e){return g(this,void 0,void 0,(function*(){const{fromAccount:t,pagingTimeStamp:s,pagingStartIndex:n,pagingPinnedTimeStamp:o,pagingPinnedStartIndex:i}=e;return tn({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:t,StartIndex:n,TimeStamp:s,TopStartIndex:i,TopTimeStamp:o}})}))}({fromAccount:rn(),pagingTimeStamp:e?this._pagingTimeStamp:0,pagingStartIndex:e?this._pagingStartIndex:0,pagingPinnedTimeStamp:e?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:e?this._pagingPinnedStartIndex:0}),{CompleteFlag:n,SessionItem:o=[],TimeStamp:i,StartIndex:r,TopTimeStamp:a,TopStartIndex:c}=s||{};if(o.length>0){const e=this._getConversationOptions(o);t.push(...e);const{notificationCenter:s}=Vt;s.emitInnerEvent(zt.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}if(this._pagingTimeStamp=i,this._pagingStartIndex=r,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=c,1!==n){const{conversationList:s}=yield this._pagingGetConversationList(e);t.push(...s)}return{conversationList:t}}catch(e){throw console.error(`${this._name}._pagingGetConversationList fail:`,e),e}}))}_getConversationOptions(e){const{utils:{isUndefined:t}}=Vt,s=this._convertConversationKey(e);return this._filterValidConversations(s).map((e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===Uh.C2C?this._assembleC2COption(e):this._assembleGroupOption(e))))}_filterValidConversations(e){return e.filter((({type:e,userID:t})=>e===Uh.C2C&&!function(e){let t;return e.startsWith(gs.CONV_C2C)&&(t=e.replace(gs.CONV_C2C,"")),"@TLS#ERROR"===t||"@TLS#NOT_FOUND"===t}(t)||2===e))}_assembleC2COption(e){var t,s,n,o,i,r;const a=this._createUserprofile(e);return{conversationID:`${gs.CONV_C2C}${e.userID}`,type:gs.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(t=e.lastMsg)||void 0===t?void 0:t.elements[0])?null===(s=e.lastMsg)||void 0===s?void 0:s.elements[0].type:null,payload:(null===(n=e.lastMsg)||void 0===n?void 0:n.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(o=e.lastMsg)||void 0===o?void 0:o.cloudCustomData)||"",isRevoked:e.lastMessageFlag===kh.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null===(r=null===(i=e.lastMsg)||void 0===i?void 0:i.revokerInfo)||void 0===r?void 0:r.revoker)||null},unreadCount:0,userProfile:a,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:Gh(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t;const{userID:s,nick:n,peerAvatar:o}=e,i=[{tag:"Tag_Profile_IM_Nick",value:n},{tag:"Tag_Profile_IM_Image",value:o}];return null===(t=Vt.user.userProfile)||void 0===t?void 0:t.createProfile(s,i)}_computeIsPeerRead(e){const t=rn(),{lastC2CMsgFromAccount:s,time:n,c2cPeerReadTime:o}=e;return s===t&&n<=o}_assembleGroupOption(e){var t,s,n;return{conversationID:`${gs.CONV_GROUP}${e.groupID}`,type:gs.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?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===kh.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(n=null===(s=e.lastMsg)||void 0===s?void 0:s.revokerInfo)||void 0===n?void 0:n.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:Gh(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.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount})))}_convertLastMsgKey(e){var t,s;const{utils:{isEmpty:n}}=Vt;if(n(e))return null;let o="",i=null;return e.MsgBody&&(o=null===(t=e.MsgBody[0])||void 0===t?void 0:t.MsgType,i=this._parseContent(o,e.MsgBody[0])),{event:e.Event,elements:[{type:o,content:i,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(s=e.RevokerInfo)||void 0===s?void 0:s.revoker}}}_parseContent(e,t){var s;if(!t)return t;const n=Vt.message.messageFactory.getElementClass(e);return n?null===(s=n.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return h(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=gs.MSG_REMIND_ACPT_AND_NOTE:1===e?t=gs.MSG_REMIND_DISCARD:2===e?t=gs.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=gs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){const{utils:{isUndefined:t}}=Vt,{event:s,elements:n=[]}=e.lastMsg||{};return t(s)?{type:n[0]?n[0].type:null,payload:n[0]?this._amendLayersOverLimitProp(n[0].content):null}:{type:gs.MSG_GRP_TIP,payload:{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,n=t-s;return n>0?n:0}_reset(){this._pagingStatus=wh.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}}class $h{constructor(){this.syncConversationHandler=new Fh,this.syncConversationHandler.init()}}return console.log(`TencentCloudLiteChat.VERSION:${We}`),{create:function(e){var t,s;const{SDKAppID:n,testEnv:o=!1,devMode:i=!1,unlimitedAVChatRoom:r=!1,scene:a="",oversea:c=!1,instance:u}=e;let l=n;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(l))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(l=Number(l),Js.has(l))return Js.get(l);let d=null;if(u)d=u,d._workflowManager&&zs.setInstance(d._workflowManager),d._pluginManager&&d._pluginManager.installBuiltInPlugin(Jl),u.isReady()&&(null===(s=(t=zs.getInstance()).executeWorkflow)||void 0===s||s.call(t,ms.SYNC_SERVER_INFO_AFTER_LOGIN));else{const e=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();Vt.init({sdkAppId:l,instanceId:e,testEnv:o,devMode:i,unlimitedAVChatRoom:r,scene:a,oversea:c,sdkEdition:zl}),zs.getInstance().init(),Vt.message=new uh,Vt.user=new Ph,Vt.login=new cd,Vt.conversation=new $h,Xl.getInstance().installBuiltInPlugin(Jl),d=od.getInstance().exposeApiForClient(),d._workflowManager=zs.getInstance(),d._pluginManager=Xl.getInstance()}return Js.set(l,d),d},TSignaling:Jt,EVENT:Wt,VERSION:We,TYPES:gs}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChat=t()}(this,function(){class w{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,n){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!n||e.context===n;return!(t&&e)}))}emit(e,...s){e=this.listeners[e];e&&e.forEach(e=>{var{fn:e,context:t}=e;e.apply(t,s)})}once(t,s,n){let r=(...e)=>{s.apply(n,e),this.off(t,r)};this.on(t,r)}}let G={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},U=["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 q;(e=q=q||{})[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";var n,x,V,e=Object.freeze({__proto__:null,get ConvModifyPushType(){return q},ENUM_PLATFORM:G,IS_TOPIC_MESSAGE:2,NOT_NEED_CRC_SERVCMD:U});function B(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{2===e.GroupInfo.MillionGroupFlag?s.push(n.TOPIC_TIPS_NOTIFICATION):s.push(n.GROUP_TIPS_NOTIFICATION)}),s}(t=n=n||{}).BUSINESS_COMMAND="business_command",t.C2C_REALTIME_MESSAGE="c2c_realtime_message",t.C2C_MESSAGE_MODIFIED="c2c_message_modified",t.C2C_REVOKED_MESSAGE="c2c_message_revoked",t.GROUP_REALTIME_MESSAGE="group_realtime_message",t.GROUP_MESSAGE_MODIFIED="group_message_modified",t.GROUP_MESSAGE_REVOKED="group_message_revoked",t.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",t.MESSAGE_REACTION_UPDATED="message_reaction_updated",t.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",t.GROUP_AT_TIPS="group_at_tips",t.USER_STATUS_UPDATE="user_status_update",t.FRIEND_LIST_MODIFIED="friend_list_modified",t.PROFILE_MODIFIED="profile_modified",t.CONV_MODIFIED="conversation_modified",t.GROUP_TIPS_NOTIFICATION="group_tips_notification",t.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",t.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",t.GROUP_SYSTEM_NOTIFICATION="group_system_notification",t.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",t.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",t.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",t.FOLLOW_LIST_UPDATED="follow_list_updated",t.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",t.ALL_MESSAGE_READ="all_message_read",t.CONVERSATION_MARK_UPDATED="conversation_mark_updated",t.CONVERSATION_GROUP_ADD="conversation_group_add",t.CONVERSATION_GROUP_DELETED="conversation_group_deleted",t.CONVERSATION_GROUP_UPDATED="conversation_group_updated",t.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",t.TOPIC_AT_TIPS="topic_at_tips",t.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",t.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",t.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",t.TOPIC_LATEST_MESSAGE="topic_latest_message";let j=[{conditions:[{type:"event",value:100}],subType:n.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:n.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:n.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:n.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:n.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:n.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:n.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:n.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:n.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:n.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(n.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(n.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(n.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(n.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:B},{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(n.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(n.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(n.TOPIC_MESSAGE_READ_SYNC):s.push(n.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(n.TOPIC_SYSTEM_NOTIFICATION):s.push(n.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:B},{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(n.TOPIC_AT_TIPS):s.push(n.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 q.CONV_MARK_UPDATED:s.push(n.CONVERSATION_MARK_UPDATED);break;case q.CONV_GROUP_ADDED:s.push(n.CONVERSATION_GROUP_ADD);break;case q.CONV_GROUP_DELETED:s.push(n.CONVERSATION_GROUP_DELETED);break;case q.CONV_GROUP_UPDATED:s.push(n.CONVERSATION_GROUP_UPDATED);break;default:s.push(n.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:n.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:n.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:n.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:n.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:n.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:n.ALL_MESSAGE_READ}];function K(n){let e,t=Array.isArray(null==(e=null==n?void 0:n.body)?void 0:e.EventArray)?n.body.EventArray:[],r=[];return t.forEach(t=>{t.Flag=n.body.Flag;var e=j.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=>{r.push({type:x.SERVER_PUSH_MESSAGE+":"+e,data:t})}):r.push({type:x.SERVER_PUSH_MESSAGE+":"+s,data:t})}),r}(t=x=x||{}).SERVER_PUSH_MESSAGE="im_open_push.msg_push",t.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",t.ERROR="error";let H={[x.SERVER_PUSH_MESSAGE]:K,[x.SERVER_PUSH_MESSAGE_MULTIPLE]:K,[x.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},W=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new w,this._innerEventEmitter=new w,this.InnerEventSubType=n}subscribeInnerEvent(s,n,r,i){var o,t;if(["string","number"].includes(typeof n)){let e=n,t=r;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,i)}else{let e=n;null!=(t=this._innerEventEmitter)&&t.on(s,e,r)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(H).includes(t)){let e=null==(t=H[t])?void 0:t.call(H,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,n,r,i){var o,t;if(["string","number"].includes(typeof n)){let e=n,t=r;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,i)}else{let e=n;null!=(t=this._innerEventEmitter)&&t.off(s,e,r)}}subscribeOuterEvent(e,t,s){var n;null!=(n=this._outerEventEmitter)&&n.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var n;null!=(n=this._outerEventEmitter)&&n.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}};function I(e,t){var s={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(s[r[n]]=e[r[n]]);return s}function S(e,o,a,l){return new(a=a||Promise)(function(s,t){function n(e){try{i(l.next(e))}catch(e){t(e)}}function r(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(n,r)}i((l=l.apply(e,o||[])).next())})}let $=e=>void 0===e,Y=e=>"string"==typeof e,z=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[1].toLowerCase()},J=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===z(e),Q=e=>null!==e&&"object"==typeof e,X=e=>J(e)||Q(e),Z=e=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},ee=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 te(e=99999999){return Math.round(Math.random()*e)}let se=(s,n,r,i)=>{if(!X(s)||!X(n))return 0;let o=0;var a,l=Object.keys(n);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!($(n[a])||r&&r.includes(a)))if(X(s[a])&&X(n[a]))o+=se(s[a],n[a],r,i);else{if(i&&i.includes(n[a]))continue;s[a]!==n[a]&&(s[a]=n[a],o+=1)}return o};function ne(s){let n,r,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)n=parseInt(i.slice(e,e+4),2),r=parseInt(i.slice(e+4,e+8),2),o+=base16Map.get(n)+base16Map.get(r);return o}let re="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),ie="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||re,oe=ie&&"function"==typeof wx.createGamePortal,ae="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),le="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),ue="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),ce="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),de="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,he="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,ge=ie&&"object"==typeof wx.miniapp,pe="undefined"!=typeof uni,_e=ie||ae||le||ue||ce||he||de,me="undefined"==typeof window&&!_e&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,ve="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),fe="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),Ie="undefined"!=typeof uni?!_e:"undefined"!=typeof window&&!_e&&!ve,Se=ae?qq:le?tt:ue?swan:ce?my:ie?wx:he?uni:de?jd:{},s=Ie&&window&&window.navigator&&window.navigator.userAgent||"",Ee=/(micromessenger|webbrowser)/i.test(s),Ce=function(){let e="WEB";return Ee?e="WEB":ae?e="QQ_MP":le?e="TT_MP":ue?e="BAIDU_MP":ce?e="ALI_MP":ie?e=ge?"DONUT_NATIVE_APP":"WX_MP":he?e="UNI_NATIVE_APP":me?e="NS_NATIVE_APP":ve&&(e="RN_NATIVE_APP"),G[e]}(),Me=/iPad/i.test(s),ye=/iPhone/i.test(s)&&!Me,Oe=/iPod/i.test(s),Ae=ye||Me||Oe,Te=(t=s.match(/OS (\d+)_/i))&&t[1]?t[1]:null,Re=/Android/i.test(s),De=(t=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i))?(Qe=t[1]&&parseFloat(t[1]),V=t[2]&&parseFloat(t[2]),Qe&&V?parseFloat(t[1]+"."+t[2]):Qe||null):null,Le=/Firefox/i.test(s),Ne=/Edge/i.test(s),be=!Ne&&/Chrome/i.test(s),Pe=/MSIE/.test(s)||-1<s.indexOf("Trident")&&-1<s.indexOf("rv:11.0"),we=function(){var e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)?11:t}(),Ge=/Safari/i.test(s)&&!be&&!Re&&!Ne,Ue=/Windows/i.test(s),ke=/MAC OS X/i.test(s),Fe=Ie&&"undefined"!=typeof Worker&&!Pe,qe=Re||Ae,xe=Ie&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,Ve="undefined"!=typeof window&&void 0!==window.navigator&&(V=window.navigator["standalone"],!(!Ae||V||Ge));function Be(){let e="unknown";if(ke&&(e="mac"),Ue&&(e="windows"),Ae&&(e="ios"),Re&&(e="android"),_e)try{var t=Se.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}let je="application/x-www-form-urlencoded;charset=UTF-8";function Ke(e){return S(this,arguments,void 0,function*({method:r,url:i,data:o,timeout:a=3e3}){return new Promise(_e?(t,e)=>{Se.request({url:i,data:o,method:r,timeout:a,header:{"content-type":je},success:e=>t(e.data),fail:()=>e(new Error('{"message":"Network error","code":2800}'))})}:(t,e)=>{let s=new XMLHttpRequest,n=setTimeout(()=>{s.abort(),e(new Error('{"message":"Request timeout","code":2801}'))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(n),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":2800}'))},s.open(r,i,!0),s.setRequestHeader("Content-type",je),s.send(o||null)})})}function He(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(ee(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 We(n){if(null===n||"object"!=typeof n)return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(n instanceof Map){let s=new Map;return n.forEach((e,t)=>{s.set(We(t),We(e))}),s}if(n instanceof Set){let t=new Set;return n.forEach(e=>{t.add(We(e))}),t}if(Array.isArray(n))return n.map(e=>We(e));let e=Object.getPrototypeOf(n),s=Object.create(e);return[...Object.getOwnPropertyNames(n),...Object.getOwnPropertySymbols(n)].forEach(e=>{var t=Object.getOwnPropertyDescriptor(n,e);t&&(t.get||t.set?Object.defineProperty(s,e,t):s[e]=We(n[e]))}),s}function $e(){let s,n;return{promise:new Promise((e,t)=>{s=e,n=t}),resolve:s,reject:n}}var t=Object.freeze({__proto__:null,ANDROID_VERSION:De,IE_VERSION:we,IN_ALIPAY_MINI_APP:ce,IN_BAIDU_MINI_APP:ue,IN_BROWSER:Ie,IN_DONUT_NATIVE_APP:ge,IN_JD_MINI_APP:de,IN_MINI_APP:_e,IN_NS_NATIVE_APP:me,IN_QQ_MINI_APP:ae,IN_RN_APP:ve,IN_TT_MINI_APP:le,IN_UNI_APP:pe,IN_UNI_NATIVE_APP:he,IN_WX_MINI_APP:ie,IN_WX_MINI_APP_DESK:re,IN_WX_MINI_GAME:oe,IN_WX_MINI_PLUGIN:fe,IOS_VERSION:Te,IS_ANDROID:Re,IS_CHROME:be,IS_EDGE:Ne,IS_FIREFOX:Le,IS_IE:Pe,IS_IOS:Ae,IS_IPAD:Me,IS_IPHONE:ye,IS_IPOD:Oe,IS_MAC:ke,IS_SAFARI:Ge,IS_WECHAT:Ee,IS_WIN:Ue,IS_WORKER_AVAILABLE:Fe,MINI_APP_NAMESPACE:Se,USER_AGENT:s,base16EncodeBinaryString:ne,deepCopyWithMethods:We,deepMerge:se,generatePromise:$e,getPlatformType:Be,getType:z,httpRequest:Ke,isArray:J,isArrayOrObject:X,isEmpty:He,isFlutterWeb:xe,isH5:qe,isIOSWebView:Ve,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:Q,isPlainObject:ee,isString:Y,isUndefined:$,isValidRequestKey:Z,platform:Ce,randomInt:te,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t}});class Ye{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:n,onSendFail:r}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=n,this._onSendFail=r)}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 ze{connectSocket(e){return this._socket=Se.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:n,onSendFail:r}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(n),this._onSendFail=r}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Je{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:"CONNECT",url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:"SEND",data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:n,onClose:r,onError:i,onSendFail:o}=e;if(this._worker){let s={OPEN:t,MESSAGE:n,CLOSE:r,ERROR:i,SEND_FAIL: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:"DISCONNECT"}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var r,Qe,c=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return _e?ce?my.getStorageSync({key:e}).data:Se.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){_e?ce?my.setStorageSync({key:e,data:JSON.stringify(t)}):Se.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}};(Qe=r=r||{})[Qe.CONNECTED=0]="CONNECTED",Qe[Qe.CONNECTING=1]="CONNECTING",Qe[Qe.DISCONNECTED=2]="DISCONNECTED";class Xe{constructor(e){this._url="",this._readyState=r.DISCONNECTED,this._url=e,this._id=te(),this._emitter=new w,ie||he?this._socket=new ze:this._canUseWebWorker()?this._socket=new Je:this._socket=new Ye,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[r.CONNECTED,r.CONNECTING].includes(this._readyState)||(this._readyState=r.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==r.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[r.CONNECTED,r.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===r.CONNECTED}disconnect(){this._readyState=r.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===r.CONNECTING&&(this._readyState=r.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=r.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=r.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=r.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 e=c.get("cloudConfig")||{};return($(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&Fe}}let Ze={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"}}},et={SINGAPORE:[[2e7,3e7],[172e7,173e7]],KOREA:[[3e7,4e7],[173e7,174e7]],GERMANY:[[4e7,5e7],[174e7,175e7]],IND:[[5e7,6e7],[175e7,176e7]],JPN:[[6e7,7e7],[176e7,177e7]],USA:[[7e7,8e7],[177e7,178e7]],INDONESIA:[[8e7,9e7],[178e7,179e7]]};function st(t){var e;if(null!=(e=c.get("instance"))&&e.oversea)return"OVERSEA";for(let e of Object.keys(et))for(var[s,n]of et[e])if(t>=s&&t<n)return e;return"CHINA"}var a,nt="1.5.1";(i=a=a||{}).INITIAL="INITIAL",i.DEFAULT="DEFAULT",i.BACKUP="BACKUP",i.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",i.BACKUP_CN="BACKUP_CN",i.ANYCAST="ANYCAST",i.IPV6="IPV6";let rt=a.INITIAL;function it(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:n,instanceId:r}=c.get("instance"),i=function e(){var t=Math.random();return 0===t?e():t}(),o=Be(),a=function(){var e=Be();let t=-1;return"ios"===e?t=Te||-1:"android"===e&&(t=De||-1),t}(),n=(s={sdkappid:n,instanceid:r,random:i,platform:Ce,host:o,version:a,sdkversion:nt},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${n}&compress=gzip`:e+"/info?"+n}function ot(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),t=st(t);if(s)return it(Ze.TEST[t].DEFAULT,{isBinary:e});let n=Ze.PRODUCTION[t],r=Ie&&n.ANYCAST,i=Ie,o=!!n.BACKUP_CN;return it({[a.INITIAL]:()=>(rt=a.DEFAULT,n.DEFAULT),[a.DEFAULT]:()=>(rt=a.IPV6,n.IPV6),[a.IPV6]:()=>(rt=a.BACKUP,n.BACKUP),[a.BACKUP]:()=>{return i?(rt=a.BACKUP_WEB_ONLY,e=n.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):o?(rt=a.BACKUP_CN,n.BACKUP_CN):r?(rt=a.ANYCAST,n.ANYCAST):n.DEFAULT;var e,t},[a.BACKUP_WEB_ONLY]:()=>o?(rt=a.BACKUP_CN,n.BACKUP_CN):r?(rt=a.ANYCAST,n.ANYCAST):n.DEFAULT,[a.BACKUP_CN]:()=>(rt=r?a.ANYCAST:a.DEFAULT,n[rt]),[a.ANYCAST]:()=>(rt=a.DEFAULT,n.ANYCAST="",n.DEFAULT)}[rt](),{isBinary:e})}var at=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}};var lt=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:n=!1,intervalMs:r=16}=e,i=Math.max(r,16);return{id:e,nextExecuteTime:Date.now()+i,intervalMs:r,callback:t,context:s,isOnce:n}}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 ut(t){var s=[];for(let e=0;e<t.length;e+=1){var n,r=t.charCodeAt(e);55296<=r&&r<=56319?(n=t.charCodeAt(++e)-56320+(r-55296<<10)+65536,s.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)):r<=127?s.push(r):r<=2047?s.push(192|r>>6,128|63&r):s.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(s)}function ct(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&Z(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=ct(e[t]));return s}function dt(e,t){if(U.includes(e))return 0;var s=ut(JSON.stringify(t));let n=4294967295;var r=s["length"];for(let e=0;e<r;e++){n^=s[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return(4294967295^n)>>>0}function ht(e){var t,{servcmd:e,data:s}=e,n=(n=e,t=c.get("login")||{},r=c.get("instance")||{},{servcmd:n,ver:"v4",platform:Ce,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:r.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:ne(""),cappid:t.cappid||0,tjgID:"",seq:_t(),cs:0}),r=ct(s);return n.cs=dt(e,r),{head:n,body:r}}function gt(e){var t,{servcmd:e,data:s}=e,n=(n=e,t=c.get("login")||{},r=c.get("instance")||{},{servcmd:n,ver:"v4",platform:Ce,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:r.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:ne(""),cappid:t.cappid||0,seq:_t(),cs:0}),r=ct(s);return n.cs=dt(e,r),{head:n,body:r}}let pt=te();function _t(){return pt=pt<2415919103?pt+1:te()}function mt(){var e=c.get("login")||{},t=c.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.5.1",tiny_id:Number(e.tinyID),user_id:e.userId,platform:Ce,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var vt,i=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,n=(n=e,t=c.get("login")||{},r=c.get("instance")||{},{servcmd:n,ver:"v4",platform:Ce,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:r.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:ne(""),cappid:t.cappid||0,seq:_t(),cs:0}),r=ct(s);return n.cs=dt(e,r),{head:n,body:r}},generateProtocolData:ht,generateSSOLogProtocolData:gt,generateSequence:_t,getCommonHead:mt,taskScheduler:lt,timeManager:at});(m=vt=vt||{})[m.info=4]="info",m[m.warning=5]="warning",m[m.error=6]="error";let ft={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 It{constructor(e){this.level=vt.info,this._canSendLog=!0,this._logCreatedAt=at.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=void 0;var{method:e,eventType:t=0,uiPlatform:s,message:n}=e||{};this.eventType=t,this.method=e,this.uiPlatform=s,this.message=n||""}setMoreMessage(e){this.moreMessage=this.moreMessage+" "+e}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=at.getTimeOffsetWithServer()}end(e=!1){var t;this._canSendLog&&(t=at.getServerTimeMs(),0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:`+t),e?(this._canSendLog=!1,this.timestamp=at.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout(()=>{this._canSendLog=!1,this.timestamp=at.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())},0))}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=c.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=vt.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(ft).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{ft[e]&&(t[ft[e]]=this[e])}),t}}(m=N=N||{}).RECONNECTED="reconnected",m.CLOUD_CONFIG_UPDATE="cloud_config_update",m.SOCKET_DISCONNECTED="socket_disconnected";var St=N;let Et=[4,5,6],Ct=[],Mt=[],yt="report-logger";var Ot=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,W.subscribeInnerEvent(St.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),lt.addTask({id:yt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=20,evt_rpt_waiting:t=6e4,evt_rpt_level:s=Et,evt_rpt_sdkappid_bl:n=Ct,evt_rpt_tinyid_wl:r=Mt}=e||{};this._sdkAppIdBlackList=n,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=r}createSSOLogData(e){var t=new It(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()}_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 S(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||He((t={Header:mt(),Event:t}).Header.user_id)||(e=(t=gt({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void wt.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(ie){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;c.set("instance",{appId:e,envVersion:t})}}else Ie&&c.set("instance",{href:window.location.href})}_filterLogs(e){var t=(c.get("login")||{})["tinyID"],s=(c.get("instance")||{})["sdkAppId"];return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}reset(){console.log("SSO_LOG_MODULE.reset"),lt.removeTask(yt),W.unSubscribeInnerEvent(St.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._logQueue=[]}};let l="Channel",At="channel_schedule_task",Tt="channel_reconnect_task",Rt="connected",Dt="disconnected",Lt="network_status_change";function Nt(e){return(Nt="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 bt(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 Pt=function s(n,r,i){function o(t,e){if(!r[t]){if(!n[t]){if(!e&&bt)return bt(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=r[t]={exports:{}};n[t][0].call(e.exports,function(e){return o(n[t][1][e]||e)},e,e.exports,s,n,r,i)}return r[t].exports}for(var a=bt,e=0;e<i.length;e++)o(i[e]);return o}({1:[function(e,t,s){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,r=(s.assign=function(e){for(var t,s,n=Array.prototype.slice.call(arguments,1);n.length;){var r=n.shift();if(r){if("object"!=Nt(r))throw new TypeError(r+"must be non-object");for(var i in r)t=r,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=r[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,n,r){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+n),r);else for(var i=0;i<n;i++)e[r+i]=t[s+i]},flattenChunks:function(e){for(var t,s,n,r,i=t=0,o=e.length;i<o;i++)t+=e[i].length;for(r=new Uint8Array(t),i=s=0,o=e.length;i<o;i++)n=e[i],r.set(n,s),s+=n.length;return r}}),i={arraySet:function(e,t,s,n,r){for(var i=0;i<n;i++)e[r+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,r)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(n)},{}],2:[function(e,t,s){var l=e("./common"),r=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var u=new l.Buf8(256),n=0;n<256;n++)u[n]=252<=n?6:248<=n?5:240<=n?4:224<=n?3:192<=n?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&r))return String.fromCharCode.apply(null,l.shrinkBuf(e,t));for(var s="",n=0;n<t;n++)s+=String.fromCharCode(e[n]);return s}u[254]=u[254]=1,s.string2buf=function(e){for(var t,s,n,r,i=e.length,o=0,a=0;a<i;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<i&&56320==(64512&(n=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(n-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new l.Buf8(o),a=r=0;r<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<i&&56320==(64512&(n=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(n-56320),a++),s<128?t[r++]=s:(s<2048?t[r++]=192|s>>>6:(s<65536?t[r++]=224|s>>>12:(t[r++]=240|s>>>18,t[r++]=128|s>>>12&63),t[r++]=128|s>>>6&63),t[r++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new l.Buf8(e.length),s=0,n=t.length;s<n;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,n,r,i=t||e.length,o=new Array(2*i),a=s=0;a<i;)if((n=e[a++])<128)o[s++]=n;else if(4<(r=u[n]))o[s++]=65533,a+=r-1;else{for(n&=2===r?31:3===r?15:7;1<r&&a<i;)n=n<<6|63&e[a++],r--;1<r?o[s++]=65533:n<65536?o[s++]=n:(n-=65536,o[s++]=55296|n>>10&1023,o[s++]=56320|1023&n)}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":1}],3:[function(e,t,s){t.exports=function(e,t,s,n){for(var r=65535&e,i=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;i=i+(r=r+t[n++]|0)|0,--o;);r%=65521,i%=65521}return r|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,n=0;n<8;n++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,n){var r=a,i=n+s;e^=-1;for(var o=n;o<i;o++)e=e>>>8^r[255&(e^t[o])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,n,r,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,S=l.window,E=l.hold,C=l.bits,M=l.lencode,y=l.distcode,O=(1<<l.lenbits)-1,A=(1<<l.distbits)-1;e:do{for(C<15&&(E+=c[u++]<<C,C+=8,E+=c[u++]<<C,C+=8),s=M[E&O];;){if(E>>>=n=s>>>24,C-=n,0==(n=s>>>16&255))g[h++]=65535&s;else{if(!(16&n)){if(!(64&n)){s=M[(65535&s)+(E&(1<<n)-1)];continue}if(32&n){l.mode=12;break e}e.msg="invalid literal/length code",l.mode=30;break e}for(r=65535&s,(n&=15)&&(C<n&&(E+=c[u++]<<C,C+=8),r+=E&(1<<n)-1,E>>>=n,C-=n),C<15&&(E+=c[u++]<<C,C+=8,E+=c[u++]<<C,C+=8),s=y[E&A];;){if(E>>>=n=s>>>24,C-=n,!(16&(n=s>>>16&255))){if(!(64&n)){s=y[(65535&s)+(E&(1<<n)-1)];continue}e.msg="invalid distance code",l.mode=30;break e}if(i=65535&s,C<(n&=15)&&(E+=c[u++]<<C,(C+=8)<n)&&(E+=c[u++]<<C,C+=8),m<(i+=E&(1<<n)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(E>>>=n,C-=n,(n=h-p)<i){if(f<(n=i-n)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=S,(o=0)===I){if(o+=v-n,n<r){for(r-=n;g[h++]=S[o++],--n;);o=h-i,a=g}}else if(I<n){if(o+=v+I-n,(n-=I)<r){for(r-=n;g[h++]=S[o++],--n;);if(o=0,I<r){for(r-=n=I;g[h++]=S[o++],--n;);o=h-i,a=g}}}else if(o+=I-n,n<r){for(r-=n;g[h++]=S[o++],--n;);o=h-i,a=g}for(;2<r;)g[h++]=a[o++],g[h++]=a[o++],g[h++]=a[o++],r-=3;r&&(g[h++]=a[o++],1<r)&&(g[h++]=a[o++])}else{for(o=h-i;g[h++]=g[o++],g[h++]=g[o++],g[h++]=g[o++],2<(r-=3););r&&(g[h++]=g[o++],1<r)&&(g[h++]=g[o++])}break}}break}}while(u<d&&h<_);u-=r=C>>3,E&=(1<<(C-=r<<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"),b=e("./adler32"),P=e("./crc32"),w=e("./inffast"),G=e("./inftrees"),U=0,k=-2,F=1,n=852,r=592;function q(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(n),t.distcode=t.distdyn=new N.Buf32(r),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,n;return!e||!e.state||(n=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t))?k:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=s,n.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 x,V,B=!0;function j(e,t,s,n){var r,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)),n>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(n<(r=e.wsize-e.wnext)&&(r=n),N.arraySet(e.window,t,s-n,r,e.wnext),(n-=r)?(N.arraySet(e.window,t,s-n,n,0),e.wnext=n,e.whave=e.wsize):(e.wnext+=r,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=r))),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,n,r,i,o,a,l,u,c,d,h,g,p,_,m,v,f,I,S,E,C,M,y,O,A=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,r=e.output,l=e.avail_out,i=e.next_in,n=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+=n[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+=n[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+=n[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+=n[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+=n[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,n,i,g,C)),512&s.flags&&(s.check=P(s.check,n,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=n[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,n,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=n[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,n,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+=n[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+=n[i++]<<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=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+=n[i++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:D=L=void 0;var D,L=s;if(B){for(x=new N.Buf32(512),V=new N.Buf32(32),D=0;D<144;)L.lens[D++]=8;for(;D<256;)L.lens[D++]=9;for(;D<280;)L.lens[D++]=7;for(;D<288;)L.lens[D++]=8;for(G(1,L.lens,0,288,x,0,L.work,{bits:9}),D=0;D<32;)L.lens[D++]=5;G(2,L.lens,0,32,V,0,L.work,{bits:5}),B=!1}if(L.lencode=x,L.lenbits=9,L.distcode=V,L.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+=n[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(r,n,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+=n[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+=n[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=G(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=(A=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}if(f<16)u>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(O=m+2;c<O;){if(0===a)break e;a--,u+=n[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(O=m+3;c<O;){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}C=0,g=3+(7&(u>>>=m)),u>>>=3,c=c-m-3}else{for(O=m+7;c<O;){if(0===a)break e;a--,u+=n[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=G(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=G(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,w(e,h),o=e.next_out,r=e.output,l=e.avail_out,i=e.next_in,n=e.input,a=e.avail_in,u=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(A=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}if(v&&!(240&v)){for(I=m,S=v,E=f;v=(A=s.lencode[E+((u&(1<<I+S)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[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(O=s.extra;c<O;){if(0===a)break e;a--,u+=n[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=(A=s.distcode[u&(1<<s.distbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}if(!(240&v)){for(I=m,S=v,E=f;v=(A=s.distcode[E+((u&(1<<I+S)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[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(O=s.extra;c<O;){if(0===a)break e;a--,u+=n[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 _=r,p=o-s.offset,g=s.length;for(l-=g=l<g?l:g,s.length-=g;r[o++]=_[p++],--g;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;r[o++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,u|=n[i++]<<c,c+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?P:b)(s.check,r,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+=n[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:b)(s.check,r,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,n=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&b(1,t,n,0)!==s.check?-3:j(e,t,n,n)?(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 w=e("../utils/common"),G=[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,n,r,i,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,O=0,A=0,T=0,R=null,D=0,L=new w.Buf16(16),N=new w.Buf16(16),b=null,P=0,f=0;f<=15;f++)L[f]=0;for(I=0;I<n;I++)L[t[s+I]]++;for(C=v,E=15;1<=E&&0===L[E];E--);if(E<C&&(C=E),0===E)r[i++]=20971520,r[i++]=20971520,a.bits=1;else{for(S=1;S<E&&0===L[S];S++);for(C<S&&(C=S),f=O=1;f<=15;f++)if((O=(O<<1)-L[f])<0)return-1;if(0<O&&(0===e||1!==E))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+L[f];for(I=0;I<n;I++)0!==t[s+I]&&(o[N[t[s+I]]++]=I);if(g=0===e?(R=b=o,19):1===e?(R=G,D-=257,b=U,P-=257,256):(R=k,b=F,-1),f=S,h=i,y=I=T=0,c=-1,d=(A=1<<(M=C))-1,1===e&&852<A||2===e&&592<A)return 1;for(;;){for(m=o[I]<g?(_=0,o[I]):o[I]>g?(_=b[P+o[I]],R[D+o[I]]):(_=96,0),l=1<<(p=f-y),S=u=1<<M;r[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==--L[f]){if(f===E)break;f=t[s+o[I]]}if(C<f&&(T&d)!==c){for(h+=S,O=1<<(M=f-(y=0===y?C:y));M+y<E&&!((O-=L[M+y])<=0);)M++,O<<=1;if(A+=1<<M,1===e&&852<A||2===e&&592<A)return 1;r[c=T&d]=C<<24|M<<16|h-i}}0!==T&&(r[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"),n=e("./zlib/messages"),r=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 r,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==p.Z_OK)throw new Error(n[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(n[e])}function a(e,t){t=new o(t);if(t.push(e,!0),t.err)throw t.msg||n[t.err];return t.result}o.prototype.push=function(e,t){var s,n,r,i,o,a=this.strm,l=this.options.chunkSize,u=this.options.dictionary,c=!1;if(this.ended)return!1;n=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||n!==p.Z_FINISH&&n!==p.Z_SYNC_FLUSH)||("string"===this.options.to?(r=g.utf8border(a.output,a.next_out),i=a.next_out-r,o=g.buf2string(a.output,r),a.next_out=i,a.avail_out=l-i,i&&h.arraySet(a.output,a.output,r,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(n=s===p.Z_STREAM_END?p.Z_FINISH:n)===p.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===p.Z_OK):n!==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"),wt=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=1e3,this._currentConnectState=Rt,this._beforeSendInterceptors=[]}init(){lt.addTask({id:At,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:n}=c.get("instance"),r=st(t);let i="";return s?i=Ze.TEST[r].DEFAULT:n?(i=Ze.PRODUCTION[r].DEFAULT,rt=a.DEFAULT):i=Ze.PRODUCTION[r].INITIAL.replace("*",""+t),it(i,{isBinary:e})}(this._isBinarySupported),W.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),W.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:n,timeout:r=15e3,canResend:i=!0}=t||{};if(He(e))return console.warn(l+".sendPacket: packet is empty ",e),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===Dt&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"send_fail"});var o=JSON.stringify(e);let a=null;if(n){let{resolve:e,reject:t,promise:s}=$e();a=s,this._pendingRequests.set(n,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:r,canResend:i})}t=this._isBinarySupported?ut(o).buffer:o;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new Xe(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),t=l+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t}),console.log(t)}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=l+".disconnect socketID:"+e;this._ssoLog({method:"disconnect",message:e}),console.log(e),this._removeEventListeners(),null!=(e=this._socketAdapter)&&e.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(l+".dispose"),lt.removeTask(At),lt.removeTask(Tt),W.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),W.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=1e3,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="connecting"===this._currentConnectState&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return S(this,void 0,void 0,function*(){var e=l+`.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=ot(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"reconnect_failed"}),console.warn(l+".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=l+`.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}),console.warn(s),e===this._connectionId&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_close"}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=l+`.onError sourceSocketID: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+JSON.stringify(t);this._ssoLog({method:"onError",message:t}),console.warn(t),e===this._connectionId&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_error"}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=l+`.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),console.warn(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=Pt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var r=new Uint8Array(e);let i="",o=0;for(var a=r["length"];o<a;){let t=r[o],s=0,n=0;if(t<=127?(s=0,n=255&t):t<=223?(s=1,n=31&t):t<=239?(s=2,n=15&t):t<=244&&(s=3,n=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=r[o+e+1],n=n<<6|63&t;else n=65533,s=a-o;i+=String.fromCodePoint(n),o+=s+1}return i})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return this._ssoLog({method:"jsonParseError",message:e}),void console.error(s)}var n;e&&e.head&&({seq:t,servcmd:n}=e.head,this._pendingRequests.has(""+t+n)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:n,str_error_message:r}=(null==e?void 0:e.body)||{},i=(null==(i=null==e?void 0:e.body)?void 0:i.ErrorCode)||n,n=(null==(n=null==e?void 0:e.body)?void 0:n.ErrorInfo)||r,r=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(r);this._pendingRequests.delete(r),i&&0!==i?(W.emitInnerEvent("error",{errorCode:i,errorInfo:n}),s({errorCode:i,errorInfo:n})):t(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:n}=e.body;1===s&&this._sendAck(n),W.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(l+`._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:n,resolve:r,reject:i,timeout:o}=e;if(n){this._pendingRequests.set(t,{resolve:r,reject:i,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:n});let e=this._isBinarySupported?ut(s).buffer:s;null!=(r=this._socketAdapter)&&r.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=l+`.onConnect cost:${s} ms. socketID:${e} res:`+JSON.stringify(t);if(this._ssoLog({method:"onConnect",message:s}),console.log(s),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){let e=l+".reconnect success";this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),W.emitInnerEvent(St.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=ht({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return S(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 S(this,void 0,void 0,function*(){var e,t=ht({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=c.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=l+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return S(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=he?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=l+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t),e);t&&"none"!==e?this._handleConnectStateChange({state:Rt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Lt}):this._handleConnectStateChange({state:Dt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Lt})}isPrivateNetWork(){var e=c.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:n}=e,n=l+`._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+n;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:n}),console.log(n),s&&(console.log(l+`._handleConnectStateChange from ${this._currentConnectState} to `+e),W.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===Dt)&&W.emitInnerEvent(St.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),lt.addTask({id:Tt,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=l+`.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),console.warn(e),3===t&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"activity_status_change"})}_resetReconnectDelay(){var e;console.log(l+"._resetReconnectDelay"),lt.removeTask(Tt),null!=(e=c.get("activityMonitor"))&&e.isActive;this._intendedDelay=1e3}_scheduleReconnectWithBackoff(){var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(1e3,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=l+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;this._ssoLog({method:"scheduleReconnectWithBackoff",message:e}),console.log(e),this.reconnect(),lt.updateTaskInterval(Tt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Ot.createSSOLogData({method:e}).setLogInfo({message:t}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){S(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 Ke({method:"GET",url:e,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}})}(this._url),function(t){S(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 Ke({method:"GET",url:e,data:{}})}catch(e){console.warn("diagnoseByCDN failed. error:",e)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(var[e,t]of this._pendingRequests.entries()){var{reject:t,timestamp:s,timeout:n}=t;Date.now()-s>=n&&(this._pendingRequests.delete(e),3e4<=Date.now()-this._lastDiagnoseAt&&this._diagnose(),t({errorCode:2801,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=c.get("instance"))&&e.devMode||(e=Be(),ce)||ie&&"windows"===e||he)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let k={init:function(e){c.set("instance",e),wt.init()},destroy:function(){wt.dispose(),c.clear(),lt.dispose()},notificationCenter:W,channel:wt,store:c,ssoLog:Ot,utils:t,common:i,constants:e},Gt=e=>"function"==typeof e;function Ut(t,s,n){let r=n||[];var e,i;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!r.includes(e)),i=Object.keys(s).filter(e=>!r.includes(e)),e.length===i.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?Ut(t[e],s[e],n):t[e]===s[e]))}(m=b=b||{}).SDK_READY="sdkStateReady",m.SDK_NOT_READY="sdkStateNotReady",m.SDK_DESTROY="sdkDestroy",m.MESSAGE_RECEIVED="onMessageReceived",m.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",m.MESSAGE_MODIFIED="onMessageModified",m.MESSAGE_REVOKED="onMessageRevoked",m.MESSAGE_READ_BY_PEER="onMessageReadByPeer",m.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",m.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",m.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",m.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",m.CONVERSATION_LIST_UPDATED="onConversationListUpdated",m.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",m.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",m.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",m.GROUP_LIST_UPDATED="onGroupListUpdated",m.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",m.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",m.TOPIC_CREATED="onTopicCreated",m.TOPIC_DELETED="onTopicDeleted",m.TOPIC_UPDATED="onTopicUpdated",m.PROFILE_UPDATED="onProfileUpdated",m.USER_STATUS_UPDATED="onUserStatusUpdated",m.BLACKLIST_UPDATED="blacklistUpdated",m.FRIEND_LIST_UPDATED="onFriendListUpdated",m.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",m.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",m.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",m.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",m.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",m.KICKED_OUT="kickedOut",m.ERROR="error",m.NET_STATE_CHANGE="netStateChange",m.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",m.SERVER_CONFIG_UPDATED="onServerConfigUpdated";var kt=b;(N=sn=sn||{}).LOGOUT="logout",N.DESTROY="destroy",N.CLOUD_CONFIG_UPDATE="cloud_config_update",N.PROFILE_UPDATE="profile_updated",N.ERROR="error",N.RECONNECTED="reconnected",N.FORCE_OFFLINE="im_open_status.stat_forceoffline",N.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",N.OVERLOAD_PUSH="OverLoadPush.notify2",N.NEW_MESSAGE="new_message",N.MESSAGE_PUSH="im_open_push.msg_push",N.MESSAGE_DELETED="message_deleted",N.MESSAGE_REVOKED="message_revoked",N.MESSAGE_MODIFIED="message_modified",N.SOCKET_DISCONNECTED="socket_disconnected",N.CONVERSATION_UPDATED="conversation_updated",N.TOPIC_MESSAGE_DELETED="topic_message_deleted",N.TOPIC_MESSAGE_REVOKED="topic_message_revoked",N.TOPIC_MESSAGE_MODIFIED="topic_message_modified",N.TOPIC_NEW_MESSAGE="topic_new_message",N.QUALITY_STAT="quality_stat",N.SYNC_CONVERSATION_LIST="sync_conversation_list";var Ft,qt,d=sn,xt=((t=pr=pr||{}).NEW_INVITATION_RECEIVED="newInvitationReceived",t.INVITEE_ACCEPTED="ts_invitee_accepted",t.INVITEE_REJECTED="ts_invitee_rejected",t.INVITATION_CANCELLED="ts_invitation_cancelled",t.INVITATION_TIMEOUT="ts_invitation_timeout",t.INVITATION_MODIFIED="ts_invitation_modified",pr);let Vt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Bt={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"},jt=((i=Ft=Ft||{}).UNSENT="unSend",i.SUCCESS="success",i.FAIL="fail",{modify:d.MESSAGE_MODIFIED,delete:d.MESSAGE_DELETED,revoke:d.MESSAGE_REVOKED}),Kt=((e=qt=qt||{})[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD",Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Bt),{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:Ft,Direction:qt})),Ht={[jt.modify]:d.TOPIC_MESSAGE_MODIFIED,[jt.delete]:d.TOPIC_MESSAGE_DELETED,[jt.revoke]:d.TOPIC_MESSAGE_REVOKED},Wt={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"},$t=Object.assign({},Wt),Yt={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},zt=Object.assign(Object.assign(Object.assign(Object.assign({},Yt),{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"}),Jt=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"}),Qt={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},Xt={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Zt={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},es=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Qt),{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:Xt,GROUP_TIPS_OPERATION_TYPE:Zt}),C=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Vt),Kt),$t),zt),Jt),es),{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},ss={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},h={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"},o={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"},ns={[h.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:o.USER_STATUS_UPDATE},{stepId:o.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_RECOVER},{stepId:o.HISTORY_MESSAGE_RECOVER,dependency:o.CONVERSATION_RECOVER},{stepId:o.BLACKLIST_RECOVER},{stepId:o.FRIEND_RECOVER},{stepId:o.GROUP_REVOKED_NOTICE_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.GROUP_TIPS_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.TOPIC_REQUEST_INFO_RESET},{stepId:o.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_RECOVER]},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[h.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:o.COMMERCIAL_CONFIG_UPDATE},{stepId:o.CLOUD_CONFIG_SYNC},{stepId:o.USER_PROFILE_SYNC},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.FRIEND_AND_BLACKLIST_SYNC},{stepId:o.GROUP_LIST_SYNC},{stepId:o.CONVERSATION_LIST_SYNC},{stepId:o.SIGNALING_MESSAGE_RECOVER,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[o.GROUP_LIST_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_GROUP_LIST_SYNC},{stepId:o.CONVERSATION_GROUP_UPDATE,dependency:[o.CONVERSATION_LIST_SYNC,o.CONVERSATION_GROUP_LIST_SYNC]},{stepId:o.QUALITY_REPORT}],[h.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.HANDLE_C2C_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]}],[h.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_GROUP_NEXT_SEQUENCE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.EMIT_GROUP_MESSAGE_EVENT,dependency:[o.HANDLE_GROUP_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},rs={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},is={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var os,as,ls=Object.freeze({__proto__:null,ERROR_CODE:ts,InnerEvent:d,OuterConstant:C,OuterEvent:kt,QUALITY_METRICS:rs,SDK_EDITION:ss,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:is,SignalingEvent:xt,WORKFLOW_DEFINITIONS:ns,WORKFLOW_NAME:h,WORKFLOW_STEP:o});(m=os=os||{})[m.USER_INITIATED=0]="USER_INITIATED",m[m.KICKED_OUT=1]="KICKED_OUT",(b=as=as||{})[b.multipleAccount=1]="multipleAccount",b[b.multipleDevice=2]="multipleDevice",b[b.restApi=3]="restApi",(N=Ea=Ea||{})[N.multipleDevice=3002]="multipleDevice",N[N.multipleAccount=3003]="multipleAccount",N[N.usersigExpired=70001]="usersigExpired",N[N.restApi=20002]="restApi";let us={[as.multipleAccount]:"multipleAccount",[as.multipleDevice]:"multipleDevice",[as.restApi]:"REST_API_Kick",[Ea.multipleAccount]:"multipleAccount",[Ea.multipleDevice]:"multipleDevice",[Ea.restApi]:"REST_API_Kick",[Ea.usersigExpired]:"userSigExpired"},cs="login_online_presence_task",{ERROR:ds,DESTROY:hs,FORCE_OFFLINE:gs}=d,{KICKED_OUT_MULT_ACCOUNT:ps,KICKED_OUT_MULT_DEVICE:_s,KICKED_OUT_REST_API:ms,ACCOUNT_A2KEY_EXPIRED:vs,MSG_A2KEY_EXPIRED:fs}=ts;class Is{init(){var e=k["notificationCenter"];e.subscribeInnerEvent(gs,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(ds,fs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(ds,vs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(ds,ps,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(ds,_s,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(ds,ms,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(hs,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(t){return S(this,void 0,void 0,function*(){var e=t["kickedOutReasonCode"];try{this._logKickedOutEvent(t),yield k.login.loginAction.logout(os.KICKED_OUT)}catch(e){console.debug(e)}finally{k.notificationCenter.emitOuterEvent(kt.KICKED_OUT,{data:{type:us[e]},name:kt.KICKED_OUT}),[as.restApi,vs,fs].includes(e)&&k.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,s=k.ssoLog.createSSOLogData({method:"kickedOut"}),e=`type:${us[e]} newInstanceInfo: `+JSON.stringify(t);s.setLogInfo({message:e}).end(!0),console.warn("loginModule."+e)}_isKickedOut(e){return[as.multipleAccount,as.multipleDevice,as.restApi].includes(e)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(gs,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(ds,vs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(ds,fs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(ds,ps,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(ds,_s,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(ds,ms,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(hs,this._dispose,this)}}function Ss(){return S(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=k.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=""+t.head.seq+e;try{let d=yield k.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:n,CustomStatus:r,PurchaseBits:i,A2Key:o,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:u,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:n,customStatus:r,purchaseBits:i,a2Key:o,authKey:a,errorCode:l,errorInfo:u,actionStatus:c}}}catch(e){throw console.warn(e),e}})}function Es(t){var s;try{var n=c.getStorage("errorMessage");if(!t||!n)return"";var r=(null==(s=JSON.parse(n))?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=r[r[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 _ extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:n="",data:r=""}=e;let i=n;s&&!n&&(i=Es(e));n=s?`${t} failed. error: {"message": ${i}, "code": ${s}}`:`${t} failed. error: {"message": ${i}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=n,this.message=n,this.data=r}}function Cs(e,t){if(e&&!0!==(null==(e=k.store.get("login"))?void 0:e.isLoggedIn))throw new _({code:ts.USER_NOT_LOGGED_IN,functionName:t})}function Ms(t,s,n){if(Array.isArray(t))for(let e=0;e<t.length;e++)ys.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:n}));else for(var e in t)ys.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:n,key:e}))}function ys({required:e,rules:n,value:t,allowEmpty:r,name:i,key:o,customValidator:a}){if(void 0===t){if(e)throw new _({functionName:i,message:`[${i}] Missing required params: "${o}"`})}else{let s="";if(!n.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<n.length;t++){let e=n[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 _({functionName:i,message:e})}if(!1===r){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new _({functionName:i,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new _({functionName:i,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new _({functionName:i,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let Os=[],As={},Ts={};function Rs(e,t){var s;Cs(As[e],e),Ms(Ts[e],t,e),s=e,Os.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function Ds(e,t){Os.push({interceptor:e,context:t})}function Ls(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(Ts,e),t&&"object"==typeof t&&Object.assign(As,t)}function Ns(e){return k.store.get("commercialConfig").get(e)}class g{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),console.log(`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),console.log(`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var n=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?n-t:0;this._stepStartTimes.delete(s+"-"+e),console.log(`[Workflow ${s}] Step ${e} completed successfully at ${new Date(n).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?n-e:0;this._workflowStartTimes.delete(s),console.log(`[Workflow ${s}] completed successfully at ${new Date(n).toISOString()} (${t}ms)`)}},error:(s,e,n)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),console.error(`[Workflow ${s}] Step ${e} failed at ${new Date(r).toISOString()} (${t}ms)`,n)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),console.error(`[Workflow ${s}] failed at ${new Date(r).toISOString()} (${t}ms)`,n)}}}}static getInstance(){return g._instance||(g._instance=new g),g._instance}static setInstance(e){g._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,n){var r;this._handlers.has(e)?ns[e].find(e=>e.stepId===t)?(r=this._handlers.get(e)).has(t)||r.set(t,n?s.bind(n):s):console.debug(`Step '${t}' not defined in workflow '${e}'`):console.debug(`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return S(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){console.log(`[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,r=(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 n=()=>{i.cancelled?t():this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:o}).filter(e=>!r.runningSteps.has(e)).forEach(e=>{r.completedSteps.has(e)||r.runningSteps.has(e)||this._executeWorkflowStep(e,r,{onComplete:()=>{0===r.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:o}).filter(e=>!r.runningSteps.has(e)).length&&0===r.runningSteps.size&&(console.log(`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:n})})};n()}),console.log(`[Workflow ${o}] Completed execution at `+(new Date).toISOString())}catch(e){console.error(`[Workflow ${o}] Failed execution at `+(new Date).toISOString(),e)}finally{this._activeWorkflows.delete(o)}}})}_executeWorkflowStep(a,l,u){return S(this,void 0,void 0,function*(){let{workflowName:i,runningSteps:e,stepMap:s,stepResults:n,data:r}=l;e.add(a),this._logWorkflowExecution(i,a,"start");try{let e=s.get(a),t=null;null!=e&&e.dependency&&(Y(e.dependency)?t=n[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=n[e]})));var o=this._handlers.get(i).get(a);if(o){let e=yield Promise.resolve(o({data:r,result:t}));n[a]=e,this._logWorkflowExecution(i,a,"success")}l.completedSteps.add(a)}catch(e){let t=`[Workflow].${i}.`+a,{errorCode:s,errorInfo:n=t+" failed"}=e||{},r=new _({functionName:t,code:s,message:n});k.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${i}, stepId: `+a}).setError(r).end(),this._logWorkflowExecution(i,a,"error",e),u.onError(e)}finally{e.delete(a),l.pendingSteps.delete(a),u.onStepComplete(),u.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)||(console.debug(`No handlers registered for workflow '${e}'`),!1):(console.debug(`Workflow '${e}' not defined`),!1)}_getExecutableSteps(e){let{pendingSteps:t,completedSteps:s,stepMap:n,workflowName:r}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=n.get(e)||{};if(!t)return!0;if(Y(t))return this._isStepRegistered({workflowName:r,stepId:t})?s.has(t):!e;if(J(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:r,stepId:e})).length&&e)return!1;for(let e of t)if(!s.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,n){this._logHandlers[s](e,t)}}let bs=new Map,Ps=({type:e,groupID:t})=>e===C.GRP_COMMUNITY||(""+t).startsWith(Xt.COMMUNITY)&&!(""+t).includes(Xt.TOPIC),ws=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(Xt.COMMUNITY)&&(""+e).includes(Xt.TOPIC)},Gs="openim",Us="million_group_open_http_svc";function ks(s){return S(this,void 0,void 0,function*(){var{servcmd:e,data:t}=Fs(e=s.data)||qs(e)?function(e){let{servcmd:t,data:s}=e;var n,r,i;return qs(s)?({servcmd:e,data:n}=e,{GroupId:r=""}=n,[r]=(i=r).split(Xt.TOPIC),{servcmd:xs(e),data:Object.assign(Object.assign({},n),{GroupId:r,TopicId:i})}):{servcmd:t=Fs(s)?xs(t):t,data:s}}(s):s,t=k.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return k.channel.sendPacket(t,{requestId:e})})}function Fs(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return Ps({type:e,groupID:t})}function qs(e){var{GroupId:e=""}=e;return ws(e)}function xs(e){return e.includes(Gs)?e:(e=e.split(".")[1],Us+"."+e)}function p(){var e;return null==(e=k.store.get("login"))?void 0:e.userId}let Vs=e=>J(e)||Q(e),Bs=(s,n,r,i)=>{if(!Vs(s)||!Vs(n))return 0;let o=0;var a,l=Object.keys(n);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!($(n[a])||r&&r.includes(a)))if(Vs(s[a])&&Vs(n[a]))o+=Bs(s[a],n[a],r,i);else{if(i&&i.includes(n[a]))continue;s[a]!==n[a]&&(s[a]=n[a],o+=1)}return o},js=(e,t)=>{if($(t))return"";switch(e){case C.MSG_TEXT:return t.text||"";case C.MSG_IMAGE:return"[Image]";case C.MSG_LOCATION:return"[Location]";case C.MSG_AUDIO:return"[Voice]";case C.MSG_VIDEO:return"[Video]";case C.MSG_FILE:return"[File]";case C.MSG_CUSTOM:return"[Custom Messages]";case C.MSG_GRP_TIP:return"[Group Notification]";case C.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case C.MSG_FACE:return"[Animated Sticker]";case C.MSG_MERGER:return"[Chat Record]";default:return""}},Ks=[{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}],Hs="im_sdk_config_mgr.fetch_config",Ws="im_sdk_config_mgr.push_configv2",$s="cloud-config";var Ys=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:n,WORKFLOW_STEP:r},channel:i}=this._core=e;e.subscribeInnerEvent(Ws,this._handlePushedConfig,this),s.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.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(Ks),i.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return S(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:n,methodCallCounter:r}=this._methodCallFrequencyMap.get(e);if(Date.now()-n>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:n,methodCallCounter:r+=1}),t<r)throw new this._core.helper.ChatError({code:2996,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_fetchCloudConfig(){return S(this,void 0,void 0,function*(){try{var e=(this._core.store.get("instance")||{})["sdkAppId"],t=this._core.helper.generateProtocolData({servcmd:Hs,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=""+t.head.seq+Hs;return yield this._core.channel.sendPacket(t,{requestId:s})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}})}_handlePushedConfig(e){return S(this,void 0,void 0,function*(){yield this._updateCloudConfig(e)})}_handleLoginSuccess(){return S(this,void 0,void 0,function*(){try{var e;this._canFetch()&&(e=yield this._fetchCloudConfig(),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:$s,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}})}_fetchCloudConfigIfReady(){return S(this,void 0,void 0,function*(){if(this._canFetch())try{var e=yield this._fetchCloudConfig();yield this._updateCloudConfig(e)}catch(e){console.warn(e)}})}_updateCloudConfig(t){return S(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:n,uint64_version:r}=e;let i=null;if(0===t){if(this._version!==r)try{i=JSON.parse(s),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*n}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return i}_parseCmdFreqLimit(){return S(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($s),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Ks),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ws,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class u{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 zs={SEARCH_GRP_SNS:new u(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new u(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new u(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new u(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new u(0,Math.pow(2,6)).toString(),USER_STATUS:new u(0,Math.pow(2,7)).toString(),CONV_MARK:new u(0,Math.pow(2,9)).toString(),CONV_GROUP:new u(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new u(0,Math.pow(2,11)).toString(),MSG_EXT:new u(0,Math.pow(2,13)).toString(),GRP_COUNTER:new u(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new u(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new u(Math.pow(2,7)).toString(),PLUGIN_CS:new u(Math.pow(2,8)).toString(),PLUGIN_PUSH:new u(Math.pow(2,9)).toString(),PLUGIN_BOT:new u(Math.pow(2,10)).toString(),MSG_REACTION:new u(Math.pow(2,16)).toString(),FOLLOW:new u(Math.pow(2,20)).toString()},Js="CommercialConfig",Qs="commercial-config";var Xs,Zs,en=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:n,WORKFLOW_STEP:r,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(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return S(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),n=s["length"];let r,i=!0;for(let e=n-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(r=(t<32?new u(0,2**t):new u(2**(t-32),0)).toString(),!this._featureMap.get(r))){i=!1;break}return console.log(Js+`.isFeatureEnabled decimalNumber:${e} key:${r} ret:`+i),{code:0,data:{enabled:i}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return S(this,void 0,void 0,function*(){var e;try{this._isFetching=!0;var t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null==(e=this._core.store.get("instance"))?void 0:e.sdkAppId}}),s=yield this._core.channel.sendPacket(t);null!=s&&s.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}})}_syncCommercialConfig(t){return S(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:Qs,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 S(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,n,r;"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:n,uint32_expired_time:r}=e,0===t?(this._parsePurchaseBits(n),this._expirationTime=Date.now()+1e3*r):void 0===t?(console.log(Js+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(console.error(Js+`._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){if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var n;for(let e=s.length-1,t=0;0<=e;e--,t++)if(n=(t<32?new u(0,2**t):new u(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(n,!0);let e=this._getKeyByValue(zs,n);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(n,!1);let e=this._getKeyByValue(zs,n);e&&this._methodKeyMap.set(e,!1)}}else console.warn(Js+".parsePurchaseBits invalid purchases:"+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(Qs),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},tn=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)}},sn=new class{constructor(){this.name="ConfigCenter"}install(e){Ys.install(e),en.install(e),tn.install(e)}},t=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return S(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 S(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"),n={},r=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(r,""),n[o]=e)}return n}}};(pr=Xs=Xs||{})[pr.START_SYNC=0]="START_SYNC",pr[pr.SYNCING=1]="SYNCING",pr[pr.SYNC_COMPLETE=2]="SYNC_COMPLETE",(i=Zs=Zs||{})[i.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",i[i.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED";var e=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 S(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=Xs.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?Zs.NEW_MESSAGE_RECEIVED:Zs.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:n,unreadCountList:r,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:r,overflowUnreadCountList:n,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 S(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return S(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:n}=e,{OuterConstant:{CONV_C2C:r,CONV_SYSTEM:i}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==i){let e=n.find(({conversationID:e})=>e===""+r+t);e?e.unreadCount=s:n.push({conversationID:""+r+t,unreadCount:s,type:r})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===i||n.find(({conversationID:e})=>e===""+r+t)||n.push({conversationID:""+r+t,type:r,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return S(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(n){var e;let r=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:i,avatar:o,conversationID:a=""}=n;if(s!==t){let s=r.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;i&&o?i===e&&o===t||r.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!1}):(n.nick=e,n.avatar=t)}}else{let e=r.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||r.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:n,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:i}=a,o=i?"":a;l.has(e)?(l.get(e).lastMessage=o,"in"!==n||r||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:r||"in"!==n?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:l}}_fetchUnreadDBMessage(l){return S(this,void 0,void 0,function*(){try{console.log("unread-message-synchronizer._fetchUnreadDBMessage options:",l);var e,t,s,n,r,i,o,a=yield function(r,l){return S(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=r,n="openim.getmsg",o=l.helper.generateProtocolData({servcmd:n,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+n;try{let e=yield l.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:n}=e,{unreadMessageList:r,revokedMessageList:i}=function(e,S){let n=[],r=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:n,MsgBody:r,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===n,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:S.message.messageHelper.parseServerPushMessageElement(r)}}();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"))r.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),n.push(e)}}),{unreadMessageList:n,revokedMessageList:r}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:r,revokedMessageList:i,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:n}}catch(e){console.warn(e)}})}(l,this._core);return a?({syncFlag:e,unreadMessageList:t,revokedMessageList:s,cookie:n,unreadCountList:r,overflowUnreadCountList:i,groupTipList:o}=a,this._parseAndSaveUnreadMessageList(t),{syncFlag:e,cookie:n,unreadMessageList:t,revokedMessageList:s,unreadCountList:r,overflowUnreadCountList:i,groupTipList:o}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===Xs.START_SYNC||t===Xs.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()}},nn=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()}},rn=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 e=((null==(e=this._core)?void 0:e.utils)||{})["MINI_APP_NAMESPACE"];e.onAppShow(()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),e.onAppHide(()=>{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()}},on=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?rn:nn).init(e)}};var an=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return S(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:"online"})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:"none"})}_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()}},ln=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return S(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()}},un=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?ln:an).init(e)}},m=new class{constructor(){this.name="SystemStateMonitor"}install(e){on.init(e),un.init(e)}};let cn=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.*"]),dn="tui_room_svr.*",hn=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=cn}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 S(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=dn}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(i,o){return S(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=dn,data:n}=i||{};let r={};try{r="string"==typeof n?JSON.parse(n):n}catch(e){console.warn(e)}n=e.generateProtocolData({servcmd:s,data:r}),e=""+n.head.seq+s;return t.sendPacket(n,{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=cn}_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)}},v="signaling",gn="signaling-timeout";function pn(e){return e.filter(e=>{var t,s;return"TIMCustomElem"===e.type&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function _n(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function mn(e,t){return e.toString(16).padStart(t,"0")}function vn(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 fn,In,Sn,f=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){v;var{inviteID:e,groupID:t,inviter:s}=e,s=s===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var n=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${e} inviteeList:${n} groupID:`+t),t){if(s)return 0<n.length;let e=this._core.common.getCurrentUserID();return n.includes(e)}return!0}updateSignaling(e){let s=v+".updateSignaling",{inviteID:n,inviter:t,inviteeList:r,groupID:i}=e;if(console.log(s+` inviteID:${n} inviter:${t} groupID:`+i),i&&this.hasSignaling(n)){let e=r[0],t=this._onlineSignalingMap.get(n)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(n)}else this.removeSignaling(n)}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()}},En=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:n}=t,s=s||n[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:n}=t;return{signaling:this._createSignaling(t,s||n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:n}=t,s=s||n[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:n}=t;return{signaling:this._createSignaling(t,s||n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:n,inviter:r}=e,s=s||(t?n[0]:r);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:n,actionType:r}=e,s=(null==(s=null==(s=f.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:n,messageControlInfo:this._createMessageControlInfo(e,r)}}_createMessageControlInfo(e,t){t=5===t&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){v;var{userID:t,timeout:s=0,groupID:n="",inviteeList:r=[]}=e,i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:1,inviter:i,inviteeList:n?r:[t],timeout:s});return console.log("signaling._createInviteSignalingData signalingData:",e),e}_createAcceptSignalingData(e){v;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:n}=f.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:3,groupID:n,inviter:t,inviteeList:[s]});return console.log("signaling._createAcceptSignalingData signalingData:",e),e}_createCancelSignalingData(e){v;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviteeList:t,groupID:n}=f.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:2,groupID:n,inviter:s,inviteeList:t});return console.log("signaling._createCancelSignalingData signalingData:",e),e}_createRejectSignalingData(e){v;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:n}=f.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:4,groupID:n,inviter:t,inviteeList:[s]});return console.log("signaling._createRejectSignalingData signalingData:",e),e}_createTimeoutSignalingData(e){v;var{isInviter:t=!1,inviteID:s}=e,{inviteeList:s,inviter:n}=f.getSignaling(s),r=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:5,inviter:n,inviteeList:t?s:[r]});return console.log("signaling._createTimeoutSignalingData signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?"GROUP":"C2C",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[mn(vn(32),8),mn(vn(16),4),mn(16384|vn(12),4),mn(32768|vn(14),4),mn(vn(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Cn=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 S(this,void 0,void 0,function*(){var s;console.log(v+".invite params:"+JSON.stringify(t));try{this._validateBeforeInvite(t);var{signaling:n,signalingData:r,signalingExtensionOptions:e}=En.createInviteSignaling(t),i=yield this._sendSignaling(n,e);if(0!==(null==i?void 0:i.code))return i;{let{inviteID:e,timeout:t}=r;return f.saveSignaling(e,Object.assign(Object.assign({},r),{signaling:n})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:gn+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}}catch(e){throw console.error(v+".invite error:"+e),e}})}accept(i){return S(this,void 0,void 0,function*(){console.log(v+".accept params:"+JSON.stringify(i));try{var e=i["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:n}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,En.createAcceptSignaling(i)),r=yield this._sendSignaling(t,n);return 0===(null==r?void 0:r.code)?(f.updateSignaling(s),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(v+".accept error:"+e),e}finally{this._isProcessingSignaling=!1}})}cancel(r){return S(this,void 0,void 0,function*(){console.log(v+".cancel params:"+JSON.stringify(r));try{var e=r["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,En.createCancelSignaling(r)),n=yield this._sendSignaling(t,s);return 0===(null==n?void 0:n.code)?(f.removeSignaling(e),Object.assign(Object.assign({},n),{inviteID:e})):n}catch(e){throw console.error(v+".cancel error:"+e),e}finally{this._isProcessingSignaling=!1}})}reject(r){return S(this,void 0,void 0,function*(){console.log(v+".reject params:"+JSON.stringify(r));try{var e=r["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,En.createRejectSignaling(r)),n=yield this._sendSignaling(t,s);return 0===(null==n?void 0:n.code)?(f.removeSignaling(e),Object.assign(Object.assign({},n),{inviteID:e})):n}catch(e){throw console.error(v+".reject error:"+e),e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return S(this,void 0,void 0,function*(){console.log(v+".modifyInvitation params:"+JSON.stringify(e));var n,r,{inviteID:i,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(i);let e=f.getSignaling(i),t=e["signaling"],s=I(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var l=yield null==(r=null==(n=this._core)?void 0:n.message.messageAction)?void 0:r.modifyMessage(t);return f.hasSignaling(i)&&f.saveSignaling(i,Object.assign(Object.assign({},s),{signaling:t})),l}catch(e){if(a){let e=f.getSignaling(i)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){if(0!==pn([e]).length)return e={businessID:(e=_n(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||1,timeout:e.timeout||0},console.log(v+" getSignalingInfo ",e),e}addSignalingListener(e,t,s){var n;e===(null==(n=this._core)?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&f.setSignalingListenStatus(!0),null!=(n=this._core)&&n.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var n;e===(null==(n=this._core)?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&f.setSignalingListenStatus(!1),null!=(n=this._core)&&n.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=f.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 S(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 S(this,void 0,void 0,function*(){var r;console.log(v+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:i,inviteID:o}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=En.createTimeoutSignaling(s),t=yield this._sendSignaling(a,e);if(0===(null==t?void 0:t.code)){let{data:e,groupID:t,inviteeList:s,inviter:n}=l;null!=(r=this._core)&&r.notificationCenter.emitOuterEvent(null==(r=this._core)?void 0:r.SignalingEvent.INVITATION_TIMEOUT,{name:null==(r=this._core)?void 0:r.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:n,isSelfTimeout:!0,message:a}}),i?f.removeSignaling(o):f.updateSignaling(l)}})}_validateInviteId(e,t){if(!f.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:8010})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var e=e["userID"],t=this._core.common.getCurrentUserID();if(e===t)throw new this._core.helper.ChatError({functionName:"invite",message:`cannot invite yourself, currentUserId:${t}, inviteeId:`+e})}_validateBeforeAccept(t){var s="accept";this._validateInviteId(s,t),this._validateProcessStatus(s);let n=this._core.common.getCurrentUserID(),e=f.getSignaling(t)["inviteeList"];if(!e.includes(n)){let e=`userID:${n} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t="cancel",s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),n=f.getSignaling(e)["inviter"];if(n!==s){let e=`unmatched inviter:${n} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s="reject";this._validateInviteId(s,t),this._validateProcessStatus(s);let n=this._core.common.getCurrentUserID(),e=f.getSignaling(t)["inviteeList"];if(!e.includes(n)){let e=`userID:${n} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){this._validateInviteId("modifyInvitation",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}},Mn=new class{constructor(){this._actionProcessor=new Map([[1,this._onNewInvitationReceived.bind(this)],[4,this._onInviteeRejected.bind(this)],[3,this._onInviteeAccepted.bind(this)],[2,this._onInvitationCancelled.bind(this)],[5,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=_n(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){f.getSignalingListenStatus()&&0!==(e=pn(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){f.getSignalingListenStatus()&&0<(e=pn(e.data)).length&&e.forEach(e=>{var t=_n(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){v;var{inviteID:n,inviteeList:r,groupID:i}=t,o=this._core.common.getCurrentUserID();if(console.log(`signaling._onNewInvitationReceived signalingData:${JSON.stringify(t)}}`),!i||r.includes(o)){let e=t["timeout"];var i=Date.now()/1e3-s.time,o=(0<e&&0<i&&e>i&&(e-=i),f.getSignaling(n));o!==t&&(o||f.saveSignaling(n,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(i=this._core)&&i.helper.taskScheduler.addOnceTask({id:gn+"-"+n,intervalMs:1e3*e,callback:Cn.handleInvitationExpiryTimer.bind(Cn,n)})),this._emitEvent({name:null==(o=this._core)?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:r})}))}}_onInviteeRejected(e){v;var{inviteID:t,inviter:s,groupID:n,inviteeList:r}=e,i=f.hasSignaling(t);console.log(`signaling._onInviteeRejected inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+n),i&&(f.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){v;var{inviteID:t,inviter:s,groupID:n,inviteeList:r}=e,i=f.hasSignaling(t);console.log(`signaling._onInviteeAccepted inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+n),i&&(f.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){v;var{inviteID:t,inviter:s,groupID:n}=e,r=f.hasSignaling(t);console.log(`signaling._onInvitationCancelled inviteID:${t} hasInviteID:${r} inviter:${s} groupID:`+n),r&&(f.removeSignaling(t),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){v;var{inviteID:t,inviteeList:s}=e,n=f.hasSignaling(t);console.log(`signaling._onInvitationTimeout inviteID:${t} hasInviteID:${n} data:`+e.data),n&&(f.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:s,isSelfTimeout:!1})}))}_onInvitationModified(e,t){v;var{inviteID:s,data:n}=e,r=f.hasSignaling(s);console.log(`signaling._onInvitationModified inviteID:${s} data:`+n),r&&(f.saveSignaling(s,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:s,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:n}=e;return{inviteID:e,inviter:t,groupID:s,data:n||""}}_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)}},yn=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:n,WORKFLOW_NAME:r}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&f.getSignalingListenStatus()){e=pn([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();Mn.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=_n(e);s&&(t=s["actionType"],1===t?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:n=[],timeout:r=0}=e,i=this._core.common.getCurrentUserID();n.includes(i)&&(n=Date.now()/1e3-t.time,0<r&&r<n&&0!==r||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 On={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}}},An={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0},Tn=new class{constructor(){this.name="Signaling"}install(e){Cn.init(e),Mn.init(e),En.init(e),f.init(e),yn.init(e),e.helper.registerValidateConfig({auth:An,params:On})}},E=new class{init(e){this.core=e}},Rn=((b=fn=fn||{}).MSG_TEXT="TIMTextElem",b.MSG_CUSTOM="TIMCustomElem",b.MSG_LOCATION="TIMLocationElem",b.MSG_FACE="TIMFaceElem",(N=In=In||{})[N.FORWARD=0]="FORWARD",N[N.BACKWARD=1]="BACKWARD",{ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"}),Dn="16k_zh-PY",Ln={[Rn.ZH_CN]:"16k_zh",[Rn.EN_US]:"16k_en",[Rn.YUE_HK]:"16k_yue",[Rn.JA_JP]:"16k_ja",[Rn.ZH_PY]:Dn},Nn=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,bn={READ:0,UNREAD:1},Pn=((Ea=Sn=Sn||{}).IN="in",Ea.OUT="out","C2C"),wn="GROUP";function Gn(i){return S(this,void 0,void 0,function*(){var e,s=E.core["appStore"],{messageList:t,conversationID:n}=i,s=s.conversationStore.getConversationMap();let r=null==(e=s.get(n))?void 0:e.peerReadTime;if(!r){let e=n.replace(Pn,""),t=yield function(t){return S(this,void 0,void 0,function*(){var e={To_Account:t};return E.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];r=null==e?void 0:e[0],s.has(n)&&(s.get(n).peerReadTime=r)}}t.forEach(e=>{e.time<=r&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)})})}function Un(a){return S(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:n,constants:{OuterConstant:r}}=E.core,i=n.conversationStore.getConversationMap();if(i.has(a)){let s=null==(e=i.get(a))?void 0:e.userProfile;if(s&&a.startsWith(r.CONV_C2C)){let{avatar:e,nick:t}=s;E.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 kn(e){let t,s=E.core["message"],{conversationID:n,messageID:r}=e;return t=(t=s.messageDataHandler.getLocalMessageList(n).find(e=>e.ID===r))||s.messageDataHandler.getSparseMessageList(n).find(e=>e.ID===r)}function Fn(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:n,avatar:r,nick:i,ID:o,clientSequence:a,clientTime:l,messageRandom:u,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:n,From_Account:t,From_AccountHeadurl:r,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 qn(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:n,GroupId:r,MsgClientTime:i,ClientSeq:o,To_Account:a,MsgTimeStamp:l,TinyId:u,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:n,clientTime:i,time:l,tinyID:u,random:c,sequence:d,to:a,groupID:r,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return E.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var xn=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:n,MESSAGE_REACTION_UPDATED_SYNC:r}}=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,n,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,r,this._handleReactionSync,this)}addMessageReaction(g,p){return S(this,void 0,void 0,function*(){let{OuterConstant:e,ssoLog:t,helper:n}=this._core;this._validateMessageReactionBusinessCapability();var r=t.createSSOLogData({method:"addMessageReaction"}),{conversationID:s,ID:i,conversationType:o,from:a,to:l,clientSequence:u,random:c,time:d,sequence:h}=g;try{return this._recordMessageReactedByMe(i,p),o===e.CONV_C2C?yield function(o,a){return S(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:n,time:r,reactionID:i}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${n}_`+r,Reaction:i,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:a,to:l,clientSequence:u,random:c,time:d,reactionID:p},this._core):o===e.CONV_GROUP&&(yield function(n,r){return S(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=n,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=r.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:l,reactionID:p,sequence:h},this._core)),r.setLogInfo({message:`conversationID:${s} messageID:${i} reactionID:`+p}).end(),{code:0}}catch(e){this._removeMyReactionRecord(i,p);let t=(e||{})["errorCode"],s=new n.ChatError({functionName:"addMessageReaction",code:t});r.setError(s).end(),console.error("addMessageReaction error: ",e)}})}removeMessageReaction(d,h){return S(this,void 0,void 0,function*(){let{OuterConstant:u,ssoLog:e,helper:n}=this._core;this._validateMessageReactionBusinessCapability();var c=e.createSSOLogData({method:"removeMessageReaction"});try{let{conversationID:e,ID:t,conversationType:s,from:n,to:r,clientSequence:i,random:o,time:a,sequence:l}=d;return this._removeMyReactionRecord(t,h),s===u.CONV_C2C?yield function(o,a){return S(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:n,time:r,reactionID:i}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${n}_`+r,Reaction:i,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:n,to:r,clientSequence:i,random:o,time:a,reactionID:h},this._core):s===u.CONV_GROUP&&(yield function(n,r){return S(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=n,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=r.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},r)})}({to:r,reactionID:h,sequence:l},this._core)),c.setLogInfo({message:`conversationID:${e} messageID:${t} reactionID:`+h}).end(),{code:0}}catch(e){let t=(e||{})["errorCode"],s=new n.ChatError({functionName:"removeMessageReaction",code:t});c.setError(s).end(),console.error("removeMessageReaction error: ",e)}})}getAllUserListOfMessageReaction(u){return S(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:n=0}=u,s=100<u.count?100:u.count,r=e["conversationID"],{ssoLog:i,helper:o,constants:a}=this._core;try{var l;if(l=r.startsWith(a.OuterConstant.CONV_C2C)?yield function(l){return S(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:n}=l,{from:e,to:r,clientSequence:i,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:n,From_Account:e,To_Account:r,MsgKey:i+`_${o}_`+a};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:n,count:s}):yield function(i){return S(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:n}=i,{sequence:e,to:r}=e,s={Reaction:s,NextSeq:t,GroupId:r,Count:n,MsgSeq:e};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:n,count:s})){let{Reaction_Account:e,NextSeq:t}=l,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===n,userList:s}}}}catch(e){let t=(e||{})["errorCode"],s=new o.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});i.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}})}getMessageReactions(g){return S(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),g),n=t[0];let r=null,i=new Map,{from:o,to:a,conversationType:l}=n,u=this._generateMessageKeyList(t,i),{Results:c=[]}=(l===e.OuterConstant.CONV_C2C?r=yield function(r){return S(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:n}=r,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:n};return E.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&&(r=yield function(n){return S(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=n,e={GroupId:e,MsgSeqList:t,Count:s};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:u,maxUserCountPerReaction:s})),r||{}),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:n}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:h}),reactedByMyself:1===n}})}})}}})}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 S(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 S(this,void 0,void 0,function*(){let n=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;n.set(s,{nick:e,avatar:t,userID:s})}),n})}_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("MSG_REACTION"))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=>S(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:n,MsgClientTime:r,MsgRandom:i}=Object.assign(Object.assign({},e),t),o=n+`-${r}-`+i,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),u=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,n=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:n}}),{reactionID:t,totalUserCount:s,partialUserList:n,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:n={},Reaction:r,OperateType:i}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:n=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),n),n=e+`-${n}-`+o,o=n+"-"+r;if(1===i?this._recordMessageReactedByMe(n,r):this._removeMyReactionRecord(n,r),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:n,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,r){var t=this._core["constants"],s=e[0]["conversationType"];let n=[];return s===t.OuterConstant.CONV_C2C?n=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:n}=e,e=e+`_${t}_`+s;return r.set(e,n),e}):s===t.OuterConstant.CONV_GROUP&&(n=e.map(e=>{var{ID:e,sequence:t}=e;return r.set(t,e),t})),n}},Vn=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:n},notificationCenter:r}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),r.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),r.subscribeInnerEvent(t,n,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return S(this,void 0,void 0,function*(){let{common:n,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new n.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(n){return S(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t=n[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=n.map(e=>{var{from:e,to:t,sequence:s,random:n,time:r,clientTime:i}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:n,MsgTime:r,MsgClientTime:i}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return S(this,void 0,void 0,function*(){var{common:e,constants:t}=E.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 n.ChatError({code:t,message:s})}})}getMessageReadReceiptList(r){return S(this,void 0,void 0,function*(){let{common:n,constants:t}=this._core;try{let e=r[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(r);if(0<(null==s?void 0:s.length)){let e=yield function(s){return S(this,void 0,void 0,function*(){var{common:e,constants:t}=E.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:r,readReceiptList:t})}}return{code:0,data:{messageList:r}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(i){return S(this,void 0,void 0,function*(){let{constants:e,common:n}=this._core,{message:t,filter:o=bn.READ,cursor:s=""}=i,{conversationID:r,sequence:a,ID:l}=t,u=r.replace(e.OuterConstant.CONV_GROUP,""),c=100<=i.count?100:i.count;try{let i=yield function(i){return S(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:n,count:r}=i,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:n,Num:r};return E.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:n}=i,r={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return o===bn.READ?r.readUserIDList=n.map(e=>e.Read_Account):o===bn.UNREAD&&(r.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:r}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let r=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:i,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(i)){let n=""+t.OuterConstant.CONV_C2C+a;null!=i&&i.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=kn({conversationID:n,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,r.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(r)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,n=new Map;t.forEach(e=>{n.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=n.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:n,UnreadNum:r}=e,e=e+`-${t}-`+s,t=kn({conversationID:o,messageID:e}),s={groupID:i,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof n&&(t.readReceiptInfo.readCount=n,s.readCount=n),"number"==typeof r&&(t.readReceiptInfo.unreadCount=r,s.unreadCount=r),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:n}=this._core;n.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),n.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Bn(o,a,l){return S(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{from:t,to:s,clientSequence:n,random:r,time:i}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:n+`_${r}_`+i,OperateType:l,ExtensionList:a}})})}function jn(n,r,i){return S(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{to:t,sequence:s}=n;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:i,ExtensionList:r}})})}var Kn=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:n},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(n,this.reset,this)}setMessageExtensions(d,n){return S(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:r,conversationID:i,sequence:o,time:a,conversationType:s}=d,l=t.createSSOLogData({method:"setMessageExtensions"}),u=n;20<n.length&&(u=n.slice(0,20),console.warn("the length of extensions cannot exceed 20"));var c=this._generateServerExtensions(d,u);try{let n;if(s===e.CONV_C2C?n=yield Bn(d,c,1):s===e.CONV_GROUP&&(n=yield jn(d,c,1)),n){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,n);return l.setLogInfo({message:`convID:${i} messageID:${r} sequence:${o}
2
+ time:${a} count:${u.length} successCount:${t} failCount:`+s}).end(),{code:0,data:{extensions:e}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"],s=new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t});throw l.setError(s).end(),s}})}getMessageExtensions(o){return S(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:n,sequence:t,time:r}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),i=this._core.ssoLog.createSSOLogData({method:"getMessageExtensions"});i.setLogInfo({message:`convID:${e} messageID:${n} sequence:${t} time:`+r});try{let e,t=(this._completedFetchExtensions.has(n)&&(e=this._extensionsLatestSequenceMap.get(n)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(n),i.end(),{code:0,data:{extensions:t}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{},n=new this._core.common.ChatError({code:t,message:s});throw i.setError(n).end(),n}})}deleteMessageExtensions(h,g){return S(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t},ssoLog:s}=this._core,{conversationType:r,conversationID:n,sequence:i,ID:o,time:a}=h,l=3,u=[];e(g)||(l=2,null==g)||g.forEach(e=>{u.push({key:e,value:"",seq:0})});var c=s.createSSOLogData({method:"deleteMessageExtensions"}),d=(c.setLogInfo({message:`convID:${n} messageID:${o} sequence:${i} time:${a} operateType:`+l}),this._generateServerExtensions(h,u));try{let n;if(r===t.CONV_C2C?n=yield Bn(h,d,l):r===t.CONV_GROUP&&(n=yield jn(h,d,l)),n){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(h,n);return c.setMoreMessage(`success count:${t} fail count:`+s),c.end(),{code:0,data:{extensions:e}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"],s=new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t});throw c.setError(s).end(),s}})}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:n}}=this._core;e.unSubscribeInnerEvent(t,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],n=t["Seq"],r=t.ExtensionList||[],i=[],o=0,a=0,l=[];return r.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:n}=t;i.push({code:e,key:t,value:s}),0===e?o++:a++,l.push({key:t,value:s,seq:n})}),this._extensionsLatestSequenceMap.set(s,n),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 n=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=n&&n.set(e,{value:s,seq:t})})}_fetchMessageExtensions(l,s){return S(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=E.core["common"]["buildAndSendPacket"],{from:e,to:n,clientSequence:r,random:i,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:n,MsgKey:r+`_${i}_`+o,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(i=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{to:e,sequence:n}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:n,StartSeq:t}})}(l,s)),i){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=i,n=(i.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,n),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=n[n.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let r=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||r.push({key:t,value:e})})}return r}}catch(e){console.error(e)}})}_clearLocationExtensions(e,n){if(!(n<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=n&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let n=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!=n&&n.has(e)?null==(t=n.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("MSG_EXT"))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:n,TinyId:r,MsgLastSeq:i,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},r=r+`-${o}-`+a;this._extensionsLatestSequenceMap.set(r,i),1===n?this._handleMessageExtensionsUpdated({messageID:r,updateMessageExtensionsInfo:e}):2===n?this._handleMessageExtensionsDeleted({messageID:r,deleteMessageExtensionsInfo:t}):3===n&&this._handleMessageExtensionsCleared({messageID:r,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,updateMessageExtensionsInfo:r=[]}=e,i=[];r.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(n,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:n,extensions:i}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,deleteMessageExtensionsInfo:r=[]}=e,i=[];r.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(i.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(n,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:n,keyList:i}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:n}}=this._core,{messageID:r,clearMessageExtensionsInfo:i=[]}=e,o=[];i.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(r)&&(this._messageExtensionsMap.get(r)||[]).forEach((e,t)=>{e.seq<=s&&!n(e.value)&&o.push(t)}),this._clearLocationExtensions(r,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:r,keyList:o}})}};let Hn={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=E.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},Wn={setMessageExtensions:[Hn,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Hn],deleteMessageExtensions:[Hn]},$n=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}=E.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}}}),Wn),Yn=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});class zn{constructor(e){this._core=e}deleteMessage(s){return S(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 S(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:n,random:r}=i;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:r,MsgTimeStamp:n}}})})}}class Jn{constructor(e){this._core=e}deleteMessage(s){return S(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 S(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 Qn{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:n,clientTime:r,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},n&&r&&s&&(a.ID=n+`-${r}-`+s)),a=Object.assign(Object.assign({},a),{revoker:o,revokeReason:i,revokerInfo:{userID:o,nick:"",avatar:""}})}updateRevokerInfo(t){return S(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 S(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:n})=>(e[t]={nick:s||"",avatar:n||""},e),{}):null})}}var Xn=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Jn(e),this._c2cMessageAction=new zn(e),this._messageHelper=new Qn(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 S(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:2116});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:n,_onlineOnlyFlag:r,sequence:i,random:o,time:a}=e||{};if("success"===n&&t===c&&s===d){if(!r){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(i){return S(this,void 0,void 0,function*(){var s;let n=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:e,isRevoked:t}=i;var 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"});n.setLogInfo({message:`type:${i.type} from:${i.from} to:`+i.to});try{if(r="C2C"===e?yield this._c2cMessageAction.revokeMessage(i):yield this._groupMessageAction.revokeMessage(i)){let e=r["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});return n.end(),yield this._handleRevokeMessageSuccess(i),{code:0,data:{message:i}}}}catch(e){let t=e["errorCode"],s=new this._core.helper.ChatError({functionName:"revokeMessage",code:t});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(s).end(),s}})}resendMessage(t,s){return S(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(r){if(0!==r.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:n}=this._core;r.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:r=""}=r[0];e(r)?t.emitInnerEvent(n.TOPIC_MESSAGE_DELETED,r):t.emitInnerEvent(n.MESSAGE_DELETED,r)}}_handleRevokeMessageSuccess(r){return S(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:n}=r;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:n,revoker:e}),yield this._messageHelper.updateRevokerInfo([r])})}};class Zn{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new Zn({index:e,data:t})}constructor(e){this.type=fn.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 er{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new er({description:e,longitude:t,latitude:s})}constructor(e){this.type=fn.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 tr=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(fn.MSG_FACE,Zn),e.message.messageFactory.registerElementClass(fn.MSG_LOCATION,er),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 Zn({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 n=((null==e?void 0:e.payload)||{})["atUserList"],r=this._core.apiMap.createTextMessage(e),i=this._core["OuterConstant"];if(!r)return null;if(Array.isArray(n)){let t=[],s=[];n.forEach(e=>{e!==i.MSG_AT_ALL?(t.push({GroupAtAllFlag:0,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:1}),s.push(i.MSG_AT_ALL))}),r._groupAtInfoList=t,r.atUserList=s}return r}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:n,priority:r,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:n,isPlaceMessage:0,priority:r,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,n;return e?({description:t,longitude:s,latitude:n}=(null==e?void 0:e.payload)||{},t=new er({description:t,longitude:s,latitude:n}),s=this._core.common.getCurrentUserID(),(n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),n):null}};let sr=class{init(e){this._messageHelper=new Qn(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:n},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),n(r.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 S(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return S(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:n,From_Account:r,RevokerInfo:{Revoker_Account:i,Revoke_Reason:o}}=e,n=l()===r?"C2C"+n:"C2C"+r,e=(null==(r=null==e?void 0:e.RevokerInfo)?void 0:r.Reason)||o,r=this._messageHelper.generateRevokeMessage({conversationID:n,sequence:s,random:t,revoker:i,revokeReason:e});a.push(r)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return S(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)}},nr=class{init(e){this._messageHelper=new Qn(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 S(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:u}=i,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:n},common:{isCommunity:r}}=this._core,h=!1;u&&(h=r({groupID:u.GroupId})||!n(u.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:n,TinyId:r,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:r,clientTime:n,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 rr=new class{constructor(){this._c2cMessageReceiver=new sr,this._groupMessageReceiver=new nr}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class ir{constructor(e){var t=(this._core=e)["constants"];this._messageHelper=new Qn(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,n=this._filterValidGroupIDList(t);0!==n.length&&(e=Math.min(Math.ceil(n.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,n.length);return this._fetchGroupRevokeNotice(n.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return S(this,void 0,void 0,function*(){var e;try{var t=yield function(i){return S(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:n}=E.core,r=e.groupStore.getGroupMap(),t={NotifyReqList:i.map(e=>{var t=r.get(e);return{NotifyType:1,Limit:20,Type:n.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*E.core.common.timeManager.getServerTimeMs()}})||[]};return n.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:n="",Reason:r=""}}=e,i="GROUP"+o,i=this._messageHelper.generateRevokeMessage({conversationID:i,sequence:t,random:s,clientTime:e,revoker:n,revokeReason:r});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 S(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 or{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new Qn(e)}getRoamingMessagesByAnchor(p){return S(this,void 0,void 0,function*(){var r;try{var{conversationID:i,count:e,messageID:n,time:o,direction:a}=p;let t=o,s="";if(!o){let e=n?this._core.message.messageDataHandler.findMessage(n):null;if(t=(null==e?void 0:e.time)||0,n&&this._historyMessageListFetchAnchors.has(i)){let e=this._historyMessageListFetchAnchors.get(i);t=e.lastMessageTime,s=e.messageKey}}var l=i.replace(Pn,""),u=yield function(i){return S(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:n,direction:r}=i,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:n,GetDirection:r};return E.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:n}=u;this._historyMessageListFetchAnchors.set(i,{messageKey:s,lastMessageTime:n});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==(r=g[0])?void 0:r.ID,lastMessageTime:n,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){Pn;var e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:"C2C",flow:"in"}));return t.setElement(e.elements),t}}var ar=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new ir(e),this._c2cMessageHistory=new or(e),this._messageHelper=new Qn(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 S(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var n=this._core.ssoLog.createSSOLogData({method:"getMessageList"}),r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:20})){let e=null;if(t.startsWith(wn)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:20,direction:In.FORWARD}):t.startsWith(Pn)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:20,direction:In.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}=E.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 Un(t),t.startsWith(Pn)&&(yield Gn({messageList:a,conversationID:t}));var _=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,l.length+r),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 n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s}
3
+ availableLocalMessagesCount: ${r} sequenceList: ${JSON.stringify(f)} `}).end(),{code:0,data:v}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r}}`}).end(),{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:20})}}catch(e){d=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(d).end(),console.debug(d)}})}getMessageListHopping(n){return S(this,void 0,void 0,function*(){var i,o;let{conversationID:e,sequence:a,time:t,direction:l=In.FORWARD}=n,u=this._core.helper["isEmpty"];if(![In.BACKWARD,In.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=20}=n,c=(s=20<s?20:s,null);if(e.startsWith(wn)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:n,invisibleSequenceList:r}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(n),l===In.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:n,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==In.BACKWARD)return{code:0,data:c};{if(u(n)&&u(r))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(i=null==n?void 0:n[n.length-1])?void 0:i.sequence)||0,t=(null==(o=null==r?void 0:r[r.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:n.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(Pn)&&(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===In.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(g){return S(this,void 0,void 0,function*(){var t;let{appStore:e,common:{ChatError:s,getCurrentUserID:n},OuterConstant:{CONV_C2C:r,CONV_GROUP:i},message:o,apiMap:a,ssoLog:l}=this._core,u=e.conversationStore.getConversation(g);if(!u)throw new s({code:2500});var c=l.createSSOLogData({method:"clearHistoryMessage"}),d=(c.setLogInfo({message:"convID:"+g}),{fromAccount:n()}),h=u["type"];h===r?(d.type=1,d.toAccount=g.replace(r,"")):h===i&&(d.type=2,d.toGroupID=g.replace(i,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:g});let e=yield function(r){return S(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:n}=r,e={From_Account:e,Type:t,To_Account:s,ToGroupid:n};return E.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(d);return e&&(c.end(),o.messageDataHandler.deleteConversationMessageList(g),this._clearedConversations.add(g),this._fetchedCompleteConversations.delete(g),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(g),this._updateConversationLastMessage(g)),{code:0,data:{conversationID:g}}}catch(e){let t=e["errorCode"],s=new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:t});throw c.setError(s).end(),s}})}_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),n=s["length"];if(!t)return n;let r=-1;return null!=e&&e.startsWith(Pn)?r=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(wn)&&(r=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===r?0:r}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return S(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var n=this._core.message.messageDataHandler.getLocalMessageList(t),r=n.length;let i=r,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=r;return s?(l=n.findIndex(e=>t.startsWith(Pn)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,i=l):a=e<r?r-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=n.slice(a,l),o.isCompleted=i<=e,t.startsWith(Pn)&&(yield Un(t),yield Gn({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()}},lr=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(r){return S(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=r,n=yield function(i,o){return S(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=i,{store:n,common:r}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=n.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=n.get("instance"))?void 0:e.sdkAppId},s=yield r.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(n){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=n;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})}})}},ur=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return S(this,void 0,void 0,function*(){let{message:e,language:t=Rn.ZH_PY}=s,n=(e.payload||{})["url"];var r=null==(r=this._core.store.get("login"))?void 0:r.userID,r=(e.from===r&&"out"===e.flow&&(n=e.payload.remoteAudioUrl),this._validateVoiceFormat(n),(null==(i=Nn.exec(n))?void 0:i[1])||"mp3"),i=Ln[t]||Dn;try{let s=yield function(e){var{store:t,common:s}=E.core,{url:e,format:n,serverLanguageType:r}=e,r={BytesUrl:e,BytesEngServiceType:r,BytesVoiceFormat:n,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:r})}({url:n,format:r,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||{},n=new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s});console.error(n),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(n).end()}})}_validateVoiceFormat(e){if(!Nn.test(e))throw new this._core.common.ChatError({code:2119})}};class cr{constructor(e){var{constants:t,common:s,utils:n}=E.core,{CONV_C2C:t,CONV_GROUP:r}=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,n.deepCopyWithMethods(m));i.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=i,e?p.startsWith(t)?this.receiverUserID=a:p.startsWith(r)&&(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 dr{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:n,PbMsgKey:r,JsonMsgKey:i}=e||{},e=e.map(e=>qn(e));return new dr({messageList:e,title:n,abstractList:s,compatibleText:t,pbDownloadKey:r,downloadKey:i})}constructor(e){this.type=E.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:n,compatibleText:r,pbDownloadKey:i="",downloadKey:o="",version:a=0,layersOverLimit:l=!1}=e,u=[];t.forEach(e=>{e&&(e=new cr(e),u.push(e))}),this.content={messageList:u,title:s,abstractList:n,compatibleText:r,version:a,downloadKey:o,pbDownloadKey:i,layersOverLimit:l}}validateBeforeSend(){var e=E.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:n,pbDownloadKey:r,title:i,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:n,PbMsgKey:r,Title:i,Version:o,MsgList:Fn(a)}}}}var hr=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:n}}=this._core=e;t.messageFactory.registerElementClass(n.MSG_MERGER,dr),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===n.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){var t,s=this._core["common"];return e?(t=new dr(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 S(this,void 0,void 0,function*(){var e,t,s;try{var i=function(t){let e="utf-8";E.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,n=0,r;if(r=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<r;e++)(s=t.codePointAt(e))<=127?n+=1:s<=2047?n+=2:s<=65535?n+=3:(n+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<r;e++)(s=t.codePointAt(e))<=65535?n+=2:(n+=4,e++);else n=t.replace(/[^\x00-\xff]/g,"aa").length;return n}(JSON.stringify(a));let n=a,r=null;if(11264<i){n=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return S(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:Fn(e)};return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(n),s=n["payload"];r=new dr(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),n.setElement(r)}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(n,l))["data"];return r&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){throw console.error(e),e}})}downloadMergerMessage(i){return S(this,void 0,void 0,function*(){try{var e=i.payload,t=e["downloadKey"],s=I(e,["downloadKey","pbDownload","type","messageList"]),n=((yield function(e){return S(this,void 0,void 0,function*(){return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(t))||{})["MsgList"],r=null==n?void 0:n.map(e=>{e=qn(e);return new cr(e)});return"function"==typeof i.isOnlineMessage?i.setElement({type:i.type,content:Object.assign({messageList:r},s)}):(i.payload.messageList=r,i.payload.downloadKey="",i.payload.pbDownloadKey=""),i}catch(e){console.error(e)}})}},gr=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return S(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:n}}=this._core,{GroupId:r,To_Account:i}=a,o=(a.From_Account=a.From_Account||s(),null);if(r){o=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:r}));let e=t.userStore.getUserProfile(s());o.level=(null==e?void 0:e.level)||0,n(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:Sn.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:Sn.OUT})),s=e["elements"];return t.setElement(s),t}},pr=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,E.init(e),Xn.init(e),tr.init(e),rr.init(e),ar.init(e),xn.init(e),lr.init(e),ur.init(e),Vn.init(e),hr.init(e),Kn.init(e),gr.init(e),e.helper.registerValidateConfig({auth:Yn,params:$n}),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),rr.dispose(),ar.dispose(),Vn.dispose(),Kn.dispose()}_reset(){ar.reset()}},_r=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(p,_){return S(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:n="PUT",url:r,qs:i,headers:o={},resources:a,dataType:l="text",uploadByIP:u,uploadIP:c}=p,d=r;if(i){let e=this._queryString(i);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(n.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,n="&",r="="){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)+r;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(n):t+encodeURIComponent(s[e])}).filter(Boolean).join(n):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let mr=["unknown","image","video","audio","log"];var vr,fr=new class{init(e){this._core=e}request(s,n){let e,{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:i,IN_UNI_IOS_APP:o}=null==(e=this._core)?void 0:e.utils,{resources:a="",headers:l={},url:u,downloadUrl:c=""}=s,d=u,h=null;var g=c?c.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(g){var g=decodeURIComponent(g[3]),g=g.includes("?")?g.split("?")[0]:g||"",g={key:s.fileKey||g,success_action_status:200,"Content-Type":""},p={};if(o){let[e,t]=u.split("?sign=");t&&(d=e+"?sign="+encodeURIComponent(t),p.sign=decodeURIComponent(t),p.signature=decodeURIComponent(t))}let t={url:d,header:l,name:"file",filePath:a,formData:Object.assign(Object.assign({},g),p),timeout:s.timeout||3e5};if(i){let e=I(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?mr[s.fileType]:"image"})}return(h=r.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:c,callback:n})},fail:e=>{this._handleResponse({response:e,downloadUrl:c,callback:n})}}))).onProgressUpdate&&h.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),h}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,n={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(n[e.toLowerCase()]=t.header[e]);var r=+t.statusCode;200==r?s(null,{statusCode:r,headers:n,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:r,message:JSON.stringify(t.data)},{statusCode:r,headers:n,data:void 0})}};function Ir(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Sr(e){e=e||99999999;return Math.round(Math.random()*e)}function Er(e,t=!0,s=!0){var n=Date.now();return t?s?n-e+" ms":Math.round((n-e)/1e3)+" s":s?n-e:Math.round((n-e)/1e3)}function Cr(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Mr(e,t){return Math.round(Number(e)*10**t)/10**t}function yr(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function Or(e){return e<=1048576?Mr(e/1024,1)+"KB/s":Mr(e/1048576,1)+"MB/s"}let Ar="TIMImageElem",Tr="TIMSoundElem",Rr="TIMFileElem",Dr="TIMVideoFileElem",M="RichMediaMessagePlugin",Lr=["rich.my-imcloud.com","imrich.qcloud.com"],Nr=((i=vr=vr||{}).UNSENT="unSend",i.SUCCESS="success",i.FAIL="fail",{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 y=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,n]=s.split("?");if(!n)return s;let t=n.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(Nr).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return Ir(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 S(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=Lr;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=Lr}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,n=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?n+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),n=e?n+"."+e:n)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),n=this.getAuthKey(),r=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),n&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),n=e&&e[2]||"";if(n.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(n.endsWith(t[e])){s=!0;break}}return s}(t,r));return t=e?-1<t.indexOf("?")?t+"&authKey="+n:t+"?authKey="+n: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:n}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:n}}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}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===s}_probeImageDimensionsWeb(n){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=n})}},br=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?fr:_r,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return S(this,void 0,void 0,function*(){var t=M+" uploadToCOS",e=l["file"];this.uploadFileType=l.uploadFileType,console.log(t+" options:",l);try{var s=Date.now(),n=yield this._createCosOptions(l),r=yield this._uploadFile(n),i=(this._handleUploadError(r,l),this._createUploadResult(e,r)),o=Date.now()-s,a=`size:${yr(e.size)} time:${o}ms speed:`+Or(1e3*e.size/o);return console.log(t+` ok. name:${e.name} `+a),{uploadOptions:n,response:i}}catch(e){throw console.warn(t+" failed, error:",e),e}})}_handleUploadError(e,t){var s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(403===e.statusCode)throw Er(Date.now(),!1),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:Er(Date.now(),!1),uploadSpeed:Or(1e3*e.size/Er(Date.now(),!1))}}_createCosOptions(h){return S(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:s}=this._prepareUploadParams(h),n=this._isC2CConversation(h.message.conversationID)?1:2;try{var r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:h.message.from,conversationType:n}),{uploadUrl:i,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c}=r,d=!y.isPrivateNetWork()&&r.uploadIP;return{url:this._getRawOrUploadProxyUrl(i),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,uploadIP:d||"",onProgress:e=>this._handleUploadProgress(e,h)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){console.log(M+" prepareUploadParams:",e);var t=e["file"],{IN_MINI_APP:s,IN_RN_APP:n}=y.getPlatformFlags(),s=s||n,n=s&&e.message.type!==Rr,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+Sr(999999)+e;return{fileName:Cr(n?t.name:e),resources:s?t.url:t,uploadMethod:s?1:0}}_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 S(this,void 0,void 0,function*(){var t=M+" fetchCosSignatureUrl",s=y.isSimpleCos(),n=this._prepareCosRequestData(e),r=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(r,i,o){return S(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:r,data:i}),n=s.head.seq+r;return yield t.sendPacket(s,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}})}(r,n,this._core);this.fetchCosTryCount=0;var i=this._processResponse(e);return console.log(t+` ok. isSimpleCos:${s} data:`,i),i||{}}catch(s){if(console.error(t+" failed, error:",s),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,s}})}_processResponse(e){var t;let s=y.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:n,str_download_url:r,str_upload_url:i,str_snapshot_url:o,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:n,downloadUrl:r,uploadUrl:i,requestSnapshotUrl:o,fileKey:a}}let{upload_url:n,download_url:r,snapshot_url:i,thumb_url:o,large_url:a,file_key:u}=l;return{uploadUrl:n,downloadUrl:r,requestSnapshotUrl:i,thumbUrl:o,largeUrl:a,fileKey:u}}_prepareCosRequestData(e){return y.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:y.getPlatform(),uint32_sdkappid:y.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(r){return S(this,void 0,void 0,function*(){return new Promise((s,n)=>{this.httpRequest.request(r,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(r).then(s).catch(n)):(this.uploadFileTryCount=0,e?n(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 n=null==(t=e.error)?void 0:t.Code,r=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===n||"AccessDenied"===n&&"Request has expired"===r}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=y.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let Pr=["jpg","jpeg","gif","png","bmp","image","webp"],wr={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Gr{constructor(e,t){this.instanceID=Sr(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=y.addAuthToUrl(e.imageUrl||e.url||""),this.url=y.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=y.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Ur(e){var{originUrl:t,originWidth:e,originHeight:s,min:n=198}=e,r=parseInt(e)||0,s=parseInt(s)||0,i={url:void 0,width:0,height:0};if((r<=s?r:s)<=n)i.url=t,i.width=r,i.height=s;else{s<=r?(i.width=Math.ceil(r*n/s),i.height=n):(i.width=n,i.height=Math.ceil(s*n/r));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";i.url=198===n?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?I(i,["url"]):i}class kr{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Ar;var{uuid:e,file:t,imageFormat:s,imageInfoArray:n=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:s,uuid:e,imageInfoArray:[]},this.initImageInfoArray(n),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:s,ImageInfoArray:n,UUID:r}=t,i=n.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new kr({imageFormat:s,imageInfoArray:i,uuid:r})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:n,IN_BROWSER:r}=y.getPlatformFlags();return t=e&&((s||n)&&(t=e.url),r)?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 n=t[e]||Object.assign({},s),n=new Gr(n,this._imageMemoryURL);n.setSizeType(e+1),n.setType(e),this.addImageInfo(n)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let n=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,s;e.url&&""!==e.imageUrl&&([t,...s]=e.imageUrl.split("://"),s=s.join("://"),n.includes(t)||e.setImageUrl("https://"+s))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=wr[e.toUpperCase()]||wr.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var s,n=this.content.imageInfoArray.length;for(let e=0;e<n;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],Ur({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:y.removeAuthToUrl(e.imageUrl)}))}}var Fr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:n}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==n?void 0:n.messageFactory)&&t.registerElementClass(Ar,kr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(r){var i,o,a,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createImageMessage"}),t=(console.log(M+" createImageMessage options:",r),null==(i=this._core.store.get("login"))?void 0:i.userId),s=null==(a=null==(o=this._core)?void 0:o.message.messageFactory)?void 0:a.createMessage(Object.assign(Object.assign({},r),{from:t})),n=this._processImage(r);r.payload.file=n;var l={imageFormat:wr.UNKNOWN,uuid:y.generateUUID(n),file:n,imageInfoArray:[]},u=new kr(l);return s.setElement(u),this._messageOptionsMap.set(s.clientSequence,r),console.log(M+" createImageMessage OK imageMessage:",s),e.end(),s}catch(r){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)&&t.call(e,r).end(),console.error(M+" createImageMessage error:",r),r}}upload(n){return S(this,void 0,void 0,function*(){console.log(M+" uploadImage message:",n);var e=n.getElements()[0],t=this._messageOptionsMap.get(n.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,n,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),n})}_performImageUpload(n,r,s){return S(this,void 0,void 0,function*(){var e=r["to"],{uploadOptions:e,response:t}=yield br.uploadToCOS({uploadFileType:1,file:s,to:e,message:r,onProgress:e=>{var t,s;n.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(r.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){console.log(M+" generateImageInfo");var{location:e,fileSize:t,width:s,height:n,smallImageUrl:r,smallImageWidth:i,smallImageHeight:o,largeImageUrl:a,largeImageWidth:l,largeImageHeight:u,imageInfoArray:c}=e,e=y.addAuthToUrl(e),d={size:t,url:e,width:s,height:n};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):r&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:r,smallImageWidth:i,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,n,720),this._generateThumbInfo(e,s,n,198)]}_generateThumbInfo(e,t,s,n){return Ur({originUrl:e,originWidth:t,originHeight:s,min:n})}_processImageInfoArray(e,t){let s,n,r;for(var i of e)1===i.type?(n=i,n.size=t):2===i.type?(r=i,r.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},r),Object.assign({},n)]}_parseResponse(n,r){return S(this,void 0,void 0,function*(){console.log(M+" parseResponse");try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=n;if(e&&t&&(yield this._getImageInfoByUrl(e,r,"thumb"),yield this._getImageInfoByUrl(t,r,"large")),y.isSimpleCos()&&!y.isPrivateNetWork()&&(yield this._getImageInfoArray(s,r),null!=r)&&r.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,r))}return r}catch(e){throw console.error("Failed to parse response:",e),e}})}_extractDomainFromUrl(e){try{var t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(n,r,i){return S(this,void 0,void 0,function*(){try{var e=y.addAuthToUrl(n),{width:t=0,height:s=0}=yield y.probeImageWidthHeight(e);r.width=t,r.height=s,"thumb"===i?(r.smallImageUrl=n,r.smallImageWidth=t,r.smallImageHeight=s):(r.largeImageUrl=n,r.largeImageWidth=t,r.largeImageHeight=s)}catch(e){console.warn(`Failed to get ${i} image info:`,e)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var s=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],n=e.payload["file"];return s?this._processMiniAppImageFile(n):this._processWebImageFile(n)}catch(e){throw console.warn(M+" _processImage error:",e),e}}_processMiniAppImageFile(e){Ir(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=y.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(n,r){return S(this,void 0,void 0,function*(){var e=M+" getDownloadIP domainName: "+n;try{var t,s=yield function(o,a){return S(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",n={str_domain:o},r=e.generateProtocolData({servcmd:s,data:n}),i=r.head.seq+s;return yield t.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(n,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=r.location.split("/"))[0]=s.str_final_ip,r.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(s,n){return S(this,void 0,void 0,function*(){var t=M+"._getImageInfoArray";try{var e=yield function(o,a){return S(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",n={str_image_url:o},r=e.generateProtocolData({servcmd:s,data:n}),i=r.head.seq+s;return yield t.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(s,this._core);return n.imageInfoArray=this._processImageInfoResponse(e),console.log(t+" ok"),n}catch(e){throw n.imageInfoArray=void 0,console.warn(t+" failed, error:",e),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 n="";if(t.IN_MINI_APP&&(n=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(n=e.name.slice(e.name.lastIndexOf(".")+1)),Pr.indexOf(n.toLowerCase())<0)throw new s.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:s}=this._core,n=0;if(t.IN_MINI_APP,0===(n=e.size))throw new s.ChatError({code:2108});if(20971520<=n)throw new s.ChatError({message:"File size exceeds limit: "+yr(20971520)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let qr=104857600;function xr(e,t){let n=e.split("."),r=t.split("."),i=Math.max(n.length,r.length);for(;n.length<i;)n.push("0");for(;r.length<i;)r.push("0");for(let s=0;s<i;s++){let e=parseInt(n[s]),t=parseInt(r[s]);if(e>t)return 1;if(e<t)return-1}return 0}let Vr=new class{init(e){this.core=e}};class Br{constructor(e){this.type=Rr,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:y.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:n,UUID:r}=e;return new Br({downloadFlag:e,url:t,fileName:s,fileSize:n,uuid:r})}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:n,fileSize:r}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:y.removeAuthToUrl(s),FileName:n,FileSize:r,UUID:e}}}_getFileInfo(e){var t=Vr.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=Sr(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 jr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:n}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==n?void 0:n.messageFactory)&&t.registerElementClass(Rr,Br),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(s){var n,r,i,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createFileMessage"}),t=(console.log(M+" createFileMessage options:",s),this._checkVersion(),this._processFile(s.payload.file));s.payload.file=t;var o=null==(n=this._core.store.get("login"))?void 0:n.userId,a=null==(i=null==(r=this._core)?void 0:r.message.messageFactory)?void 0:i.createMessage(Object.assign(Object.assign({},s),{from:o})),l={uuid:y.generateUUID(t),file:t},u=new Br(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,s),console.log(M+" createFileMessage success fileMessage:",a),e.end(),a}catch(s){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)&&t.call(e,s).end(),console.error(M+" createFileMessage error:",s),s}}upload(s){return S(this,void 0,void 0,function*(){console.log(M+" uploadFile message:",s);var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),s.getElements()[0]),e=yield this._performFileUpload(t,s,e),e=y.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:2401});if(e.size>qr)throw new t({message:"File size exceeds limit: "+yr(qr)});if(0===e.size)throw new t({code:2108})}_performFileUpload(n,r,t){return S(this,void 0,void 0,function*(){var e=r["to"],e=(yield br.uploadToCOS({uploadFileType:255,file:t,to:e,message:r,onProgress:e=>{var t,s;n.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(r.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:n,IN_QQ_MINI_APP:r,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=y.extractFileFromInput(t);if(e)return e;throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(n||r){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:n,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils,i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(e){if(!(s||n||r))throw new i({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&xr(e,"2.5.0")<0)throw new i({message:"WXChooseMessageFile requires SDK version 2.5.0 or higher"});if(n&&xr(e,"1.18.0")<0)throw new i({message:"QQChooseMessageFile requires SDK version 1.18.0 or higher"})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Kr=["mp4","quicktime","mov"],Hr=104857600;class Wr{constructor(e){this.type=Dr,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:y.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:y.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:y.addAuthToUrl(e.thumbUrl),snapshotUrl:y.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:n,VideoDownloadFlag:r,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 Wr({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:n,videoDownloadFlag:r,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;y.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),y.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),y.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:n,videoDownloadFlag:r,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:y.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:n,VideoDownloadFlag:r,VideoUUID:i,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:y.removeAuthToUrl(_),SnapshotUrl:y.removeAuthToUrl(m)}}}}var $r=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:n}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==n?void 0:n.messageFactory)&&t.registerElementClass(Dr,Wr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(s){var n,r,i,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"}),t=(console.log(M+" createVideoMessage options:",s),this._processVideo(s));s.payload.file=t;var o=null==(n=this._core.store.get("login"))?void 0:n.userId,a=null==(i=null==(r=this._core)?void 0:r.message.messageFactory)?void 0:i.createMessage(Object.assign(Object.assign({},s),{from:o})),l={videoFormat:t.videoFile.type,videoSecond:Mr(t.videoFile.second,0),videoSize:t.videoFile.size,remoteVideoUrl:"",videoUrl:t.videoFile.url,videoUUID:y.generateUUID(t.videoFile),thumbUUID:y.generateUUID(t.videoFile,"jpg"),thumbWidth:t.width||200,thumbHeight:t.height||200,thumbUrl:t.thumbUrl,thumbSize:t.thumbSize,thumbFormat:"jpg"},u=new Wr(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,s),e.end(),a}catch(s){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)&&t.call(e,s).end(),console.error(M+" createVideoMessage error:",s),s}}upload(n){return S(this,void 0,void 0,function*(){console.log(M+" uploadVideo message:",n);var e=n.getElements()[0],t=this._messageOptionsMap.get(n.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,n,t)),{location:t,snapshotInfo:s}=t,t=y.addAuthToUrl(t);return e.updateVideoUrl(t),y.isEmpty(s)||e.updateSnapshotInfo(s),n})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>Hr)throw new t({message:"File size exceeds limit: "+yr(Hr)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===Kr.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(n,r,s){return S(this,void 0,void 0,function*(){var e=r["to"],{response:e,uploadOptions:t}=yield br.uploadToCOS({uploadFileType:2,file:s,to:e,message:r,onProgress:e=>{var t,s;n.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(r.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var n,r;try{var i=(null==(n=this._core)?void 0:n.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(r=this._core)?void 0:r.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=y.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(M+" _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,n=(null==(n=this._core)?void 0:n.helper)["ChatError"];if(t)throw new n({message:"VideoUnsupportedInAlipay"});if(Ir(e))throw new n({message:"FileUnsupportedInMiniApp"});let r=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(r=e.fileType||r),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:r}}_processWebVideoFile(e){var{name:t,size:s=1,duration:n=0,type:r}=e,r=r.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:n,type:r}}_getSnapshotInfoByUrl(r){return S(this,void 0,void 0,function*(){try{console.log(M+" _getSnapshotInfoByUrl url:",r);var e,t,s,n=((yield function(i,o){return S(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,n=t.generateCosSpecifiedData({servcmd:e,data:i}),r=n.head.seq+e;return yield s.sendPacket(n,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:y.getPlatform(),cover_name:Cr(Sr(99999)),snapshot_url:r},this._core))||{})["download_url"];return(console.log(M+" _getSnapshotInfoByUrl OK snapshotUrl:",n),y.isEmpty(n))?{}:(e=y.addAuthToUrl(n),{width:t=0,height:s=0}=yield y.probeImageWidthHeight(e),{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s})}catch(e){throw console.error(M+" _getSnapshotInfoByUrl error:",e),e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Yr{constructor(e){this.uploadProgress=0,this.type=Tr,this.content={downloadFlag:2,second:e.second,size:e.size,url:y.addAuthToUrl(e.url),remoteAudioUrl:y.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:n,UUID:r}=e;return new Yr({url:e,downloadFlag:t,second:s,size:n,uuid:r})}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:n,second:r}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:y.removeAuthToUrl(s),Download_Flag:t,Second:r,Size:n,UUID:e}}}}var zr,Jr,Qr,Xr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:n}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==n?void 0:n.messageFactory)&&t.registerElementClass(Tr,Yr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(t){var s,n,e,r;try{let e=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(M+" createAudioMessage options:",t);t.payload["file"];var i=this._processAudioFile(t.payload.file),o=(t.payload.file=i,null==(r=this._core.store.get("login"))?void 0:r.userId),a=null==(n=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:n.createMessage(Object.assign(Object.assign({},t),{from:o})),l={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:y.generateUUID(i)},u=new Yr(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,t),e.end(),a}catch(t){throw null!=(r=(e=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)&&r.call(e,t).end(),console.error(M+" createAudioMessage error:",t),t}}upload(s){return S(this,void 0,void 0,function*(){console.log(M+" uploadAudio message:",s);var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadAudio(e),s.getElements()[0]),e=yield this._performAudioUpload(t,s,e),e=y.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:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+yr(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(n,r,t){return S(this,void 0,void 0,function*(){var e=r["to"],e=(yield br.uploadToCOS({uploadFileType:3,file:t,to:e,message:r,onProgress:e=>{var t,s;n.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(r.clientSequence))?void 0:t.onProgress)&&s.call(t,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 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}},ei={createImageMessage:Zr,createAudioMessage:Zr,createVideoMessage:Zr,createFileMessage:Zr},ti={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},si={TIMImageElem:Fr,TIMFileElem:jr,TIMVideoFileElem:$r,TIMSoundElem:Xr},ni=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:n,MSG_VIDEO:r}}=(this._core=e)["constants"];Vr.init(e),Fr.init(e),jr.init(e),$r.init(e),Xr.init(e),br.init(e),y.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,n,r].includes(e[0].type)}),e.helper.registerValidateConfig({auth:ti,params:ei})}sendMessage(n,r){return S(this,void 0,void 0,function*(){var e,t,s;try{return console.log("sendMessage message:",n),yield this._upload(n),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(n,r)}catch(e){throw console.error("sendMessage error:",e),e}})}_upload(n){return S(this,void 0,void 0,function*(){var t,s;if(!0!==n._relayFlag)try{let t=si[n.type];if(t){let e=this._core.ssoLog.createSSOLogData({method:"upload"});e.setLogInfo({message:"type:"+n.type}),yield t.upload(n),e.end()}}catch(e){throw n.status=vr.FAIL,e instanceof Error&&(e.data={message:n}),this._core.message.messageDataHandler.storeConversationMessage(n),null!=(s=(t=this._core.ssoLog.getSSOLogData("upload")).setError)&&s.call(t,e).end(),e}})}},O=new class{init(e){this.core=e}},ri=e=>{var{OuterConstant:t,utils:{isString:s}}=O["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},ii=e=>{var{OuterConstant:t,utils:{isString:s}}=O["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},oi=e=>{var{OuterConstant:t,utils:{isString:s}}=O["core"];return s(e)&&e===t.CONV_SYSTEM},ai=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:O.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 li(e){var t=O.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 ui(e,t){var s=O.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 ci{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=ai(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}}=O["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}}=O["core"],{nextUnreadCount:e,isFromGetConversations:n,isUnreadC2CMessage:r}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?n&&this.type===t.CONV_GROUP||r&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=ai(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=O["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}}=O["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}(b=zr=zr||{})[b.OFF=0]="OFF",b[b.ON=1]="ON",Jr=Jr||{},Jr[Jr.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID",(N=Qr=Qr||{})[N.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",N[N.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",N[N.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE";var A=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:e,notificationCenter:t,appStore:{conversationStore:s},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:r},InnerEvent:{SYNC_CONVERSATION_LIST:i,MESSAGE_PUSH:o,NEW_MESSAGE:a,MESSAGE_DELETED:l,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:c,CONVERSATION_UPDATED:d,LOGOUT:h,DESTROY:g}}=this._core=e,s=(this._conversationStore=s,e.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),e.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,r.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,r.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(n.RECEIVE_GROUP_NEW_MESSAGE,r.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t)["InnerEventSubType"]["GROUP_AT_TIPS"];t.subscribeInnerEvent(i,this._handleConversationSynced,this),t.subscribeInnerEvent(a,this._handleNewMessage,this),t.subscribeInnerEvent(o,s,this._handleNewGroupAtTips,this),t.subscribeInnerEvent(l,this._handleMessageDeleted,this),t.subscribeInnerEvent(u,this._handleMessageRevoked,this),t.subscribeInnerEvent(c,this._handleMessageModified,this),t.subscribeInnerEvent(d,this._handleConversationUpdated,this),t.subscribeInnerEvent(h,this._reset,this),t.subscribeInnerEvent(g,this._dispose,this),console.log(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:n=[],isUnreadC2CMessage:r}=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:r}),i=!0)}),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(n)}_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 n,{WORKFLOW_STEP:t}=this._core.constants,r=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:i}=this._core.OuterConstant,o=!1;for(let s=0;s<r.length;s++){let e=r[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==(n=e._groupAtInfoList)?void 0:n.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:r=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:r}),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:n,ClientSeq:r}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=n,i.__sequence=r,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:n}=e;return{from:e,groupID:t,sequence:s,groupAtType:n}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:n}=this._core,r=e.getCurrentUserID(),i=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==r){let e=this.getLocalConversation(""+n.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:n},OuterConstant:r}=this._core,i=(null==n?void 0:n.getLocalMessageList(t))||[];let o={};for(let e=(i.length||0)-1;0<=e;e--)if(!i[e].isDeleted){o=i[e];break}n=this.getLocalConversation(t);if(n){let e=!1;n.lastMessage.lastSequence===o.sequence&&n.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),n.updateLastMessage(o),e=!0),t.startsWith(r.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,n.lastMessage))}}_handleMessageRevoked(e){let{messageList:n=[],updateUnreadCount:r=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+n.length),0!==n.length){let t=null,s=!1;n.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(r&&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:n},common:{getMessagePreviewText:r}}=this._core;if(!n(e)){n=e["lastMessage"];if(n){let e=(null==s?void 0:s[0])||{};n.lastTime===e.time&&n.lastSequence===e.sequence&&n.version!==e.version&&(n.type=e.type,n.payload=e.payload,n.messageForShow=r(e.type,e.payload),n.cloudCustomData=e.cloudCustomData,n.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),console.log(this._name+".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 r=0;r<t;r++){let t=new ci(o[r]),{conversationID:s,type:n}=t;if(!function(e){var t=O.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),n===i.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:n===i.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[r].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:o[r].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:n,isInstantMessage:r}=e,e=this.getLocalConversation(e),i=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:n,isEmpty:o},common:{deepMerge:a}}=(!1===r&&i.push("lastMessage"),n&&i.push("isPinned"),this._core);n(r)&&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 r=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:n=""}=i;o&&(e&&(a.lastMessage.payload=e),a.type===r.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==n&&(a.lastMessage.cloudCustomData=n)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],n=[],r=[],i=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?n:s:t(e[1].lastMessage.lastTime)?i:r).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(n).concat(r.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(i);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],n=[],{CONV_GROUP:r,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===r){let e=t.replace(r,"");n.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<n.length&&this._updateGroupConversation(n)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:r},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"],n=this.getLocalConversation(""+r+s);if(n){let e=(null==(s=i.getFriend(s))?void 0:s.remark)||"";n.remark=e,n.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:n}}=this._core,r=!1;e.forEach(e=>{var t=n.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,r=!0)}),r&&this.emitConversationListUpdate()}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:n},utils:{isUndefined:r}}=this._core,e=this.getLocalConversation(e);return!(!r(e)&&(r=e.type===t&&(null==(r=e.groupProfile)?void 0:r.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===n,r||t))}updateUnreadCount(e,t=!0){let s,n,r=!1;var i,o=this.getLocalConversation(e),a=null==(n=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:n.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,(r=!0)===t)&&this.emitConversationListUpdate(),r}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&&(console.log(`${this._name}._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(),n=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(n+=e.unreadCount)}),n}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(e=>this._isConversationNeedShow(e.conversationID))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(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:r=0,lastReadSequence:i=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let n=e-1;0<=n;n--){let e=o[n],t=r&&e.time>r,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:n,MESSAGE_MODIFIED:r,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(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(r,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)}},di=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return S(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 A.getLocalConversationList();if(t(o))return 0===o.length?[]:A.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:n,hasUnreadCount:r,hasGroupAtInfo:i}=o;return A.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,r)&&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}},hi=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(n){return S(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,n){return S(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return n.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:n},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=li(t);A.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},gi=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return S(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,n){return S(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return n.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;A.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},pi=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return S(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:n,GRP_AVCHATROOM:r},appStore:{groupStore:i},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=A.getLocalConversation(u);if(oi(u))o.data.conversation=a;else{let t=!1;var l=ri(u)?s:n;if(e(a)&&(t=!0,a=new ci({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 hi.get([e]))}if(l===n){let e=u.replace(n,"");if(!i.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==r&&(yield gi.get([e]))}}}return o})}_handleC2CConversation(o,a){return S(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:n,userStore:r}}=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:Qr.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=r.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),r=A.hasLocalConversation(i);console.log(this._name+`._handleC2CConversation conversationID:${i} hasLocalConversation: `+r),r?n.updateConversation(i,o):A.appendToPinnedConversation(o)})}_handleGroupConversation(n,r){return S(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=n["conversationID"],e=yield e({groupID:r}),e=(n.groupProfile=null==e?void 0:e.data.group,n.setProfileCompleted(),A.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,n):A.appendToPinnedConversation(n)})}},_i=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return A.getTotalUnreadMessageCount()}},mi=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:n,InnerEvent:{MESSAGE_PUSH:r},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}),n.subscribeInnerEvent(r,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:n}=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=""+n.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),A.markMessageAsRead({conversationID:e,lastReadTime:t}),A.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),A.markMessageAsRead({conversationID:e,lastReadSequence:t}),A.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(l){return S(this,void 0,void 0,function*(){let e=this._core["OuterConstant"],t=l["conversationID"],s={code:0,data:{}},n=A.getLocalConversation(t);if(console.log(this._name+`.setMessageRead conversationID:${t} unreadCount:`+((null==n?void 0:n.unreadCount)||0)),n){var r=!(null!=(i=null==(r=this._core)?void 0:r.helper)&&i.isEmpty(n.groupAtInfoList));if(n.type===e.CONV_GROUP&&r&&this._deleteGroupAtTips(t),0!==n.unreadCount){var{ssoLog:i,helper:{ChatError:o}}=this._core,a=i.createSSOLogData({method:"setMessageRead"});a.setLogInfo({message:"conversationID:"+t});try{if(n.type===e.CONV_C2C){let e=this._getLocalMessageMaxTime(n);yield this._setC2CMessageRead(t,e),a.setLogInfo({moreMessage:"lastMessageTime:"+e}).end()}if(n.type===e.CONV_GROUP){let e=this._getLocalMessageMaxSequence(n);yield this._setGroupMessageRead(t,e),a.setLogInfo({moreMessage:"lastMessageSequence:"+e}).end()}}catch(e){let{errorCode:t,errorInfo:s}=e,n=new o({functionName:"setMessageRead",code:t,message:s});throw a.setError(n).end(),n}n.type===e.CONV_SYSTEM&&(n.unreadCount=0),A.emitConversationListUpdate()}}return s})}setAllMessageRead(){return S(this,arguments,void 0,function*(s={}){let{OuterConstant:{READ_ALL_MSG:e},ssoLog:t}=this._core,r=t.createSSOLogData({method:"setAllMessageRead"}),i=(s.scope||(s.scope=e),s)["scope"],o=this._generateSetAllMessageReadRequestData(i);if(0===o.allC2CMessageReadStatus&&0===o.groupMessageReadInfoList.length)return{code:0};try{let n=yield function(s){return S(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return O.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(o);if(n){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=n,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&A.emitConversationListUpdate(),r.setLogInfo({message:`scope:${i} failureGroups:`+JSON.stringify(s)}).end()}return{code:0}}catch(s){let e=s["errorCode"],t=new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e});throw r.setError(t).end(),t}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&A.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:n,CONV_GROUP:r},appStore:t}=this._core,i=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of i)if(1<=t.unreadCount){if(1===o&&t.type===n){let e=this._getLocalMessageMaxTime(t);A.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===r){let t=s.replace(r,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);A.markMessageAsRead({conversationID:s,lastReadSequence:e})}}A.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(n){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:i,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:0,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:n,type:e,unreadCount:t}))if(e===r&&0===a.allC2CMessageReadStatus){if(a.allC2CMessageReadStatus=1,n===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:r}=this._core["utils"],i=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:n}=e;r(s)?this._serverGroupConversationLastReadSeqMap.set(e,n):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&i.push(e+`-${t}-`+s))}),i}_deleteGroupAtTips(o){return S(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=A.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:n}}=this._core,r=[...i];e({groupID:o.replace(s,"")})&&0===(r=i.filter(e=>!e.atTypeArray.includes(n))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return S(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:r.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=A.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&A.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 S(this,void 0,void 0,function*(){try{yield function(e,t){return S(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:e})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(this._name+"._setC2CMessageRead ok, lastReadTime:"+t),A.markMessageAsRead({conversationID:e,lastReadTime:t}),A.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return S(this,void 0,void 0,function*(){try{yield function(s,n){return S(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return n.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),A.markMessageAsRead({conversationID:e,lastReadSequence:t}),A.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:n,READ_ALL_C2C_MSG:r,READ_ALL_GROUP_MSG:i}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![n,r].includes(o))&&(e!==s||![n,i].includes(o)))}},vi=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 r=this._core["OuterConstant"],i=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let n;1===e?n=A.getLocalConversation(""+r.CONV_C2C+t):2===e&&(n=A.getLocalConversation(""+r.CONV_GROUP+s)),n&&(console.log(`${this._name}.handleConversationPinned conversationID:${n.conversationID} localPinned:${n.isPinned} remotePinned:`+o),o&&!n.isPinned&&(n.isPinned=!0,i=!0),!o)&&n.isPinned&&(n.isPinned=!1,i=!0)}),i&&A.emitConversationListUpdate(!0)}}pinConversation(t){return S(this,void 0,void 0,function*(){let{OuterConstant:s,common:n,ssoLog:e,helper:{ChatError:r}}=this._core,{conversationID:i,isPinned:o}=t,a={code:0,data:{conversationID:i}},l=A.getLocalConversation(i);if(l&&l.isPinned===o)return a;if(oi(i))return l&&(l.isPinned=o),A.emitConversationListUpdate(!0),a;var u=e.createSSOLogData({method:"pinConversation"});u.setLogInfo({message:`conversationID:${i} isPinned:`+o});try{let e=null,t=(ri(i)?e={Type:1,To_Account:i.replace(s.CONV_C2C,"")}:ii(i)&&(e={Type:2,GroupId:i.replace(s.CONV_GROUP,"")}),yield function(n,r){return S(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=n;return r.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:n.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(u.end(),console.log(this._name+`.pinConversation ok, conversationID:${i} isPinned:${o}.`),t){if(l)l.isPinned!==o&&(l.isPinned=o);else{let e=new ci({conversationID:i,type:ri(i)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});A.setLocalConversation(i,e)}A.emitConversationListUpdate(!0)}return a}catch(e){let{errorCode:t,errorInfo:s}=e,n=new r({functionName:"pinConversation",code:t,message:s});throw u.setError(n).end(),console.error(this._name+".pinConversation fail:",n),n}})}},fi=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 n=this._core["OuterConstant"],r=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&r.push(""+n.CONV_C2C+t),2===e&&r.push(""+n.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+r),this._deleteLocalConversationList(r)}}deleteConversation(t){return S(this,void 0,void 0,function*(){var e=this._core["utils"]["isString"];e(t)?(console.log(this._name+".deleteConversation conversationID:"+t),yield this._deleteConversation({conversationIDList:[t],flag:Jr.ONLY_CONVERSATIONID})):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(a){return S(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:n=!0,flag:r=0}=a,{ssoLog:e,helper:{ChatError:i}}=this._core,t=`conversationIDList:${s} clearHistoryMessage:`+n,o=e.createSSOLogData({method:"deleteConversation"});o.setLogInfo({message:t}),console.log(this._name+"._deleteConversation "+t);try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,n)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:Qr.CONV_NOT_FOUND});return o.end(),console.log(this._name+"._deleteConversation ok."),{code:0,data:r===Jr.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,n=new i({functionName:"deleteConversation",code:t,message:s});throw o.setError(n).end(),console.error(this._name+"._deleteConversation fail:",n),n}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!A.hasLocalConversation(e)&&((t=null==(t=A.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,i){return S(this,void 0,void 0,function*(){let{OuterConstant:n,common:e}=this._core,r={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:i?1:0};if(t.forEach(e=>{var t,s;A.hasLocalConversation(e)&&(t=(null==(t=A.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===n.CONV_C2C?r.conversationList.push({To_Account:s,Type:1}):t===n.CONV_GROUP&&this._hasLocalGroup(e)&&r.conversationList.push({ToGroupid:s,Type:2}))}),0!==r.conversationList.length){var s=yield function(n,r){return S(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=n;return r.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(r,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.type?""+n.CONV_C2C+e.To_Account:""+n.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{A.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&A.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=A.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(A.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&A.emitConversationListUpdate()}_hasLocalGroup(e){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)}},Ii=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return S(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),A.hasLocalConversation(e))return null!=(e=A.getLocalConversation(e))&&e.setDraftText(t),A.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:Qr.CONV_NOT_FOUND})})}},Si=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return S(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}=O.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[l],t=yield function(s,n){return S(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return n.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||{},n=[],r=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(n.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),r.push({userID:e})}),A.patchMessageRemindType(i,l),{code:0,data:{successUserIDList:r,failureUserIDList:n}}})}},Ei=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(n,r){return S(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=n;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:n,userID:e(),receiveMessageOption:r},this._core),!t(n)){let e=""+s.CONV_GROUP+n;A.patchMessageRemindType([e],r)}return{code:0,data:{groupID:n,messageRemindType:r}}})}},Ci=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}=this._core;e.forEach(e=>{var r=e["MuteNotificationsSync"];if(!t(r)){let{To_Account:e,MuteNotifications:t}=r,s=e.map(e=>""+i.CONV_C2C+e),n=li(t);console.log(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+n),A.patchMessageRemindType(s,n)}})}setMessageRemindType(o){return S(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:n}=o,{helper:r,utils:{isUndefined:i}}=this._core;try{if(!i(e))return console.log(`${this._name}.${s} groupID:${e} messageRemindType:`+n),yield Ei.set(e,n);if(i(t))throw new r.ChatError({functionName:s,message:"userIDList or groupID is required"});return console.log(this._name+`.${s} userIDList:${t} messageRemindType:`+n),yield Si.set(t,n)}catch(e){let t=new r.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}})}},Mi=new class{init(e){console.log("ConversationAction.init"),this._core=e,di.init(e),pi.init(e),_i.init(e),mi.init(e),vi.init(e),fi.init(e),Ii.init(e),Ci.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:r,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,n,this._onConversationModified,this),e.subscribeInnerEvent(t,r,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"];fi.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];vi.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];vi.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;mi.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;Ci.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;mi.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:r,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,n,this._onConversationModified,this),e.unSubscribeInnerEvent(t,r,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},yi=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return S(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:n=0,endTime:r=0}=this._calcStartAndEndTime(o),i=yield function(i){return S(this,void 0,void 0,function*(){var e=O.core["common"],{startTime:t,endTime:s,isRepeated:n,messageRemindType:r}=i;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:n,Level:r}})})}({messageRemindType:this._getType(t),startTime:n,endTime:r,isRepeated:s?zr.ON:zr.OFF});return{code:0,data:{errorCode:i.ErrorCode,errorInfo:i.ErrorInfo}}}catch(e){ui("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:n=0,isRepeated:r=!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=r&&86400<=n?e+86400:e+n;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]}},Oi=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 S(this,void 0,void 0,function*(){try{var e=yield function(){return S(this,void 0,void 0,function*(){var e=O.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){ui("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:n}=t,{Level:e,StartTime:r,EndTime:i,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:n}[e]||t,startTime:r,endTime:i,isRepeated:o===zr.ON}}},Ai=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,Si.init(e),Ei.init(e),hi.init(e),gi.init(e),yi.init(e),Oi.init(e)}};let Ti=e=>!ri(e)&&!ii(e)&&!oi(e),Ri={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Ti(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Ti(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Ti(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:n}}=O["core"];if(!n(e)&&!s(e))return"options is String or Object.";if(n(e)&&Ti(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(Ti(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=>!(!ri(e)&&!ii(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}}},Di={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0},Li=new class{constructor(){this.name="Conversation"}install(e){O.init(e),Mi.init(e),Ai.init(e),A.init(e),e.helper.registerValidateConfig({auth:Di,params:Ri})}},Ni=new class{init(e){this.core=e}},bi="AVChatRoom",Pi="GRP_COUNTER",wi=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Gi=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ui=["Role","JoinTime","MsgFlag","MsgSeq"],ki=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Fi="notStart",qi="resolved",xi="rejected",Vi=["Owner","Admin","Member"],Bi=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ji={from:!0,groupID:!0,groupName:!0,to:!0},Ki={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Hi=e=>e===Ni.core.OuterConstant.GRP_PUBLIC,Wi=e=>e===Ni.core.OuterConstant.GRP_AVCHATROOM,$i=(n,e)=>{var t=Ni.core.utils["isArray"];if(!t(n)||!t(e))return!1;let r=!1;return e.forEach(({key:t,value:e})=>{var s=n.find(e=>e.key===t);s?s.value!==e&&(s.value=e,r=!0):(n.push({key:t,value:e}),r=!0)}),r},Yi=s=>{var n=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:r,Value:i}=s[e];n.push({key:r,value:i})}return n},zi=s=>{var n=[];for(let e=0,t=s.length;e<t;e++){var{key:r,value:i}=s[e];n.push({Key:r,Value:i})}return n};function Ji(e,t){var s=Ni.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:3122,replacement1:e})}function Qi(e,t){var s=Ni.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 Xi=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Zi{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}=Ni.core["utils"];for(t in e)Xi.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:n,isString:r},common:{deepMerge:i}}=Ni.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),r(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&$i(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=n(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:n,readedSequence:r,excludedUnreadSequenceList:i}=e,o=Ni.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:n,readedSequence:r,excludedUnreadSequenceList:i},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var T=new class{constructor(){this._name="GroupDataHandler"}init(e){var e=(this._core=e)["appStore"]["groupStore"];this._groupMap=e.getGroupMap(),console.log(this._name+".init")}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 Zi(e))});var n=t();for(let[,e]of this._groupMap)e.selfInfo.userID=n,"Owner"===e.selfInfo.role&&(e.ownerID=n)}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,n=""+e+t;if(s.getConversation(n)){let e=this.getLocalGroup(t);s.updateConversation(n,{groupProfile:e})}}reset(){this.clearLocalGroup()}};function eo(o,a){return S(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:n=0,memberAccount:r,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:r,ResponseFilter:i,SupportTopic:n,NeedAppDefineData:1}})})}function R(e){return{code:0,data:e||{}}}var to=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Fi,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 S(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}),T.updateLocalGroup(e),T.getLocalGroupList()}return console.log(this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===xi||this._pagingStatus===Fi?this._syncGroupList().then(()=>{var e=T.getLocalGroupList();return R({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw console.error(this._name+".getGroupList fail:",e),e}):(e=T.getLocalGroupList(),console.log(this._name+".getGroupList return group count:"+e.length),R({groupList:e,isSyncCompleted:this._isSyncCompleted()}))})}_syncGroupList(){return S(this,void 0,void 0,function*(){this._pagingStatus===Fi&&T.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=qi,this._groupListTreeShaking(t),T.updateLocalGroup(t);var s=T.getLocalGroupList();return console.log(this._name+"._syncGroupList ok, count:"+s.length),T.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=xi,console.error(this._name+"._syncGroupList fail:",e),e}})}_pagingGetGroupList(e){return S(this,void 0,void 0,function*(){var{isCommunityRelay:r=!1,groupList:i}=e;let o,{limit:a,offset:l}=e;var u=[...wi];r&&(o=this._core.OuterConstant.GRP_COMMUNITY,u.push("AtInfoList"));try{let e=yield eo({type:o,limit:a,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:u,SelfInfoFilter:[...Ui]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},n=this._convertGroupKey(t);i.push(...n);var c=l+a,d=!(c<s),h=`offset:${l} limit:${a} total:${s} isCompleted:${d} current:${i.length} isCommunityRelay:`+r;return console.log(this._name+"._pagingGetGroupList ok. "+h),r?d?i:(l=c,this._pagingGetGroupList({isCommunityRelay:!0,limit:a,offset:l,groupList:i})):d?(console.log(this._name+"._pagingGetGroupList start to get community list"),l=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:a,offset:l,groupList:i})):(l=c,this._pagingGetGroupList({limit:a,offset:l,groupList:i}))}catch(e){if(10018===e.ErrorCode)return console.warn(this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+a),this._pagingGetGroupList({isCommunityRelay:r,limit:50,offset:l,groupList:i});if(r)return 11e3===e.code&&console.log(this._name+"._pagingGetGroupList ok. community unavailable"),i;throw e}})}_pagingGetJoinedCommunityList(e){return S(this,void 0,void 0,function*(){var{common:{getCurrentUserID:r},OuterConstant:i}=this._core,o=e["groupList"];let{limit:a,offset:l}=e;try{let e=yield eo({limit:a,offset:l,type:i.GRP_COMMUNITY,memberAccount:r(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...wi],SelfInfoFilter:[...Ui]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},n=this._convertGroupKey(t);o.push(...n);var u=l+a,c=!(u<s),d=`offset:${l} limit:${a} total:${s} isCompleted:${c} current:`+o.length;return console.log(this._name+"._pagingGetJoinedCommunityList ok. "+d),c?o:(l=u,this._pagingGetJoinedCommunityList({limit:a,offset:l,groupList:o}))}catch(e){if(10018===e.code)return console.warn(this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+a),this._pagingGetJoinedCommunityList({limit:50,offset:l,groupList:o});throw e}})}_groupListTreeShaking(s){var n=new Map([...T.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)n.delete(s[e].groupID);var r=[...n.keys()];for(let e=0,t=r.length;e<t;e++)T.deleteLocalGroup(r[e])}_isSyncCompleted(){return this._pagingStatus===qi}_convertGroupKey(s){var n=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:r,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:S,LastRecallTime:E,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],r=Yi(r),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);n.push({groupCustomField:r,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:S,selfInfo:C,_lastRevokedTime:E,_groupAtInfoList:M,isSupportTopic:y})}return n}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:n,Role:r}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:n,role:r}}_convertAtInfoList(n,e){if(0===e.length)return[];let r=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;r.push({groupID:n,groupAtType:e,sequence:t,from:s})}),r}},so=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(l){return S(this,void 0,void 0,function*(){var i;this._preCheckParams(l);let{ssoLog:e,helper:{ChatError:n}}=this._core,o=e.createSSOLogData({method:"createGroup"});try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(g,p){return S(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:n,notification:r,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:n,Notification:r,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?zi(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:n,OverJoinedGroupLimit_Account:r=[]}=s||{};o.setLogInfo({message:"groupID:"+n}).end(),console.log(`${this._name}.createGroup ok, type:${l.type} groupID:${n} overLimitUserIDList:`+r),e(l.memberList)||e(r)||(l.memberList=null==(i=l.memberList)?void 0:i.filter(e=>r.includes(e.userID))),T.updateLocalGroup([Object.assign(Object.assign({},l),{groupID:n})]);var a=T.getLocalGroup(n);return this._notNeedSendCustomMessage(l)||(this._sendCustomMessage(n,l.type),T.emitGroupListUpdate()),R({group:a})}catch(i){let{errorCode:e,errorInfo:t}=i,s=new n({functionName:"createGroup",code:e,message:t});throw o.setLogInfo({message:"groupID:"+(l.groupID||"")}).setError(s).end(),console.error(this._name+".createGroup fail:",s),s}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:n,isUndefined:r},common:{isCommunity:i}}=this._core,n=!n(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:n,GRP_COMMUNITY:r}=Ni.core.OuterConstant;return[e,t,s,n,r]})().includes(t))throw new this._core.helper.ChatError({code:2600});if(!i({type:t})){if(n&&i({groupID:s}))throw new this._core.helper.ChatError({code:2602});r(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||r(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||r(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(n&&!i({groupID:s}))throw new this._core.helper.ChatError({code:2602});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Wi(e)}_canIUseJoinOption(e){return Hi(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:n}=this._core["OuterConstant"];return e===s||e===n&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let n="Create Group",r=0;t===s.GRP_COMMUNITY&&(n="Create Community",r=1);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:n,cmd:r,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,{})}},D=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:n}=t,r=(console.log(this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+n),this._core)["utils"]["isUndefined"];r(n)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:n}),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}),console.log(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:n,groupAttributeList:r,operation:i}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];5!==i&&n-t!=1||(e.serverMainSequence=n,e.localMainSequence=n,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:r,operation:i})),1<n-t&&(e.serverMainSequence=n),this._groupAttributesCache.set(s,e),console.log(this._name+`.refreshGroupAttributesCache. operation:${i} localMainSequence:${t} serverMainSequence:`+n)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:n,groupAttributeList:t=[],operation:s}=e;3!==s?4!==s?(1===s&&n.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;n.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{n.values.delete(e.key)}):n.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:n,keyList:r=[]}=e,i={};if(this.hasGroupAttributesCache(n)){let t=this.getGroupAttributesCache(n)["values"];if(0===r.length)for(let e of t.keys())i[e]=(null==(s=t.get(e))?void 0:s.value)||"";else r.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:n,deletedKeyList:r}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${n.length}, delete count:`+r.length),0===n.length&&0===r.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:n,deletedKeyList:r}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],n=[],r=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&n.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&r.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:n,deletedKeyList:r}}_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={}}},no=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(bi)})}dismissGroup(t){return S(this,void 0,void 0,function*(){console.log(this._name+".dismissGroup groupID:"+t);let{ssoLog:e,helper:{ChatError:r}}=this._core,i=e.createSSOLogData({method:"dismissGroup"});i.setLogInfo({message:"groupID:"+t});try{yield function(e,t){return S(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(t,this._core),i.end(),console.log(this._name+".dismissGroup ok.");let e=T.getLocalGroup(t)["type"];return T.deleteLocalGroup(t),T.emitGroupListUpdate(),D.deleteGroupAttributesCache(t),R({groupID:t,type:e})}catch(e){let{errorCode:t,errorInfo:s}=e,n=new r({functionName:"dismissGroup",code:t,message:s});throw i.setError(n).end(),console.error(this._name+".dismissGroup fail:",n),n}})}},ro=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return S(this,void 0,void 0,function*(){let{groupID:r,groupCustomFieldFilter:e}=s,i={groupIDList:[r],responseFilter:{GroupBaseInfoFilter:[...wi],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...ki]}},{ssoLog:t,helper:{ChatError:o}}=this._core,a=t.createSSOLogData({method:"getGroupProfile"});a.setLogInfo({message:"groupID:"+r});try{let e=yield this.getGroupProfileAdvance(i),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let n;return(n=!T.hasLocalGroup(r)&&Wi(t[0].type)?new Zi(t[0]):(T.updateLocalGroup(t),T.getLocalGroup(r))).isSupportTopic||T.updateConversationGroupProfile(r),a.end(),console.log(this._name+".getGroupProfile ok."),R({group:n})}catch(e){let{code:t,message:s}=e,n=new o({functionName:"getGroupProfile",code:t,message:s});throw a.setError(n).end(),console.error(this._name+".getGroupProfile fail:",n),e}})}getGroupProfileAdvance(a){return S(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),n=e.filter(e=>t({groupID:e})),r=(50<s.length&&(s.length=50),50<n.length&&(n.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:n,isCommunityProfile:!0}))])),i=[],o=[];return r.forEach(e=>{i.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:i,failureGroupList:o}})}_getGroupProfileAdvance(e){return S(this,void 0,void 0,function*(){let{isCommunityProfile:t=!1}=e,o=I(e,["isCommunityProfile"]);if(0===o.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,n){return S(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(o,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),{isUndefined:n}=this._core["utils"],r=s.filter(e=>n(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 console.log(this._name+"._getGroupProfileAdvance ok, groupID:"+o.groupIDList.join(",")),{successGroupList:r,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var n=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:r,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:S,ShutUpAllMember:E,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:O,ErrorInfo:A}=s[e],r=Yi(r),y=this._convertMembers(y);n.push({groupCustomField:r,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:S,shutUpAllMember:E,muteUntil:C,type:M,members:y,errorCode:O,errorInfo:A})}return n}_convertMembers(s){if(!s)return[];var n=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:r,JoinTime:i,Member_Account:o,MsgFlag:a,MsgSeq:l,NameCard:u,Role:c}=s[e],r=Yi(r);n.push({memberCustomField:r,joinTime:i,userID:o,messageRemindType:a,sequence:l,nameCard:u,role:c})}return n}},io=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:n,counterList:r=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(n)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(n);0<i&&i<t||(r.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(n,{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 n={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(n[e]=t.get(e))});else for(let e of t.keys())n[e]=t.get(e)}return n}deleteLocalGroupCounters(e){var{groupID:s,counterList:n=[],groupCounterSeq:r}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);n.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:r,counters:t,avChatRoomKey:e})}}setGroupCounters(t,r){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],n=!1;Object.entries(r).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),n=!0)}),n&&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()}},oo=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(bi)})}joinGroup(o){return S(this,void 0,void 0,function*(){let t=o["groupID"],{ssoLog:s,helper:{ChatError:r},OuterConstant:n}=this._core,i=s.createSSOLogData({method:"joinGroup"});try{if(T.hasLocalGroup(t))try{return yield ro.getGroupProfile({groupID:t}),i.setLogInfo({message:`groupID:${t} joinedStatus:`+n.JOIN_STATUS_ALREADY_IN_GROUP}).end(),R({status:n.JOIN_STATUS_ALREADY_IN_GROUP,group:T.getLocalGroup(t)})}catch(s){console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),T.deleteLocalGroup(t);let e=yield this._applyJoinGroup(o);return i.setLogInfo({message:"groupID:"+t}).end(),e}let e=yield this._applyJoinGroup(o);return i.setLogInfo({message:"groupID:"+t}).end(),e}catch(e){let{errorCode:t,errorInfo:s}=e,n=new r({functionName:"joinGroup",code:t,message:s});throw i.setError(n).end(),console.error(this._name+".joinGroup fail:",n),n}})}_applyJoinGroup(d){return S(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t}=this._core,s=d["groupID"],n=Object.assign({},d),t=t.checkBusinessCapabilityBits("AV_HISTORY_MSG"),n=(t&&(n.historyMessageFlag=1),yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=n;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(n,this._core)),{Type:n,JoinedStatus:r,LongPollingKey:i,StartSeq:o,HugeGroupFlag:a,AVChatRoomKey:l,RspMsgList:u=[]}=n||{},t=`groupID:${s} joinedStatus:${r} longPollingKey:${i} startSeq:${o} avChatRoomFlag:${a} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+u.length;console.log(this._name+"._applyJoinGroup ok, "+t);let c=new Zi({groupID:s,type:n});if(r===e.JOIN_STATUS_WAIT_APPROVAL)return R({status:e.JOIN_STATUS_WAIT_APPROVAL,group:c});if(r!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:2660});try{c=(yield ro.getGroupProfile({groupID:s})).data.group}catch(e){console.warn(this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${s}, errorCode:`,null==e?void 0:e.code)}return this._handleJoinResult({group:c,avChatRoomFlag:a,longPollingKey:i,startSequence:o,avChatRoomKey:l,historyMessageList:u})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:n}=e;return 1===s?(D.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:n}),io.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:n}),R(e)):(T.updateLocalGroup([t]),T.emitGroupListUpdate(),R({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}},ao=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(bi)})}quitGroup(t){return S(this,void 0,void 0,function*(){if(!T.hasLocalGroup(t))throw new this._core.helper.ChatError({code:2623});let{ssoLog:e,helper:{ChatError:r}}=this._core,i=e.createSSOLogData({method:"quitGroup"});i.setLogInfo({message:"groupID:"+t});try{yield function(e,t){return S(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(t,this._core),i.end(),console.log(this._name+".quitGroup ok, groupID:"+t);let e=T.getLocalGroup(t)["type"];return T.deleteLocalGroup(t),T.emitGroupListUpdate(),D.deleteGroupAttributesCache(t),R({groupID:t,type:e})}catch(e){let{errorCode:t,errorInfo:s}=e,n=new r({functionName:"quitGroup",code:t,message:s});throw i.setError(n).end(),console.error(this._name+".quitGroup fail:",n),n}})}},lo=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return S(this,void 0,void 0,function*(){console.log(this._name+".searchGroupByID groupID:"+v);try{var e=yield function(t,s){return S(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...Gi]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:t=[]}=e||{},{AppDefinedData:s=[],ApplyJoinOption:n,CreateTime:r,FaceUrl:i,Introduction:o,InviteJoinOption:a,MaxMemberNum:l,MemberNum:u,Name:c,Owner_Account:d,Type:h,ErrorCode:g,ErrorInfo:p}=t[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:p});console.log(this._name+".searchGroupByID ok.");var _=Yi(s),m=new Zi({groupID:v,name:c,avatar:i,introduction:o,joinOption:n,inviteOption:a,maxMemberCount:l,memberCount:u,type:h,ownerID:d,createTime:r,groupCustomField:_});return R({group:m})}catch(e){throw console.error(this._name+".searchGroupByID fail:",e),e}})}},uo=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(r){return S(this,void 0,void 0,function*(){let t=r["groupID"],{isUndefined:s}=this._core["utils"],n=T.getLocalGroup(t);if(n){let e=n["type"];this._canIUseJoinOption(e)||s(r.joinOption)||(console.warn(this._name+".updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom"),r.joinOption=void 0)}s(r.muteAllMembers)||(r.muteAllMembers=!0===r.muteAllMembers?"On":"Off");try{return yield function(u,c){return S(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:n,notification:r,muteAllMembers:i,joinOption:o,inviteOption:a,groupCustomField:l}=u,e={GroupId:e,Name:t,FaceUrl:s,Introduction:n,Notification:r,ShutUpAllMember:i,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:l?zi(l):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(r,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),n?(n.updateGroup(r),T.emitGroupListUpdate()):n=new Zi(r),R({group:n})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}})}_canIUseJoinOption(e){return Hi(e)||this._core.common.isCommunity({type:e})}},co=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(a){return S(this,void 0,void 0,function*(){let s="changeGroupOwner",{groupID:e,newOwnerID:t}=a,n=T.getLocalGroup(e),{helper:r,OuterConstant:i,common:{getCurrentUserID:o}}=this._core;if((null==n?void 0:n.type)===i.GRP_AVCHATROOM)throw new r.ChatError({functionName:s,code:2620});if(t===o())throw new r.ChatError({functionName:s,code:2621});console.log(`${this._name}.${s} groupID:${e} newOwnerID:`+t);try{return yield function(s,n){return S(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(a,this._core),console.log(this._name+`.${s} ok.`),n.ownerID=t,T.emitGroupListUpdate(),R({group:n})}catch(e){let t=new r.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}})}},ho=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(bi)})}getGroupOnlineMemberCount(r){return S(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount",e=T.hasLocalGroup(r);if(console.log(`${this._name}.${s} groupID:${r} hasLocalGroup:`+e),!e)return R({memberCount:0});let n=Date.now();if(this._onlineMemberCountMap.has(r)){let e=this._onlineMemberCountMap.get(r),{lastReqTime:t=0,memberCount:s=0}=e||{};if(n-t<=6e4)return R({memberCount:s})}try{let e=yield function(e,t){return S(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(r,this._core),{OnlineMemberNum:t=0}=e||{};return this._onlineMemberCountMap.set(r,{lastReqTime:Date.now(),memberCount:t}),console.log(`${this._name}.${s} ok. groupID:${r} memberCount:`+t),R({memberCount:t})}catch(e){let t=new this._core.helper.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}})}},go=new class{init(e,t){console.log("GroupAction.init"),to.init(e),so.init(e),no.init(e,t),oo.init(e,t),ao.init(e,t),lo.init(e),ro.init(e),uo.init(e),co.init(e),ho.init(e,t)}dismissGroup(e){return no.dismissGroup(e)}joinGroup(e){return oo.joinGroup(e)}quitGroup(e){return ao.quitGroup(e)}getGroupOnlineMemberCount(e){return ho.getGroupOnlineMemberCount(e)}},po=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return S(this,void 0,void 0,function*(){var t="getGroupApplicationList";try{var s=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]),e=(console.log(this._name+`.${t} ok.`),this._handleGroupApplicationResult([...s[0],...s[1]]));return R({applicationList:e})}catch(e){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}})}_getGroupApplicationList(i){return S(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=i||{},n=this._core["common"];let r;try{r=yield function(r,i){return S(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:n}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:n}})})}({type:e,startTime:t,limit:s,handleAccount:n.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;r={}}var{NextStartTime:e=0,PendencyList:t=[]}=r||{};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=I(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:n,FromUserNickName:r,From_Account:i,GroupId:o,GroupName:a,PendencyType:l,To_Account:u}=e;return{handled:e,messageKey:t,applicant:i,applicantNick:r,groupID:o,groupName:a,authentication:n,applicationType:l,userID:u,note:s}}},_o=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return S(this,void 0,void 0,function*(){let s="handleGroupApplication",t=e["application"],n=this._handleParams(e);try{2===(null==t?void 0:t.applicationType)?yield function(o,a){return S(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:n,authentication:r,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:n,Authentication:r,Invited_Account:i}})})}(n,this._core):yield function(o,a){return S(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:n,authentication:r,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:n,Authentication:r,MsgKey:i}})})}(n,this._core),console.log(this._name+`.${s} ok.`);let e=T.getLocalGroup(n.groupID);return R({group:e})}catch(e){let t=new this._core.helper.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}})}_handleParams(e){var{handleAction:e,handleMessage:t,message:s,application:n}=e;let r,i,o,a,l;if(s){let e=(s||{})["payload"];r=e.operatorID,i=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else r=(null==n?void 0:n.applicant)||"",i=(null==n?void 0:n.groupID)||"",o=(null==n?void 0:n.authentication)||"",a=(null==n?void 0:n.messageKey)||0;return 2===(null==n?void 0:n.applicationType)&&(l=n.userID),{handleAction:e,handleMessage:t,applicant:r,invitee:l,groupID:i,authentication:o,messageKey:a}}},mo=new class{init(e){console.log("GroupApplication.init"),po.init(e),_o.init(e)}};let vo=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}}=Ni["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&&$i(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function fo(a,l){return S(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:n,nameCard:r,memberCustomField:i}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:n,NameCard:r,AppMemberDefinedData:o=i?zi(i):o};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var Io=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(bi)})}getGroupMemberList(n){return S(this,void 0,void 0,function*(){let i="getGroupMemberList",{groupID:o,offset:a=0,count:e=100,role:t="",filter:s=""}=n;console.log(`${this._name}.${i} groupID:${o} offset:${a} count:${e} role:${t} filter:`+s);var l=T.getLocalGroup(o),u=100<e?100:e,c={groupID:o,offset:a,limit:u,memberRoleFilter:Vi.includes(t)?[t]:void 0,memberInfoFilter:Bi};try{let e=yield function(i,o){return S(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:n,memberInfoFilter:r}=i;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:n,MemberInfoFilter:r}})})}(c,this._core),{MemberList:t,MemberNum:s,Next:n}=e||{};console.log(`${this._name}.${i} ok, totalMemberCount:${s} next:`+n);var{utils:{isArray:d,isEmpty:h},common:{isCommunity:g}}=this._core;if(l&&(l.memberCount=s),!d(t)||0===t.length)return R({memberList:[],offset:0});let r=a+u;g({groupID:o})&&(r=h(n)?0:n),t.length<u&&(r=0);var p=this._convertMemberInfo(t),p=yield this._patchAvatarAndNick(p),_=this._generateGroupMember(p);return R({memberList:_,offset:r})}catch(e){let t=new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${i} fail:`,t),t}})}_convertMemberInfo(s){var n=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:r,JoinTime:i,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u}=s[e],r=Yi(r);n.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:r})}return n}_patchAvatarAndNick(i){return S(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}),n=(null==s?void 0:s.data)||[],r=new Map(n.map(e=>[e.userID,e]));return i.forEach(e=>{var t,s;r.has(e.userID)&&({nick:t="",avatar:s=""}=r.get(e.userID),e.nick=t,e.avatar=s)}),i})}_generateGroupMember(s){var n=[];for(let e=0,t=s.length;e<t;e++){var r=new vo(s[e]);n.push(r)}return n}},So=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(t){return S(this,void 0,void 0,function*(){let s="getGroupMemberProfile",{groupID:n,userIDList:r,memberCustomFieldFilter:i}=t,e=T.getLocalGroup(n),{helper:o,utils:{isArray:a}}=this._core;if(e&&Wi(e.type))throw new o.ChatError({functionName:s,replacement1:s,code:2687});50<r.length&&(console.warn(`${this._name}.${s} userIDList length:${r.length} exceeds limit 50`),r.splice(50));try{let e=yield function(r,i){return S(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:n}=r;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:n}})})}({groupID:n,userIDList:r,memberCustomFieldFilter:i,memberInfoFilter:[...Bi]},this._core),t=(console.log(this._name+`.${s} ok.`),e||{})["MemberList"];var l,u;return a(t)&&0!==t.length?(l=this._convertMemberInfo(t),l=yield this._getMemberAvatarAndNick(l),u=this._generateGroupMember(l),R({memberList:u})):R({memberList:[]})}catch(e){let t=new o.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}})}_convertMemberInfo(s){var n=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:r,JoinTime:i,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u}=s[e],r=Yi(r);n.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:r})}return n}_getMemberAvatarAndNick(i){return S(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}),n=(null==s?void 0:s.data)||[],r=new Map(n.map(e=>[e.userID,e]));return i.forEach(e=>{var t,s;r.has(e.userID)&&({nick:t="",avatar:s=""}=r.get(e.userID),e.nick=t,e.avatar=s)}),i})}_generateGroupMember(s){var n=[];for(let e=0,t=s.length;e<t;e++){var r=new vo(s[e]);n.push(r)}return n}},Eo=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(t){return S(this,void 0,void 0,function*(){let o="addGroupMember",{groupID:a,userIDList:e}=t,l=T.getLocalGroup(a),s=this._core["helper"];if(l&&Wi(l.type))throw new s.ChatError({functionName:o,code:2661});var u=e.map(e=>({Member_Account:e}));try{let e=yield function(s,n){return S(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:a,userIDList:u},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:n,existedUserIDList:r,overLimitUserIDList:i}=this._handleResult(t);return console.log(`${this._name}.${o} groupID:${a} ok, successUserIDList:${n} failureUserIDList:${s} existedUserIDList:${r} overLimitUserIDList:`+i),R({failureUserIDList:s,successUserIDList:n,existedUserIDList:r,overLimitUserIDList:i,group:l})}catch(e){let t=new s.ChatError({functionName:o,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${o} fail:`,t),t}})}_handleResult(e){let s=[],n=[],r=[],i=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;0===e?s.push(t):1===e?n.push(t):2===e?r.push(t):4===e&&i.push(t)}),{failureUserIDList:s,successUserIDList:n,existedUserIDList:r,overLimitUserIDList:i}}},Co=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(bi)})}deleteGroupMember(o){return S(this,void 0,void 0,function*(){let s="deleteGroupMember",{groupID:e,userIDList:t}=o,n=T.getLocalGroup(e),{helper:r,utils:{isUndefined:i}}=this._core;if(i(n))throw new r.ChatError({functionName:s,code:2603});20<t.length&&(console.warn(`${this._name}.${s} userIDList length:${t.length} exceeds limit 20`),t.splice(20));try{return yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=n;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:t},this._core),console.log(`${this._name}.${s} ok, groupID:${e} userIDList length:`+t.length),R({group:n,userIDList:t})}catch(e){let t=new r.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}})}},Mo=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return S(this,void 0,void 0,function*(){let n="setGroupMemberMuteTime",t=this._core["helper"];this._preCheckSettingMuteParams(o);try{yield fo(o,this._core);let{groupID:e,userID:t,muteTime:s}=o;console.log(`${this._name}.${n} ok, groupID:${e} userID:${t} muteTime:`+s);var r=T.getLocalGroup(e),i=new vo({userID:t,muteTime:s});return R({group:r,member:i})}catch(e){r=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:`,r),r}})}_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:2685})}},yo=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(o){return S(this,void 0,void 0,function*(){let n="setGroupMemberRole",t=this._core["helper"];this._preCheckSettingRoleParams(o);try{yield fo(o,this._core);let{groupID:e,userID:t,role:s}=o;console.log(`${this._name}.${n} ok, groupID:${e} userID:${t} role:`+s);var r=T.getLocalGroup(e),i=new vo({userID:t,role:s});return R({group:r,member:i})}catch(e){r=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:`,r),r}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:n,helper:r,OuterConstant:i,common:{isCommunity:o}}=this._core,a=T.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==i.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:2681});if(t===n.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:2684});a=[...Vi];if(o({groupID:e})&&a.push(i.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new r.ChatError({functionName:"setGroupMemberRole",code:2683})}},Oo=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(l){return S(this,void 0,void 0,function*(){let r="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:i}}=this._core;this._preCheckSettingNameCardParams(l);try{let{groupID:e,userID:t=i(),nameCard:s}=l,n={groupID:e,userID:t,nameCard:s};yield fo(n,this._core),console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} nameCard:`+s);var o=T.getLocalGroup(e),a=new vo({userID:t,nameCard:s});return R({group:o,member:a})}catch(e){let t=new s.ChatError({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${r} fail:`,t),t}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=T.getLocalGroup(e);if(Wi(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:2687})}},Ao=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(l){return S(this,void 0,void 0,function*(){let r="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:i}}=this._core;this._preCheckSettingCustomFiledParams(l);try{let{groupID:e,userID:t=i(),memberCustomField:s}=l,n={groupID:e,userID:t,memberCustomField:s};yield fo(n,this._core),console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} memberCustomField:`+JSON.stringify(s));var o=T.getLocalGroup(e),a=new vo({userID:t,memberCustomField:s});return R({group:o,member:a})}catch(e){let t=new s.ChatError({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${r} fail:`,t),t}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=T.getLocalGroup(e);if(Wi(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:2687})}},To=new class{init(e,t){console.log("GroupMember.init"),Io.init(e,t),So.init(e),Eo.init(e),Co.init(e,t),Mo.init(e),yo.init(e),Oo.init(e),Ao.init(e)}getGroupMemberList(e){return Io.getGroupMemberList(e)}deleteGroupMember(e){return Co.deleteGroupMember(e)}},Ro=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return S(this,void 0,void 0,function*(){var t="getGroupCounters";try{Ji(t,Pi);var e,s,n,{groupID:r,keyList:i=[]}=l,{avChatRoomKey:o,lastUpdateTime:a}=io.getLocalGroupCounters(r);return Date.now()-a>=this._getExpireTime()&&(e=yield function(r){return S(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=r,n=Ni.core["common"];return n.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:r,keyList:i,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:n}=e,io.updateLocalGroupCounters({groupID:r,counterList:s,groupCounterSeq:n})),{code:0,data:{counters:io.getLocalCounters(r,i)}}}catch(e){Qi(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)}},Do=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 S(this,void 0,void 0,function*(){return this._handleCounterOperation("Set",e)})}increaseGroupCounter(e){return S(this,void 0,void 0,function*(){return this._handleCounterOperation("Increase",e)})}decreaseGroupCounter(e){return S(this,void 0,void 0,function*(){return this._handleCounterOperation("Decrease",e)})}_handleCounterOperation(a,l){return S(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{Ji(t,Pi);var{groupID:e,key:s,value:n=0}=l,r=io.getLocalGroupCounters(e)["avChatRoomKey"],i="Set"===a?this._convertObjectToList(l.counters):[{Key:s,Value:n}],o=yield this._updateGroupCounters({groupID:e,counterList:i,avChatRoomKey:r,mode:a});return io.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){Qi(t,e)}})}_updateGroupCounters(i){return S(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:n}=i,r=Ni.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:n}})}(),{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}))}},Lo=new class{init(e){this._core=e,Ro.init(e),Do.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:n,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;0!==e&&2!==e||this._processAndNotifyCounterUpdate(n,t,s),1===e&&io.deleteLocalGroupCounters({groupID:n,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:n,notificationCenter:r}=this._core;io.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{r.emitOuterEvent(n.GROUP_COUNTER_UPDATED,{name:n.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){io.reset()}},No=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return S(this,void 0,void 0,function*(){let n="initGroupAttributes",{groupID:r,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a}=D.getGroupAttributesCache(r),l=D.convertKeyValueMapToList(i);try{let e=yield function(r,i){return S(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:n}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:n,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${n} ok. groupID:${r} serverMainSequence:`+t);var u=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:i[e],sequence:t}});return D.saveGroupAttributesCacheValuesCopy(r),D.refreshGroupAttributesCache({groupID:r,serverMainSequence:t,groupAttributeList:u,operation:1}),D.emitGroupAttributesUpdated(r),R({groupAttributes:i})}catch(e){let t=new this._core.helper.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,t),t}})}},bo=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return S(this,void 0,void 0,function*(){let n="setGroupAttributes",{groupID:r,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a,values:l}=D.getGroupAttributesCache(r),u=D.convertKeyValueMapToList(i).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=l.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(r,i){return S(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:n}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:n,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:a,groupAttributeList:u,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${n} ok. groupID:${r} serverMainSequence:`+t);var c=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:i[e],sequence:t}});return D.saveGroupAttributesCacheValuesCopy(r),D.refreshGroupAttributesCache({groupID:r,serverMainSequence:t,groupAttributeList:c,operation:2}),D.emitGroupAttributesUpdated(r),R({groupAttributes:i})}catch(e){let t=new this._core.helper.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,t),t}})}},Po=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(a){return S(this,void 0,void 0,function*(){let s="deleteGroupAttributes",{groupID:e,keyList:t=[]}=a;try{var{resultList:n,serverMainSequence:r,operation:i,groupAttributeList:o}=(0===t.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,t))||{};return console.log(`${this._name}.${s} ok. groupID:${e} operation: `+i),D.saveGroupAttributesCacheValuesCopy(e),D.refreshGroupAttributesCache({groupID:e,serverMainSequence:r,groupAttributeList:o,operation:i}),D.emitGroupAttributesUpdated(e),R({keyList:n})}catch(e){let t=new this._core.helper.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}})}_deleteGroupAttributes(o,a){return S(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=D.getGroupAttributesCache(o),n=[],r=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},r.push({key:e,seq:t}),n.push(e))});var i=((yield function(r,i){return S(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:n}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:n,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:r,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:n,serverMainSequence:i,groupAttributeList:r,operation:4}})}_clearGroupAttributes(n){return S(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=D.getGroupAttributesCache(n),s=[...s.keys()],t=((yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=n;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:3}})}},wo=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(c){return S(this,void 0,void 0,function*(){let n="getGroupAttributes",r=c["groupID"],{avChatRoomKey:i,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=D.getGroupAttributesCache(r),{ssoLog:o,helper:{ChatError:a}}=this._core,l=o.createSSOLogData({method:"getGroupAttributes"});if(l.setLogInfo({message:`groupID:${r} localMainSequence:${t} serverMainSequence:${s} keyList:`+c.keyList}),3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:r,avChatRoomKey:i}),t=D.getGroupAttributesCacheValues(c),{serverGroupAttributeList:s=[]}=e||{};return l.setLogInfo({moreMessage:"from server, count:"+s.length}).end(),console.log(this._name+`.${n} from server. groupID:`+r),R({groupAttributes:t})}catch(e){let t=new a({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw l.setError(t).end(),console.error(this._name+`.${n} fail:`,t),t}var u=D.getGroupAttributesCacheValues(c);return l.setLogInfo({moreMessage:"from cache."}).end(),console.log(this._name+`.${n} from cache. groupID:`+r),R({groupAttributes:u})})}getGroupAttributesFromServer(r){return S(this,void 0,void 0,function*(){var e=this._core["utils"]["isUndefined"],{groupID:t,avChatRoomKey:s}=r,{AttrMainSeq:e=0,GroupAttrAry:s}=(yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=n;return r.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:t,avChatRoomKey:s,groupType:e(s)?0:1},this._core))||{},n=(console.log(this._name+`._getGroupAttributesFromServer ok. groupID:${t} serverMainSequence:`+e),s.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return D.refreshGroupAttributesCache({groupID:t,serverMainSequence:e,groupAttributeList:n,operation:5}),{serverGroupAttributeList:s}})}},Go=new class{init(e){console.log("GroupAttribute.init"),No.init(e),bo.init(e),Po.init(e),wo.init(e),D.init(e)}isGroupAttributesUpdated(e){return D.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,n=s["groupAttributeOption"],{serverMainSequence:r,withChangedAttributeInfo:i}=n,o=D.getGroupAttributesCache(t)["localMainSequence"],a=r-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:`+a),0!=a)if(D.saveGroupAttributesCacheValuesCopy(t),1!==i||1!=a){if(D.hasGroupAttributesCache(t)){let e=D.getGroupAttributesCache(t)["avChatRoomKey"];wo.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{D.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else D.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:n})}reset(){D.reset()}};function Uo(e,t="tips"){let{ClientSeq:s,From_Account:n,MsgClientTime:r,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:n,MsgFrom_AccountExtraInfo:r,From_Account:i,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:n,messageFromAccountExtraInformation:r,from:i,to:o}}();return{clientSequence:s,from:n,clientTime:r,priority:i,random:o,sequence:a,time:l,tinyID:u,to:c,groupProfile:g,elements:("tips"===t?ko:qo)(h)}}function ko(n){let e={};return Object.keys(n).forEach(s=>{switch(s){case"MemberNum":e.memberCount=n[s];break;case"OpType":e.operationType=n[s];break;case"Operator_Account":e.operatorID=n[s];break;case"List_Account":e.userIDList=n[s];break;case"MsgMemberExtraInfo":e.memberInfoList=n[s].map(e=>Fo(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=Fo(n[s]);break;case"MsgGroupNewInfo":e.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:n,GroupAttrInfo:r}=o[i];return{changedKeyList:e,groupAttributeList:r.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:n}}()}}),e}(n[s]);break;case"MsgMemberInfo":e.msgMemberInfo=n[s].map(e=>{var{ShutupTime:e,User_Account:t}=e;return{muteTime:e,userID:t}});break;case"OnlineMemberInfo":e.onlineMemberInfo=function(){var{ExpireTime:e,OnlineMemberNum:t}=n[s];return{expireTime:e,onlineMemberNum:t}}();break;case"GroupCounterInfo":e.groupCounterInfo=n[s].map(e=>{var{GroupCounterSeq:e,GroupCounter:t,Type:s}=e;return{type:s,groupCounterSeq:e,counterList:t}})}}),e}function Fo(e){var{ImageUrl:e,NickName:t,Role:s,UserId:n}=e;return{avatar:e,nick:t,role:s,userID:n}}function qo(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 xo{constructor(e){this.type=Ni.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=ko(e);return new xo(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 n=s[e];ji[n]&&(this.content.groupProfile[n]=t[n])}}_initOperatorInfo(t){this.content.operatorInfo={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var n=s[e];this.content.operatorInfo[n]=t[n]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach(t=>{e.forEach(e=>{t.userID===e.userID&&Object.assign(t,e)})}):this.content.memberList=e}_initNewGroupProfile(t){this.content.newGroupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var n=s[e];"muteAllMembers"!==n?this.content.newGroupProfile[n]=t[n]:this.content.newGroupProfile.muteAllMembers=1===t.muteAllMembers}}}var Vo=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=this._core=e,{message:{messageFactory:e},OuterConstant:r}=e;null!=e&&e.registerElementClass(r.MSG_GRP_TIP,xo),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this)}onNewGroupTips(e){let{messageList:t,conversationUpdateFieldList:s}=this._handleGroupTips(e),{notificationCenter:n,OuterEvent:r,appStore:{conversationStore:i}}=this._core;null!=s&&s.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:n=0}=i.getConversation(e)||{};i.updateConversation(e,{lastMessage:t,unreadCount:s+n})}),0<t.length&&(n.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:t}),this._handleGroupTipMessage(t))}_handleGroupTips(e,s=!0){let{Event:n,GroupTips:r}=e,i=new Map,t=[],o=[];for(let t=0,e=r.length;t<e;t++){let e=Uo(r[t],"tips");if(6===n){if(Go.isGroupAttributesUpdated(e)){Go.handleGroupAttributesUpdated(e);continue}if(Lo.isGroupCounterUpdated(e)){Lo.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(T.hasLocalGroup(a)){a=this._assembleMessage(e);if(6===n&&(a._onlineOnlyFlag=!0,o.push(a)),4===n){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 xo(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:n}}=this._core,{operationType:r,memberInfoList:i,operatorInfo:o}=e,a={};if(t(i)?t(o)||(a=o):r!==n.JOINED&&r!==n.KICKED&&r!==n.ADMIN_SET&&r!==n.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:n}}=this._core,{conversationID:r,conversationType:i}=t;let o;if(e.has(r))o=e.get(r),"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:r,unreadCount:e,type:i,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}n(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(r,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:n,operatorInfo:r}=e.payload,i=n.groupID,o=T.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(r)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==r.userID||Object.keys(r).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:r[e]}),"role"===e&&this._updateSelfRole(o,r[e])}),T.emitGroupListUpdate(),T.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:n}=this._core,e=T.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:n.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let n=s.GRP_MBR_ROLE_MEMBER;400===t?n=s.GRP_MBR_ROLE_OWNER:300===t&&(n=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:n})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=T.getLocalGroup(t),n=this._core["utils"]["isNumber"];s&&n(e)&&s.memberCount!==e&&(s.memberCount=e,T.emitGroupListUpdate(),T.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 Bo{constructor(e){this.type=Ni.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=qo(e);return new Bo(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 n=s[e];Ki[n]&&(this.content.groupProfile[n]=t[n])}}}var jo=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,Bo)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(console.log(`${this._name}.onNewGroupSystemNotification count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:n,OuterEvent:r}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&n.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var n=[];let r={};for(let e=0;e<t.length;e++){var i=Uo(t[e],"system"),o=i["elements"]["operationType"];15!==o&&(o=this._assembleMessage(i),this._core.message.messageDataHandler.storeConversationMessage(o))&&(n.push(o),r=this._handleConversationOptions(o,s))}return r.lastMessage=n[n.length-1],{conversationUpdateFieldList:0<n.length?[r]:[],messageList:n}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:n}}=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 Bo(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=n(),s.random=n(),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 2:this._handleGroupJoinResult(e);break;case 4:this._handleMemberKicked(e);break;case 5:this._handleGroupDismissed(e);break;case 7:this._handleGroupInvitedResult(e);break;case 8:this._handleGroupQuitResult(e);break;case 20:this._handleMessageRemindTypeSynced(e);break;case 21:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,n=T.hasLocalGroup(t);console.log(this._name+`._handleGroupJoinResult groupID:${t} type:${s} hasLocalGroup:`+n),n||Wi(s)||(T.updateLocalGroup([Object.assign({},e)]),T.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];T.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];T.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=T.hasLocalGroup(e);console.log(this._name+`._handleGroupInvitedResult groupID:${e} hasLocalGroup:`+t),t||ro.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];T.updateLocalGroup([Object.assign({},e)]),T.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=T.hasLocalGroup(e);console.log(this._name+`._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(Wi(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}T.deleteLocalGroup(s),T.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:n}}=this._core,n=""+n+e;s.getConversation(n)&&s.updateConversation(n,t)}},Ko=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),Vo.init(e),jo.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){Vo.onNewGroupTips(e)}_onNewGroupSystemNotification(e){jo.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 L={required:!0,rules:["string"],allowEmpty:!1},Ho={required:!0,rules:["number"],allowEmpty:!1},Wo={required:!0,rules:["array"],allowEmpty:!1},$o={required:!0,rules:["object"],allowEmpty:!1},Yo={createGroup:{name:L,type:L},dismissGroup:[Object.assign({key:"groupID"},L)],joinGroup:{groupID:L,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},L)],searchGroupByID:[Object.assign({key:"groupID"},L)],getGroupProfile:{groupID:L,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:L,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:L,newOwnerID:L},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},L)],handleGroupApplication:{handleAction:L},getGroupMemberList:{groupID:L},getGroupMemberProfile:{groupID:L,userIDList:Wo,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:L,userIDList:Wo},deleteGroupMember:{groupID:L,userIDList:Wo},setGroupMemberMuteTime:{groupID:L,userID:L,muteTime:Object.assign(Object.assign({},Ho),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:L,userID:L,role:L},setGroupMemberNameCard:{groupID:L,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:L},setGroupMemberCustomField:{groupID:L,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Wo},markGroupMemberList:{groupID:L,markType:Object.assign(Object.assign({},Ho),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Wo},initGroupAttributes:{groupID:L,groupAttributes:$o},setGroupAttributes:{groupID:L,groupAttributes:$o},deleteGroupAttributes:{groupID:L,keyList:Object.assign(Object.assign({},Wo),{allowEmpty:!0})},getGroupAttributes:{groupID:L,keyList:Object.assign(Object.assign({},Wo),{allowEmpty:!0})},getGroupCounters:{groupID:L,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:L,counters:$o},increaseGroupCounter:{groupID:L,key:L,value:Ho},decreaseGroupCounter:{groupID:L,key:L,value:Ho}},zo={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},Jo=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=T,this.groupAction=go,this.groupAttribute=Go,this.groupMember=To,this.name="Group"}install(e,t=[]){this._core=e,Ni.init(e),T.init(e),go.init(e,this),To.init(e,this),mo.init(e),Lo.init(e),Go.init(e),Ko.init(e),e.helper.registerValidateConfig({auth:zo,params:Yo}),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(){T.reset(),Go.reset(),Lo.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)}},Qo=new class{init(e){this.core=e}},Xo={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},Zo={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21};class ea{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:n,onSuccess:r,onFail:i}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=n,this._onSuccess=r,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 S(this,void 0,void 0,function*(){try{var e=yield function(r,i){return S(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:n}=r;return i.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:n,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 ta{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 sa=e=>e===Xo.GROUP_TIPS_HAS_NO_ROAMING||e===Xo.GROUP_TIPS_HAS_ROAMING,na=e=>e===Xo.GROUP_SYSTEM_MESSAGE;function ra(g){var e,t,s,n,r,i,o,a=function(){var{E:e,MCT:t,MR:s,MP:n,MTS:r,GId:i,MS:o,CCD:a,F_Account:l,IsSys:u,GInf:c,MsgBody:d}=g,h=I(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:n,MsgTimeStamp:r,ToGroupId:i,MsgSeq:o,CloudCustomData:a,From_Account:l,IsSystemMsg:u,GroupInfo:function(e){var e=e||{},{GN:t,GT:s,F_Hd:n,F_NN:r,F_Ll:i}=e,e=I(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return n&&(t.From_AccountHeadurl=n),r&&(t.From_AccountNick=r),i&&(t.From_AccountLevel=i),t}(c),MsgBody:function(e){let t=e,s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:n,RT:r,UDF:i,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:l}=e,e=I(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:n,ReportType:r,UserDefinedField:i},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=I(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=l.map(e=>{var{Img:t,NN:s}=e,e=I(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]}(d)},h)}(),l=a,u=l["Event"];if((sa(u)||na(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===Xo.BROADCAST_MESSAGE||u===Xo.NORMAL_MESSAGE){var c=l;let e=Qo["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 sa(u)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:n,List_Account:r,OpType:i}=(c=l).MsgBody||{},"number"==typeof e||1!==i&&2!==i||(c.MsgBody.GroupJoinType=2===i?0:1),s||(c.MsgBody.MsgMemberExtraInfo=r.map(e=>({UserId:e}))),1!==i||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:n,ImageUrl:"",NickName:""},t)),na(u)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:r}=(o=l).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:r,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}var ia=new class{constructor(){this._name="MessageParser",this._sequenceList=new ta(200),this._messageIDList=new ta(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(r,e,i=!1){this._sortServerMessageList({groupID:r,serverMessageList:e,isHistoryMessage:i});var o=this._handleMessageList(r,e);if(0!==o.length){if(!i){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=Qo["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+r,{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:n}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:n,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let n=[];n=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:${n.length} sequenceList:`+n),n.length=0}_handleMessageList(s,n){var r,i,{messageDataHandler:o,messageHelper:a}=this._core["message"],l=this._avChatRoomHandler.isPollingSimplifiedMessage(),u=[],e=n.length;for(let t=0;t<e;t++){let e=n[t];if(l&&(e=ra(e)),na(e.Event)&&Object.values(Zo).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),r=a.parseServerGroupMessage(e),(i=this._createMessage(r)).level=e.GroupInfo.From_AccountLevel,sa(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(r)?this._avChatRoomHandler.handleGroupAttributesUpdated(r):null===this._filterDuplicateMessage(i)||o.isMessageSentByCurrentInstance(i)||(1===r.isModified&&(i.isModified=!0),sa(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(i)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];sa(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),na(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(Xo).includes(t)?t===Xo.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===Xo.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===Xo.MESSAGE_REACTION?null:e:(console.warn(this._name+".onMessageReceived unknown event:"+t),null)}_createMessage(e){var{message:{messageFactory:t},OuterConstant:s}=this._core;let n=s.CONV_GROUP;e.event===Xo.GROUP_SYSTEM_MESSAGE&&(n=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:n,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:r,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:n}=e,e={conversationID:""+r.CONV_GROUP+i,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:n};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:n,MsgBody:r}=e,r=(null==r?void 0:r.MsgContent)||"";this._emitEvent({name:t,data:r}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${n} data:`+r)}_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.createSSOLogData({method:"MessageStacked"}).setLogInfo({message:`count:${t} groupID:`+e.join(",")}).end(),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(s){var{message:{messageHelper:n},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,r=this._avChatRoomHandler.isPollingSimplifiedMessage(),i=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];r&&(e=ra(e));var a=n.parseServerGroupMessage(e);Object.values(Xo).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:n}}=t;if(!s(n)){var{OnlineMemberNum:n=0,ExpireTime:r=60}=n,i=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:i,memberCount:n,expireTime:r}:(e.latestUpdateTime=i,e.memberCount=n),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let oa=e=>{var{store:t}=Qo["core"];return(t.get("cloudConfig")||{})[e]},aa=e=>{var{utils:{isUndefined:t}}=Qo["core"];return!t(e)},la=()=>{var e=oa("polling_interval");return aa(e)?parseInt(e,10):300},ua=()=>{var e=oa("polling_simplified_msg");return aa(e)?parseInt(e,10):0};var ca,da=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,ia.init(e,this),console.log("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:n,GroupInfo:{GroupId:r,GroupType:i}}=s[e],n=Object.values(Zo).includes(n.ReportType);i===t&&n&&this.reset(r)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||la()}isPollingSimplifiedMessage(){return 0!==ua()}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 S(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:n}=this._core,{longPollingKey:r,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&&ia.onMessageReceived(a,o,!0),e(r)?{status:n.JOIN_STATUS_SUCCESS,group:i}:this.startMessageLongPolling(l)})}_preCheck(r){return S(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:n}}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=oa("polling_count_limit"),aa(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:2688,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&r.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 n(t)}catch(e){console.log(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:n}=e,r=n["groupID"];return this._pollingRequestInfoMap.set(r,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(r,la()),this._startPolling(r),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:n}}_startPolling(t){if(console.log(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 ea({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:ua()}:{longPollingKey:t,startSequence:s,simplifiedMessage:ua()}}_handleSuccess(s,e){var n=e["ErrorCode"];if(0===n)this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,e);else{let{longPollingKey:e,startSequence:t}=this._pollingRequestInfoMap.get(s)||{};console.warn(`${this._name}._handleSuccess groupID:${s} key:${e} startSeq:${t} errorCode:`+n)}}_handleResponseData(t,e){var{Key:e,NextSeq:s,NextBroadcastSeq:n,RspMsgList:r=[],RspBroadcastMsgList:i=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),n&&n>this._startBroadcastSequence&&(this._startBroadcastSequence=n),0<r.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,la())),ia.onMessageReceived(t,r);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=oa("polling_no_msg_count"),aa(s)?parseInt(s,10):20)){let e=la()+(n=oa("polling_interval_plus"),aa(n)?parseInt(n,10):2e3);this._pollingIntervalMap.set(t,e)}}0<i.length&&ia.onBroadcastMessageReceived(i)}_handleFailure(e,t){console.warn(this._name+`._handleFailure groupID:${e} error:`,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){ia.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,n,r;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:n,count:r}=(()=>{var e=oa("av_members_freq_limit");if(aa(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*n)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),r<s)}_stopPolling(e){var t,s;if(e)console.log(this._name+"._stopPolling groupID:"+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{console.log(this._name+"._stopPolling all.");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,n=e.isUnlimitedAVChatRoom()?1:0,r=[],i=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?i:r).push(e)}),t.createSSOLogData({method:"longPollingCount"}).setLogInfo({message:o,moreMessage:`av:${r.join(",")} live:`+i.join(","),eventType:29,code:n}).end()}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,ia.reset()}},ha=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(r){return S(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(r),{status:s,group:{type:n}}=t["data"];return n!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:da.handleJoinGroupResult(t.data)})}},ga=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(n){return S(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(n),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&da.reset(n),t})}},pa=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(n){return S(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(n),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&da.reset(n),t})}},_a=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(r){return S(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,n=r["groupID"],e=e.getGroup(n);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits("AV_MBR_LIST")){if(da.isOverFrequencyLimit(n))throw{code:2996,message:"Over frequency limit: get_members-"+n};return this._getGroupMemberList(r)}return this._parentPlugin.groupMember.getGroupMemberList(r)})}_getGroupMemberList(i){return S(this,void 0,void 0,function*(){let r="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,n){return S(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return n.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(i,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},n=this._handleMemberList(t);return console.log(`${this._name}.${r} ok, groupID:${i.groupID} count:${n.length} nextOffset:`+s),{code:0,data:{memberList:n,offset:s}}}catch(e){var s=new t.ChatError({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${r} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:n="",JoinTime:r=0,Marks:i=[]}=e;return{userID:e,nick:t,avatar:s,remark:n,joinTime:r,marks:i,isOnline:!0}})}},ma=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 S(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(n){return S(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=da.getLocalOnlineMemberCount(n);if(e(s)||this._isExpired(n)){let{memberCount:e=0}=yield this._getOnlineMemberCountFromServer(n);return console.log(`${this._name}.${t} ok, groupID:${n} memberCount:${e} from server.`),{code:0,data:{memberCount:e}}}return console.log(`${this._name}.${t} ok, groupID:${n} memberCount:${s.memberCount} from local.`),{code:0,data:{memberCount:s.memberCount}}})}_isExpired(e){var e=da.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,n=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&n&&t}_getOnlineMemberCountFromServer(i){return S(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return S(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=60}=e||{},n=Date.now(),r={lastSyncTime:n,latestUpdateTime:n,lastReqTime:n,memberCount:t,expireTime:s};return da.updateLocalOnlineMemberCount(i,r),{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}})}},va=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 S(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:n,OuterConstant:r}=this._core,i=o["groupID"],t=t.getGroup(i);if(s(t))throw new n.ChatError({functionName:e,code:2603});if(t.type!==r.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(n.checkBusinessCapabilityBits("AV_BAN_MBR"))return this._deleteGroupMember(o);throw new n.ChatError({functionName:e,code:3122})})}_deleteGroupMember(o){return S(this,void 0,void 0,function*(){let s="_deleteGroupMember",{appStore:{groupStore:e},helper:n}=this._core,{groupID:t,duration:r=0,userIDList:i}=o;if(0===r)throw new n.ChatError({functionName:s,code:2686});try{return yield function(r,i){return S(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:n}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:n}})})}(o,this._core),console.log(this._name+`.${s} ok, groupID:`+t),{code:0,data:{group:e.getGroup(t),userIDList:i}}}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}})}},fa=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return S(this,void 0,void 0,function*(){let r="markGroupMemberList",{groupID:i,markType:o,enableMark:a,userIDList:l=[]}=e,u=this._generateRequestData(e);try{let e=yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=n;return r.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:n}=this._handleResult(t,l);return console.log(`${this._name}.${r} ok, groupID:${i} markType:${o} enableMark:${a} success:${s.length} fail:`+n.length),{code:0,data:{successUserIDList:s,failureUserIDList:n}}}catch(e){let t=new this._core.helper.ChatError({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${r} fail:`,t),t}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:n,userIDList:r=[]}=e,i=!0===n?1:2,o=[...r];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=[],n=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:n).push(t)}),{successUserIDList:s,failureUserIDList:n}}},Ia=new class{init(e,t){console.log("AVChatRoomAction.init"),ha.init(e,t),ga.init(e,t),pa.init(e,t),_a.init(e,t),ma.init(e,t),va.init(e,t),fa.init(e)}},Sa=new class{constructor(){this._name="LiveHandler"}init(e){e=(this._core=e).helper;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),console.log("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:n}=this._core,{groupID:e,longPollingKey:r,longPollingSequence:i=1}=e;if(s(r))return console.warn(this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});da.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=da.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),console.log(this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${r} longPollingSequence:`+i),s={groupID:e,type:n.GRP_LIVE};return da.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:r,startSequence:i}),da.startMessageLongPolling({group:s,longPollingKey:r,startSequence:i})}stopMessageLongPolling(e){e=e.groupID;return da.reset(e),console.log(this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(n){return S(this,void 0,void 0,function*(){var t=n["groupID"];try{var e=yield function(n,r){return S(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=n;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(n,this._core),{RspMsgList:s=[]}=e||{};console.log(this._name+`._getLiveHistoryMessages ok, groupID:${t} count:`+s.length),0<s.length&&da.handleLiveHistoryMessages(t,s)}catch(e){console.log(this._name+`._getLiveHistoryMessages failed, groupID:${t} info:`,e)}})}},Ea=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,Qo.init(e),da.init(e,t),Ia.init(e,t),Sa.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){da.onAVChatRoomSystemNotification(e)}_reset(){da.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 Ca=new class{init(e){this.core=e}},Ma="message",ya="user",Oa={OR:"or",AND:"and"},Aa={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},Ta={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Oa.OR,Oa.AND].includes(e)||"keywordListMatchType should be OR or AND"},Ra={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},Da={required:!1,rules:["string"],allowEmpty:!0},La={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=Ca.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 n=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){n=!0;break}return!n||"groupTypeList should be supported group type"}},Na={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=Ca.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 n=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){n=!0;break}return!n||"messageTypeList should be supported message type"}},ba={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Ca.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Pa=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),wa={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Ca.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Ga={searchCloudMessages:{keywordList:Aa,keywordListMatchType:Ta,cursor:Da,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Na,conversationID:ba,timePosition:Pa("timePosition"),timePeriod:Pa("timePeriod")},searchCloudUsers:{keywordList:Aa,keywordListMatchType:Ta,cursor:Da,count:Ra,miniBirthday:Pa("miniBirthday"),maxBirthday:Pa("maxBirthday"),gender:wa},searchCloudGroupMembers:{keywordList:Aa,keywordListMatchType:Ta,cursor:Da,count:Ra,groupTypeList:La,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Aa,keywordListMatchType:Ta,cursor:Da,count:Ra,groupTypeList:La}},Ua={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0},ka=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,Ca.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:Ua,params:Ga})}searchCloudMessages(v){return S(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a,ssoLog:e}=this._core,t=e.createSSOLogData({method:"searchCloudMessages"}),{conversationID:s,timePeriod:n,timePosition:r}=v,i=I(v,["conversationID","timePeriod","timePosition"]),l=Object.assign({count:100},i);s&&(s.startsWith(o.CONV_C2C)?l.account=s.replace(o.CONV_C2C,""):s.startsWith(o.CONV_GROUP)&&(l.groupID=s.replace(o.CONV_GROUP,""))),this._setTimeRangeParams(l,{timePeriod:n,timePosition:r});var u=yield function(c){return S(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:n,messageTypeList:r,endTime:i,startTime:o,cursor:a,account:l,groupID:u}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:n,MsgTypeList:r,EndTime:i,StartTime:o,Cursor:a,PeerAccount:l,GroupID:u};return Ca.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(l);if(!u)return{code:0,data:{}};var{ErrorCode:c,ErrorInfo:d,TotalCount:h,Cursor:g="",ConversationMsgs:p=[]}=u;if(0!==c)throw{errorCode:c,errorInfo:d};var _=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} res: totalCount:`+h,m=(t.setLogInfo({message:_}).end(),p.map(e=>{let{MsgList:t,Count:s,GroupID:r,UserID:n}=e,i=r?""+o.CONV_GROUP+r:""+o.CONV_C2C+n;return this._isSearchingAllConversations(v)&&1<s?{conversationID:i,messageCount:s,messageList:[]}:{conversationID:i,messageCount:s,messageList:t.map(e=>{return a.isEmpty(r)?(t=this._core,s=t.OuterConstant.CONV_C2C,n=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}))).setElement(n.elements),t):(s=this._core,n=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:n,flow:"in"}))).setElement(t.elements),s);var t,s,n})}}));return{code:0,data:{searchResultList:m,cursor:g,totalCount:h}}}catch(e){var{errorCode:u,errorInfo:c}=e||{};this._handleError({errorCode:u,errorInfo:c,searchType:Ma,functionName:"searchCloudMessages"})}})}searchCloudUsers(f){return S(this,void 0,void 0,function*(){var s;try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:t,count:n=20}=f,r=I(f,["keywordListMatchType","count"]),i=Object.assign({count:n,keywordListMatchType:t===Oa.AND?1:0},r),o=(this._setBirthdayRangeParams(i,f),yield function(a){return S(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:n,maxBirthday:r,cursor:i,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,UserBirthStart:n,UserBirthEnd:r,Gender:o};return Ca.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(i));if(!o)return{error:0,data:{}};var{ErrorCode:a,ErrorInfo:l,TotalCount:u,Cursor:c="",Users:d=[]}=o;if(0!==a)throw{errorCode:a,errorInfo:l};var h=`keywordList:${f.keywordList} keywordListMatchType:${f.keywordListMatchType} cursor:${f.cursor} count:${f.count} res: totalCount:`+u,g=(e.setLogInfo({message:h}).end(),[]);for(let e=0,t=d.length;e<t;e++){var p,_,{UserID:m,ProfileItems:v}=d[e];m!==this._core.OuterConstant.USER_NOT_FOUND&&""!==m&&(p=v.map(e=>({tag:e.Tag,value:e.StrValue})),_=null==(s=this._core.user.userProfile)?void 0:s.createProfile(m,p),g.push(_))}return{code:0,data:{searchResultList:g,cursor:c,totalCount:u}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ya,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(h){return S(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:t=20,keywordListMatchType:s}=h,n=I(h,["count","keywordListMatchType"]),r=yield function(o){return S(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:n,cursor:r,groupIDList:i}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:r,GroupType:n,GroupIdList:i};return Ca.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Oa.AND?1:0},n));if(!r)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:o,GroupMembers:a=[],Cursor:u,TotalCount:c}=r;if(0!==i)throw{errorCode:i,errorInfo:o};var d=`keywordList:${h.keywordList} keywordListMatchType:${h.keywordListMatchType} cursor:${h.cursor} count:${h.count} res: totalCount:`+c;e.setLogInfo({message:d}).end();let l=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:n,GroupMemberUserName:r,GroupMemberUserID:i,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:n},s={userID:i,nick:r,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}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ya,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(d){return S(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:t=20,keywordListMatchType:s}=d,n=I(d,["count","keywordListMatchType"]),r=yield function(i){return S(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:n,cursor:r}=i,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:r,GroupType:n};return Ca.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Oa.AND?1:0},n));if(!r)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:o,Groups:a,Cursor:l,TotalCount:u}=r;if(0!==i)throw{errorCode:i,errorInfo:o};var c=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+u;return e.setLogInfo({message:c}).end(),{code:0,data:{searchResultList:(null==a?void 0:a.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:n,GroupName:r,GroupOwnerTinyID:i,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:l,GroupAddOption:u,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:n,name:r,ownerTinyID:i,ownerID:o,ownerNick:a,type:l,joinOption:u,inviteOption:c}}))||[],cursor:l,totalCount:u}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ya,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,functionName:n}){var{ssoLog:r,helper:i}=this._core;let o=e;60020===e?o="SearchUnable":s!==Ma&&27003===e?o="SearchParamsError":s!==Ma&&60018===e&&(o="SearchOverLimit");s=new i.ChatError({code:o,message:t});throw r.getSSOLogData(n).setError(s).end(),s}_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 Fa(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let qa="qualityStat",xa="im-ssolog-quality-stat",Va=(ca=ca||{},ca[ca.ONLINE=8]="ONLINE","networkRTT"),Ba="messageE2EDelay",ja="sendMessageC2C",Ka="sendMessageGroup",Ha="sendMessageGroupAV",Wa="sendMessageRichMedia",$a="cosUpload",Ya="messageReceivedGroup",za="messageReceivedGroupAVPush",Ja="messageReceivedGroupAVPull",Qa={networkRTT:2,messageE2EDelay:3,sendMessageC2C:4,sendMessageGroup:5,sendMessageGroupAV:6,sendMessageRichMedia:7,messageReceivedGroup:8,messageReceivedGroupAVPush:9,messageReceivedGroupAVPull:10,cosUpload:11},Xa=[ja,Ka,Ha,Wa,$a],Za=[Ya,za,Ja],el=[Va,Ba,ja,Ka,Ha,Wa,$a,Ya,za,Ja],tl={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},sl="quality_stat";var nl=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(tl))}init(e){this._core=e,Object.values(Xa).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:n}=e,r=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case r.TOTAL_COUNT:this._handleTotalCount(t);break;case r.SUCCESS_COUNT:this._handleSuccessCount(t);break;case r.FAILED_COUNT:this._handleFailedCount(t,s);break;case r.SEND_COST:this._handleSendCost(t,n)}}getStatResult(e){var t,s,n,r,i,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:r}=o,n=Fa(s/t*100,2),i=Fa((r=s+r)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:n,success_count_platform:r,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:n,MSG_FILE:r,CONV_C2C:i,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,n,r].includes(s.type))return Wa;if(s.conversationType===i)return ja;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?Ha:Ka}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===$a?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)}},rl=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:n}}=this._core;s(t)||!this._currentCycleStats.has(t)?console.warn(qa+".addMessageSequence invalid key:",t):({conversationID:s,sequence:e}=e,s=s.replace(n,""),0!==(n=this._lastCycleStats.get(t)).size&&n.has(s)&&e>(n=n.get(s)).minSeq&&e<n.maxSeq?this._insertToLastCycle(e,n):this._addToCurrentCycle(t,s,e))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let n=0,r=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(r+=e.length,n+=s-t+1)}),0===n?null:(this._transferCycleDataOptimized(e),{total_count:n,success_count_business:r,percent_business:Fa(r/n*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(Za).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 n=new Map;t.forEach((e,t)=>{var s=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;n.set(t,{sortedSequences:s,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,n),this._currentCycleStats.set(e,new Map)}}_getReceivedMessageSpecifiedKey(s){let{CONV_GROUP:e,GRP_AVCHATROOM:n}=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===n?Ja:Ya):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,n=e.length-1;for(;s<=n;){var r=Math.floor((s+n)/2);if(e[r]===t)return r;e[r]<t?s=r+1:n=r-1}return s}_addToCurrentCycle(e,t,s){let n=this._currentCycleStats.get(e).get(t);n?(n.sortedSequences.push(s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s),n.dirty=!0):(n={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,n))}},il=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:n}=this._core["OuterConstant"],r=[s,n];t.forEach(e=>{!r.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Fa(this._totalDelay/e,1)}_calculatePercentage(e,t){return Fa(e/t*100,2)}},ol=new class{init(e){this.core=e}},i=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:n,LOGOUT:r,DESTROY:i},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;ol.init(e),nl.init(e),rl.init(e),il.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(n,this._handleQualityStat,this),s.subscribeInnerEvent(r,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){console.log(qa+".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:sl,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...el.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&&nl.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:Qa[e],timestamp:Date.now(),network_type:ca.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case Ba:return il.getStatResult();case ja:case Ka:case Ha:case Wa:case $a:return nl.getStatResult(e);case Ya:case za:case Ja:return rl.getStatResult(e);default:return null}}_uploadQualityReports(t){return S(this,void 0,void 0,function*(){try{var n={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=ol.core,s="imopenstat.tim_web_report_v2",e=e.generateSSOLogProtocolData({servcmd:s,data:n}),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=qa+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(xa)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(xa,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(sl)}_dispose(){var{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:n}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(n,this._dispose,this),this._reset(),il.dispose(),rl.dispose()}};let al=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n,InnerEvent:r}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(r.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:n}}=this._core;if(n(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return S(this,void 0,void 0,function*(){let r=this._core["OuterConstant"],i=[],o=[];return yield Promise.all(null==e?void 0:e.map(n=>S(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=n,e=""+r.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(r.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:i,groupTipList:o}})}_recoverHistoryForConversation(e){return S(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:S,serverLastMessageSequence:E,groupTipList:C}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:n,OuterConstant:r,notificationCenter:i,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:r.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===r.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(n.MESSAGE_RECEIVED,{name:n.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){console.debug("Recovery failed for conversation:",I,S)}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],n=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of n)if(!t.startsWith("C2C")){let e=Array.from(s.values());var r;0<(null==e?void 0:e.length)&&(r=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,r))}}_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&&1<=t&&t<300}},ll,ul;ll=ss.STANDARD,ul=[t,sn,e,m,hn,i,al,pr,ni,Li,Jo,Ea,ka,Tn];var cl=Object.freeze({__proto__:null,ChatError:_,WorkflowManager:g,buildAndSendPacket:ks,get builtInPlugins(){return ul},checkBusinessCapabilityBits:Ns,deepMerge:Bs,getCurrentUserID:p,getErrorMessage:Es,getMessagePreviewText:js,isC2CConv:e=>Y(e)&&e.slice(0,3)===Yt.CONV_C2C,isCommunity:Ps,isGroupConv:e=>Y(e)&&e.slice(0,5)===Yt.CONV_GROUP,isTopic:ws,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=k.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:bs,registerInterceptor:Ds,registerValidateConfig:Ls,requireAuth:Cs,get sdkEdition(){return ll},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:n,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:i}=C;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:r}=C,{groupID:i,sequence:o}=t,a=!1;return Ps({groupID:i})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(n)&&(e.atTypeArray=[r]),e.atTypeArray.includes(n)&&t.groupAtType.includes(s)&&(e.atTypeArray=[r],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(n)&&e.includes(r)&&(e=[i]);n={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(n)}},validateAndExecute:Rs,validateParameters:Ms});class dl{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return dl._instance||(dl._instance=new dl),dl._instance}static setInstance(e){dl._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 n=(s=J(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),r=-1<n?s.splice(n,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&Gt(e.install)?(t.add(e.name),Gt(e.getInstalledSubPlugins)?e.install(P.getInstance().exposeApiForPlugin(),r):e.install(P.getInstance().exposeApiForPlugin()),Gt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Gt(e)?(t.add(e.name),e(P.getInstance().exposeApiForPlugin()),Gt(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=k.store.get("login"))?void 0:e.isLoggedIn)}}var F,hl,gl,N,b,pl,_l=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:n,needSort:r}=s,i=this._conversationMap.get(e);i&&!He(t)&&(Object.keys(t).forEach(e=>{i[e]=t[e]}),n)&&k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED,{needSort:r})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED))}},ml=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&&!He(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},vl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let n,{operation:r,updateUnreadCount:i=!0}=e,o=I(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(n=this._messagesByConversation.get(s))?void 0:n.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(r,{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"];ws(s)?k.notificationCenter.emitInnerEvent(Ht[e],t):k.notificationCenter.emitInnerEvent(e,t)}},fl=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)}},Il=Object.freeze({__proto__:null,conversationStore:_l,groupStore:ml,messageStore:vl,userStore:fl});class P{static getInstance(){return P._instance||(P._instance=new P),P._instance}static setInstance(e){P._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this)},this._apiHandlersMap={},this._apiMap={on:k.notificationCenter.subscribeOuterEvent.bind(k.notificationCenter),off:k.notificationCenter.unSubscribeOuterEvent.bind(k.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:dl.getInstance().installExternalPlugin.bind(dl.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){console.log("registerPlugin",e)}statKeyFeatureUsage(e){console.log("statTUIKeyFeatures",e)}setLogLevel(e){console.log("setLogLevel",e),!k||"function"!=typeof k.setLogLevel||null!=k&&k.setLogLevel(e)}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{apiName:n,context:t,methodName:r=n,matcher:s}=e;this._apiHandlersMap[n]||(this._apiHandlersMap[n]=[]),this._apiHandlersMap[n].push({context:t,methodName:r,matcher:s}),this._apiMap[n]&&1!==this._apiHandlersMap[n].length||(this._apiMap[n]=(...t)=>{Rs(r,t);var s=this._apiHandlersMap[n];for(let e of s)if(!e.matcher||e.matcher(t))return e.context[e.methodName].bind(e.context)(...t)})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return S(this,void 0,void 0,function*(){var e,t;try{null!=(e=k.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),k.notificationCenter.emitInnerEvent(d.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{k.notificationCenter.emitOuterEvent(kt.SDK_DESTROY,{SDKAppID:null==(t=k.store.get("instance"))?void 0:t.sdkAppId}),bs.clear(),dl.getInstance().clear(),g.getInstance().destroy(),k.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:d,InnerEventSubType:k.notificationCenter.InnerEventSubType,OuterEvent:kt,OuterConstant:C,SignalingEvent:xt,helper:Object.assign(Object.assign(Object.assign({},k.utils),k.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Ds,registerValidateConfig:Ls,checkBusinessCapabilityBits:Ns,registerWorkflowStep:g.getInstance().registerWorkflowStep.bind(g.getInstance()),ChatError:_}),apiMap:this._apiMap},k),{constants:Object.assign(Object.assign({},ls),k.constants),common:Object.assign(Object.assign(Object.assign({},cl),k.common),{workflowManager:g.getInstance()}),utils:k.utils,appStore:Il})}callExperimentalAPI(e,t){return this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new _({code:ts.INVALID_OPERATION}))}}class Sl{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){var{notificationCenter:e,store:t}=k;t.set("login",{isReady:!1}),P.getInstance().registerApi({apiName:"login",context:this}),P.getInstance().registerApi({apiName:"logout",context:this}),P.getInstance().registerApi({apiName:"getLoginUser",context:this}),P.getInstance().registerApi({apiName:"isReady",context:this}),e.subscribeInnerEvent(d.RECONNECTED,this._reLogin,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}login(s){return S(this,void 0,void 0,function*(){let e=this._getUiPlatform(),t=(k.store.get("instance")||{})["sdkEdition"],n=k.ssoLog.createSSOLogData({method:"login",eventType:4,uiPlatform:e,message:t});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new _({functionName:"login",code:ts.REPEAT_LOGIN});let e=yield this._performLogin(s);return this._validateAfterLogin(e),this._handleLoginSuccess(e),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:this._latestLoginAt=0,data:e}}catch(e){let t=e["errorCode"],s=(t!==ts.REPEAT_LOGIN&&(this._latestLoginAt=0),new _({functionName:"login",code:t}));throw n.setError(s).end(!0),s}})}_getUiPlatform(){var e,t=k["store"],t=null==(e=t.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_reLogin(){return S(this,void 0,void 0,function*(){var e,t,s,n,r,i;try{this._isLoginIn()&&(t=k.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Ss())&&({instanceID:n,customStatus:r}=s,k.store.set("login",{statusInstanceId:n}),g.getInstance().executeWorkflow(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:Wt.USER_STATUS_ONLINE}),i=`socketId:${null==(e=k.channel.getSocketAdapter())?void 0:e.getId()} instanceId:`+n,t.setLogInfo({message:i}).end(!0))}catch(e){console.warn(e)}})}logout(){return S(this,arguments,void 0,function*(s=os.USER_INITIATED){let e=k.ssoLog.createSSOLogData({method:"logout"});e.setLogInfo({moreMessage:"identifier:"+p()});try{yield this._performLogout(s),e.end(!0),k.ssoLog.uploadSSOLogData()}catch(s){let e=s["errorCode"],t=new _({functionName:"logout",code:e});this._handleLogoutError(t)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?p():""}isReady(){var e;return null==(e=k.store.get("login"))?void 0:e.isReady}_updateAndEmitSDKReady(){k.store.set("login",{isReady:!0}),setTimeout(()=>{k.notificationCenter.emitOuterEvent(kt.SDK_READY,{name:kt.SDK_READY})},1)}_updateAndEmitSDKNotReady(){k.store.set("login",{isReady:!1}),k.notificationCenter.emitOuterEvent(kt.SDK_NOT_READY,{name:kt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s="login";if(!e)throw new _({functionName:s,message:"login response is empty"});var{tinyID:e,a2Key:n}=e||{},r=k.ssoLog.getSSOLogData(s);if(!e){let e=new _({functionName:s,code:ts.NO_TINYID});throw null!=(t=null==r?void 0:r.setError)&&t.call(r,e).end(),e}if(!n){let e=new _({functionName:s,code:ts.NO_A2KEY});throw null!=(t=null==r?void 0:r.setError)&&t.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Es({code:"RepeatLogin",replacement1:null==(e=k.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return S(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return k.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Ss()})}_ensureAsyncComplete(){return S(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=k.common["timeManager"],{helloInterval:s,timeStamp:n,customStatus:r,purchaseBits:i}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*n),this._helloInterval=s||120,this._updateLoginStore(e),k.user.userStatus.setCustomStatus(r),g.getInstance().executeWorkflow(h.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),k.common.taskScheduler.addTask({id:cs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(s){return S(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=k.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield k.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutError(e){k.ssoLog.getSSOLogData("logout").setError(e).end(),console.error("logout "+e)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),g.getInstance().reset(),k.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:n}=e;k.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:n,isLoggedIn:!0})}_logLoginSuccess(e){var t=k.ssoLog.getSSOLogData("login"),{helloInterval:e,instanceID:s,timeStamp:n,customStatus:r}=e,i=null==(i=k.channel.getSocketAdapter())?void 0:i.getId(),o=k.common.timeManager.getTimeOffsetWithServer(),{appId:a,href:l}=k.store.get("instance")||{},i=`login._logLoginSuccess socketID:${i} scene: helloInterval:${e} instanceID:${s}
4
+ timeStamp:${n} offset:${o} customStatus:${r} href: ${l} appId: `+a;console.log("login ok. "+i),t.updateLogCreatedAtByTimeOffset(),t.setLogInfo({moreMessage:i}).end()}_sendOnlinePresenceRequest(){return S(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=k.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield k.channel.sendPacket(t,{requestId:e})}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),k.common.taskScheduler.removeTask(cs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,k.store.clear("login"),k.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}let El={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Cl={logout:!0};class Ml{constructor(){this.loginAction=new Sl,this.kickedOutHandler=new Is,this.loginAction.init(),this.kickedOutHandler.init(),Ls({auth:Cl,params:El})}}(b=F=F||{}).CONV_C2C="C2C",b.CONV_GROUP="GROUP",b.CONV_TOPIC="TOPIC",b.CONV_SYSTEM="@TIM#SYSTEM",(N=hl=hl||{}).MSG_PRIORITY_HIGH="High",N.MSG_PRIORITY_NORMAL="Normal",N.MSG_PRIORITY_LOW="Low",N.MSG_PRIORITY_LOWEST="Lowest",(t=gl=gl||{}).MSG_TEXT="TIMTextElem",t.MSG_CUSTOM="TIMCustomElem",t.MSG_LOCATION="TIMLocationElem",t.MSG_FACE="TIMFaceElem",t.MSG_IMAGE="TIMImageElem",t.MSG_AUDIO="TIMSoundElem",t.MSG_FILE="TIMFileElem",t.MSG_VIDEO="TIMVideoFileElem",t.MSG_GRP_TIP="TIMGroupTipElem",t.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",t.MSG_MERGER="TIMRelayElem";let yl={1:hl.MSG_PRIORITY_HIGH,2:hl.MSG_PRIORITY_NORMAL,3:hl.MSG_PRIORITY_LOW,4:hl.MSG_PRIORITY_LOWEST},Ol=((sn=pl=pl||{}).IN="in",sn.OUT="out",{});function Al(e){var t,s,n;return e?(void 0===Ol[e]?(t=("3"+(n=new Date).getHours()).slice(-2),s=("0"+n.getMinutes()).slice(-2),n=("0"+n.getSeconds()).slice(-2),Ol[e]=parseInt([t,s,n,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Ol[e])):Ol[e]+=1,Ol[e]):0}class Tl{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=hl.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=k.common.timeManager.getServerTimeSeconds()||0,senderTinyID:n,currentUser:r,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:S=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:O=Ft.SUCCESS,revokeReason:A="",conversationSubType:T,clientSequence:R,protocol:D="JSON",revokerInfo:L={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:b,groupProfile:P,atUserList:w,flow:G,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=n||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===b?(t=t||99999999,Math.round(Math.random()*t)):b,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||F.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=A,this.revokerInfo=L,this._receiverList=M,this.conversationSubType=T,this.revoker=(null==L?void 0:L.revoker)||"",this.clientSequence=R||I||0,this.status=O,this.atUserList=w||[],this.flow=G,this.isRead=U,this.reInitialize(r),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===F.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!==F.CONV_SYSTEM?(e=t!==F.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=F.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Al(e)),0===this.sequence&&this.conversationType===F.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===F.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class Rl{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new Rl({data:e,description:s,extension:t})}constructor(e){this.type=gl.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=k.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 Dl{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new Dl({text:e})}constructor(e){this.type=Bt.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 Ll=new class{constructor(){this._elementClassMap={[gl.MSG_CUSTOM]:Rl,[gl.MSG_TEXT]:Dl}}init(){P.getInstance().registerApi({apiName:"createCustomMessage",context:this}),P.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=pl.OUT}=e,n=(k.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:n})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:n})&&(e.flow=pl.OUT),Object.assign(Object.assign({},e),{currentUser:n}));return new Tl(t)}createCustomMessage(t){let e=p(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),n=this._elementClassMap[gl.MSG_CUSTOM];if(!s)return null;if(n){let e=new n(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 Dl({text:t}),s=p(),(e=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:n,tinyID:r}=k.store.get("login")||{},i=fl.getUserProfile(n);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||r||"",e.from=n,e.status=Ft.UNSENT,e.flow=pl.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===pl.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===pl.OUT}};let Nl={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}},bl={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Pl={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function wl(n,r){return Object.keys(r).forEach(e=>{var{range:t,defaultValue:s}=r[e];n[e]=t.includes(n[e])?n[e]:s}),n}function Gl(e){return k.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:function(e){var{apnsInfo:e={},ignoreIOSBadge:t=!1,disableVoipPush:s}=e,{ignoreIOSBadge:n,disableVoipPush:r,enableIOSBackgroundNotification:i}=e=wl(e,Pl),e=I(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),n=!0===n||!0===t?1:0;let o;return $(s)||(o=!1===s?1:0),$(r)||(o=!1===r?1:0),Object.assign(Object.assign({},e),{BadgeMode:n,IsVoipPush:o,ContentAvailable:i?1:0})}(e),AndroidInfo:function(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,{sound:s="",FCMChannelID:n=""}=e=wl(e,bl),e=I(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:-1===(s=(e=s).lastIndexOf("."))?e:e.slice(0,s),OPPOChannelID:t,GoogleChannelID:n})}(e)}:Nl}function Ul(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:n,IsPeerRead:r,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,S,{From_Account:E,To_Account:C}=e;if(1===i){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===n,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:S,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:r,elements:ql(o)}}function kl(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:n,MsgSeq:r,MsgTimeStamp:i,To_Account:o,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:n,sequence:r,time:i,to:o,elements:ql(t),messageVersion:a,cloudCustomData:l}}function Fl(e){let{ClientSeq:t,From_Account:s,GroupInfo:n,MsgBody:r,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,S=hl.MSG_PRIORITY_NORMAL;if(Object.keys(yl).includes(String(e.MsgPriority))&&(S=yl[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=>{0===e.GroupAtAllFlag?t.push(e.GroupAt_Account):1===e.GroupAtAllFlag&&t.push(C.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:n,clientTime:i,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:ql(r),to:function(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=k,{ToGroupId:e,GroupInfo:{MillionGroupFlag:n=0,TopicId:r}={}}=e;return n!==s||t(r)?e:r}(e)}}function ql(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=k.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=k.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function xl(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:n,MsgSeq:r,MsgTimeStamp:i,GroupId:o,TopicId:a,MsgVersion:l,CloudCustomData:u}=e;return{from:e,clientTime:s,random:n,sequence:r,time:i,groupID:o,topicID:a,elements:ql(t),messageVersion:l,cloudCustomData:u}}function Vl({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:n,conversationSubType:r,flow:i,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&i===pl.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:n,subType:r,unreadCount:t?1:0,lastMessage:a})}function Bl(e){return e.filter(e=>{var t=!He(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||k.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:`+e.sequence}).end(),t&&!s})}function jl(e){var t=k.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var Kl=Object.freeze({__proto__:null,autoIncrementIndex:Al,filterValidMessages:Bl,parseServerGroupMessage:Fl,parseServerPushC2CModifyMessage:kl,parseServerPushGroupModifyMessage:xl,parseServerPushMessage:Ul,parseServerPushMessageElement:ql,shouldStoreMessage:jl,updateConversationFields:Vl});let Hl=k.utils["isPlainObject"];function Wl(e,t={}){let{onlineUserOnly:s,messageControlInfo:n}=t,r=t["offlinePushInfo"],i=(e.conversationType===F.CONV_C2C&&!0===s&&(r?r.disablePush=!0:r={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(i=e.cloudCustomData);var o=[];if(n&&Hl(n)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=n;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:o,offlinePushInfo:r}}function $l(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 Yl(t,s){return S(this,void 0,void 0,function*(){var e=yield ks((t.conversationType===F.CONV_GROUP?function(e,t){var s,{onlineUserOnly:n,cloudCustomData:r,messageControlInfo:i,offlinePushInfo:o}=Wl(e,t),a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let l;return J(e._receiverList)&&0<e._receiverList.length&&(l=e._receiverList,50<e._receiverList.length)&&(l=e._receiverList.slice(0,50),console.warn("ReceiverListLimit")),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:a,CloudCustomData:r,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:n?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Gl(o),SendMsgControl:n?void 0:i,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:l,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:$l(t)}}}:function(e,t){var s,{onlineUserOnly:n,cloudCustomData:r,messageControlInfo:i,offlinePushInfo:o}=Wl(e,t),n=!0===n?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:r,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:n,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==n?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:Gl(o),forbidCallbackControl:$l(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let zl=k.utils["isPlainObject"],{MSG_AUDIO:Jl,MSG_FILE:Ql,MSG_IMAGE:Xl,MSG_VIDEO:Zl,MSG_MERGER:eu}=C;class tu{init(){P.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![Jl,Ql,Xl,Zl,eu].includes(e[0].type)})}sendMessage(c,t){return S(this,void 0,void 0,function*(){let n=k.ssoLog.createSSOLogData({method:"sendMessage"}),{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:i}=is;if(!(c instanceof Tl)){let e=new _({code:ts.MSG_INSTANCE_REQUIRED});throw n.setError(e).end(),e}let r=c.validateBeforeSend();if(!r.isValid){let{code:e,message:t=""}=r.error||{},s=new _({code:e,message:t});throw n.setError(s).end(),s}this._reportMessageSendQuality({name:e,message:c});let l=!1;var u=(k.message||{})["messageDataHandler"];try{let n=(t||{})["messageControlInfo"],r=null,i=(u.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===F.CONV_C2C?(l=!0===(null==t?void 0:t.onlineUserOnly),r=yield Yl(c,t)):c.conversationType===F.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),r=yield Yl(c,t)),r){let{messageDropReason:e,sequence:t,time:s}=r;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:o,message:c,startTs:i}),!0===c.isResend){let e=u.findMessage(c.ID);e&&(console.log("sendMessage resend ok. ID:"+e.ID),u.deleteConversationMessage(e))}return c.status=Ft.SUCCESS,c.time=s,c.conversationType===F.CONV_GROUP&&(c.sequence=t),l?c._onlineOnlyFlag=!0:(u.storeConversationMessage(c),this._applySentMessageControlInfo(c,n),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=Ft.FAIL,u.removeRandomOfSentMessage(c.random);let{errorCode:t,errorMessage:s="",errorInfo:n=s}=e||{},r=(this._hasRiskContent(t)&&(c.hasRiskContent=!0),l||this._isRejectedByRestApi(t)||u.storeConversationMessage(c),this._reportMessageSendQuality({name:i,message:c,error:e}),new _({code:t,message:n,data:{message:c}}));throw this._logSendMessageError({message:c,error:r}),r}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_logSendMessageError({message:e,error:t}){var s=k.ssoLog.createSSOLogData({method:"sendMessage"});let n=`head.seq: type:${e.type} from:${e.from} to:`+e.to;if(k.utils.IN_BROWSER){if("connection"in navigator){let e=navigator.connection;n+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:`+e.rtt}if("memory"in window.performance){let e=window.performance.memory;n+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:`+e.jsHeapSizeLimit}}s.setLogInfo({message:n}).setError(t).end()}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:n}=e,r=ws(s)?d.TOPIC_NEW_MESSAGE:d.NEW_MESSAGE;k.notificationCenter.emitInnerEvent(r,{result:{conversationUpdateFieldList:[{conversationID:s,type:n,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&zl(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t){var s=k.ssoLog.createSSOLogData({method:"messageDropReason"}),e=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:`+messageDropReason;s.setLogInfo({message:e}).end(),console.warn("sendMessage "+e)}_updateNickAndAvatarOfSentMessageByMe(e){var t=(k.message||{})["messageDataHandler"];let s=!1;var n,r=e["conversationID"],i=t.getLatestMsgSentByMe(r);i&&({nick:i,avatar:n}=i,s=i!==e.nick||n!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:r,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(r){return S(this,void 0,void 0,function*(){var{to:t,from:s}=r;let n=t,e=ml.getGroup(n);if(Ps({groupID:n})&&null!=e&&e.isSupportTopic)throw new _({code:ts.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(ws(t)&&([n]=t.split(Xt.TOPIC),e=ml.getGroup(n)),!e&&"function"==typeof(null==(t=P.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield P.getInstance().getApiMap().getGroupProfile({groupID:n});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===C.GRP_AVCHATROOM){let e=Es({code:ts.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:n});throw new _({code:ts.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){k.notificationCenter.emitInnerEvent(d.QUALITY_STAT,{label:rs.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class su{constructor(e){this.value=e,this.next=null}}class nu{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new su(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 ru=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new nu(100)}init(){k.notificationCenter.subscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}get _messagesByConversation(){return vl.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),n=this._messagesByConversation.get(e.conversationID);if(null!=n&&n.has(s)){let e=null==n?void 0:n.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:n,cloudCustomData:r,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=We(n);return null!=(l=this._messagesByConversation.get(a))&&l.has(e)?vl.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:r,hasRiskContent:i,operation:jt.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=r,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 n of e)if(s=Array.from(n.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var r of e)if(s=r.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:n,revoker:r}){let e=this._messagesByConversation.get(t),i=null;if(e){var o=Array.from(e.values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:n,sequence:s})){let e=this._getUniqueIdOfMessage(i);return vl.updateMessage(t,[e],{isRevoked:!0,revoker:r,operation:jt.revoke}),i}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(i=this._findMessageBySequenceAndRandom({messageList:e,random:n,sequence:s}))return i.isRevoked=!0,i.revoker=r,i}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:n}){for(let e=0;e<t.length;e+=1){var r=t[e];if(r.sequence===s&&($(n)||r.random===n))return r}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var n=[],r=[],i=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);i.has(e)||(n.push(t),r.push([e,t]))}if(0<r.length){let e=new Map([...r,...i.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return n}storeSparseMessageList(n){if(0!==n.length){let e=n[0]["conversationID"],s=n.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var r=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=n[t];r.has(e.ID)||r.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:n,time:r}=e;return e+`-${t}-${s}-${n}-`+r}_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,n=this._messagesByConversation.get(t);if(n){let e=Array.from(n.values()),r=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:n}=e;n===r&&(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(),k.notificationCenter.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}};function iu(e,t){var s,n,r,i,o,a,l,u=_l.getConversation(e);null!=u&&u.lastMessage&&(u=u["lastMessage"],{lastTime:s,lastSequence:n,version:r}=u,{time:t,sequence:i,messageVersion:o,elements:a,cloudCustomData:l}=t,s===t)&&n===i&&r!==o&&(u.type=a[0].type,u.payload=a[0].content,u.messageForShow=js(u.type,u.payload),u.cloudCustomData=l,u.version=o,_l.updateConversation(e,{lastMessage:u}))}class ou{init(){P.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(c){return S(this,void 0,void 0,function*(){let n=k.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:r,payload:e,sequence:i,conversationType:o,random:a,time:l,from:u,type:t}=c;if(this._canModifyMessageElement(t)){var s=c.getElements();1<s.length&&(s[0].type=t,s[0].content=e);try{let t=null,s;if(n.setLogInfo({message:"to:"+r}),o===F.CONV_C2C?t=yield function(c){return S(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:n,random:r,time:i,type:o,cloudCustomData:a}=c,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:n,MsgRandom:r,MsgTime:i,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},u=yield ks({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:ql(e),messageVersion:t,cloudCustomData:s}}})}(c):o===F.CONV_GROUP&&(t=yield function(o){return S(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:n}=o,r={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:n},i=yield ks({servcmd:"openim.modify_group_msg",data:r});if(i){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=i;return{elements:ql(e),messageVersion:t,cloudCustomData:s}}})}(c)),t){n.end();let e=""+o+r;return r===p()&&o===F.CONV_C2C&&(e=""+o+u),s={conversationType:o,from:u,to:r,time:l,random:a,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:c}}}}catch(e){let t=(e||{})["errorCode"],s=new _({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}else n.setLogInfo({message:"can not modify message element. message type: "+t}).end()})}_logModifyMessageError(e){k.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:n}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent(kt.MESSAGE_MODIFIED,{name:kt.MESSAGE_MODIFIED,data:[n]}),k.notificationCenter.emitInnerEvent(d.MESSAGE_MODIFIED,{conversationID:t,message:n}),iu(t,e)}_canModifyMessageElement(e){return[gl.MSG_TEXT,gl.MSG_CUSTOM,gl.MSG_LOCATION,gl.MSG_FACE].includes(e)}}class au{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];g.getInstance().registerWorkflowStep(h.RECEIVE_C2C_NEW_MESSAGE,o.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),g.getInstance().registerWorkflowStep(h.RECEIVE_C2C_NEW_MESSAGE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){g.getInstance().executeWorkflow(h.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(k.message||{})["messageDataHandler"],n=[],r=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)||n.push(e)):jl(e)&&(s.storeConversationMessage(e)&&Vl({conversationUpdateFields:r,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||n.push(e))}),{conversationUpdateFieldList:[...r.values()],messages:n}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.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&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=F.CONV_C2C,e=Ul(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:pl.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(n){var e;let r=(k.message||{})["messageDataHandler"],t=null==(e=k.store.get("login"))?void 0:e.userId,{from:s,nick:i,avatar:o,conversationID:a=""}=n;if(s!==t){let s=r.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;$(i)||$(o)?(n.nick=Y(e)?e:n.nick,n.avatar=Y(t)?t:n.avatar):i===e&&o===t||(r.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:i,avatar:o}))}}else{let e=r.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||r.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:n={}}=_l.getConversation(e)||{};n.avatar===s&&n.nick===t||_l.updateConversation(e,{userProfile:Object.assign(Object.assign({},n),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:n}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),k.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),iu(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=F.CONV_C2C,e=kl(e),{to:s,from:n}=e;let r=""+t+s;s===(null==(s=k.store.get("login"))?void 0:s.userId)&&(r=""+t+n),e=Object.assign({conversationType:t,conversationID:r},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],e=e["InnerEventSubType"];k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class lu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];g.getInstance().registerWorkflowStep(h.RECEIVE_GROUP_NEW_MESSAGE,o.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),g.getInstance().registerWorkflowStep(h.RECEIVE_GROUP_NEW_MESSAGE,o.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&g.getInstance().executeWorkflow(h.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=k.message["messageDataHandler"],n=[],r=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)||n.push(e)):jl(e)&&s.storeConversationMessage(e)&&(n.push(e),Vl({conversationUpdateFields:r,message:e})))}),{conversationUpdateFieldList:[...r.values()],messages:n}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[o.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=F.CONV_GROUP,e=Fl(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:pl.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(r){var e;let t=(k.message||{})["messageDataHandler"],s=null==(e=k.store.get("login"))?void 0:e.userId,{from:n,nick:i,avatar:o,conversationID:a="",_elements:l}=r;if(n===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(n===C.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=l,n={};if(He(t)?He(s)||(n=s):[Zt.JOINED,Zt.KICKED,Zt.ADMIN_SET,Zt.ADMIN_CANCELED].includes(e)&&(n=Object.assign({},t[0])),!He(n)){let{nick:e="",avatar:t=""}=n;r.nick=e,r.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:n}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),iu(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=F.CONV_GROUP,{topicID:s,groupID:n}=e=xl(e),s=s||n,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(d.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===Qt.GRP_AVCHATROOM;return!(!ml.getGroup(e)&&t)}}var uu=new class{constructor(){this.c2cMessageReceiver=new au,this.groupMessageReceiver=new lu}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let cu={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 is invalid."}}}},du={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var hu=new class{getGroupRoamingMessagesByAnchor(s){return S(this,void 0,void 0,function*(){try{var o=k.ssoLog.createSSOLogData({method:"getGroupRoamingMessagesByAnchor"}),{conversationID:t,count:e,direction:a,sequence:l}=s,u=t.replace(Yt.CONV_GROUP,""),c=[];let i=l;if(a===qt.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};i=l+e-1}var d=yield function(n){return S(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s}=n,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1};return s&&(e.ReqMsgSeq=s),yield ks({servcmd:"group_open_http_svc.group_msg_get",data:e})})}({groupID:u,count:e,messageSequence:i});if(d){let{RspMsgList:t=[],NextReqMsgSeq:e=0,IsFinished:s,InvisibleMsgSeq:n}=d;o.setLogInfo({message:`groupID:${u} sequence:${l} reqSeq:${i} direction:${a}
5
+ complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+n}).end();var h=[];for(let e=0;e<t.length;e++){var g=t[e],p=(g.From_Account===C.CONV_SYSTEM&&c.push(g),this._parseMessage(g));h.push(p)}h.reverse();let r=2===s;return a===qt.BACKWARD&&(r=h[h.length-1].sequence>=l),{messageList:Bl(h),invisibleSequenceList:n,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:r,serverGroupTipList:c}}}catch(e){t=new _({code:null==e?void 0:e.code});k.ssoLog.getSSOLogData("getGroupRoamingMessagesByAnchor").setError(t).end()}})}_parseMessage(e){var t=Yt.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=C.MSG_GRP_TIP),Fl(e)),t=Ll.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class gu{constructor(){this.messageHelper=Kl,this.messageFactory=Ll,this.messageSender=new tu,this.messageAction=new ou,this.messageReceiver=uu,this.messageDataHandler=ru,this.messageHistory=hu,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),Ls({auth:du,params:cu})}}let pu="Tag_Profile_IM_",_u={NICK:pu+"Nick",GENDER:pu+"Gender",BIRTHDAY:pu+"BirthDay",LOCATION:pu+"Location",SELFSIGNATURE:pu+"SelfSignature",ALLOWTYPE:pu+"AllowType",LANGUAGE:pu+"Language",AVATAR:pu+"Image",MESSAGESETTINGS:pu+"MsgSettings",ADMINFORBIDTYPE:pu+"AdminForbidType",LEVEL:pu+"Level",ROLE:pu+"Role"},mu="Tag_Profile_Custom",vu="profileCustomField",fu={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:[]},Iu=new Map([[_u.NICK,"nick"],[_u.GENDER,"gender"],[_u.BIRTHDAY,"birthday"],[_u.LOCATION,"location"],[_u.SELFSIGNATURE,"selfSignature"],[_u.ALLOWTYPE,"allowType"],[_u.LANGUAGE,"language"],[_u.AVATAR,"avatar"],[_u.MESSAGESETTINGS,"messageSettings"],[_u.ADMINFORBIDTYPE,"adminForbidType"],[_u.LEVEL,"level"],[_u.ROLE,"role"]]);var Su=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(mu)?s.profileCustomField.push({key:e,value:t}):Iu.has(e)&&(s[Iu.get(e)]=t)}),Object.assign(Object.assign({},fu),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!==vu&&s.push({tag:_u[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&J(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let n={},r=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(mu)&&r.push({key:t,value:s}),Iu.has(t)&&void 0!==s){let e=Iu.get(t);n[e]=s}}),0<r.length&&(n.profileCustomField=r),n}};let Eu=k.common["generateProtocolData"];function Cu(n){return S(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:p(),UserItem:[]};n.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var i=Eu({servcmd:e,data:t}),s=i.head.seq+e,i=yield k.channel.sendPacket(i,{requestId:s});if(i){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:n,UserProfileItem:r}=i,o=[];return r.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:n,StandardSequence:r,ProfileItem:i}=e,i=Su.parseProfileItem(i);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:n,standardSequence:r,profileItem:i})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:n,userProfile:o}}})}function Mu(e){return fl.getFriendMap().has(e)}let yu=k.utils["isEmpty"];class Ou{constructor(){this._strangerProfileMap=new Map}init(){P.getInstance().registerApi({apiName:"getMyProfile",context:this}),P.getInstance().registerApi({apiName:"getUserProfile",context:this}),P.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Su.createProfile.bind(Su);var e=k["notificationCenter"];g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_LOGIN,o.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}getMyProfile(){return S(this,void 0,void 0,function*(){let t=k.ssoLog.createSSOLogData({method:"getMyProfile"});try{var s=p(),n=yield Cu([s]);if(n){let e=this._handleProfileFormResponse(n)[0];return fl.getUserProfileMap().set(s,e),{code:0,data:e}}t.end()}catch(e){var{errorCode:n,errorInfo:s}=e,n=new _({functionName:"getMyProfile",code:n,message:s});throw t.setError(n).end(),e}})}getUserProfile(d){return S(this,void 0,void 0,function*(){var t=k.ssoLog.createSSOLogData({method:"getUserProfile"});try{var s=d["userIDList"],{userIdListToRequest:n,profileFromCache:r}=this._filterRequestAndCacheUsers(s),i="User.getUserProfile userIDList.length:"+s.length;if(0===n.length)return t.setLogInfo({message:i}).end(),{code:0,data:r};1e3<n.length&&(console.warn("userIdListToRequest.length > 1000"),n.length=1e3);var{data:o,error:e}=yield this._batchFetchUserProfiles(n),a=n.length,l=o.length,u=a-l,c=`getUserProfile query:${a} success:${l} fail:${u} from cache:`+r.length;if(0===r.length&&a===u&&!yu(e))throw console.error(c+` error:${JSON.stringify(e)}}`),e;if(J(o)){o.forEach(e=>{(Mu(e.userID)?fl.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=o.concat(r);return t.setLogInfo({message:i}).end(),{code:0,data:e}}}catch(e){s=e["errorCode"],n=new _({functionName:"getUserProfile",code:s});throw t.setError(n).end(),n}})}getMyProfileCacheThenServer(){return S(this,void 0,void 0,function*(){var e=p(),e=fl.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(l){return S(this,void 0,void 0,function*(){let r=k.ssoLog.createSSOLogData({method:"updateMyProfile"}),t=p(),s={};for(let e in l)void 0!==l[e]&&(s[e]=l[e]);let n=Su.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:n};r.setLogInfo({message:JSON.stringify(n)}),yield function(n){return S(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Eu({servcmd:e,data:n}),s=""+t.head.seq+e,r=yield k.channel.sendPacket(t,{requestId:s});if(r){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:n}=r;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:n}}})}(e);var i=fl.getUserProfile(t),o=i?Object.assign(Object.assign({},i),s):Su.createProfile(t,n),a=!Ut(i,o,["lastUpdatedTime"]);return o.lastUpdatedTime=Date.now(),fl.getUserProfileMap().set(t,o),a&&this._emitProfileUpdated(o),r.end(),{code:0,data:o}}catch(e){let{errorCode:t,errorInfo:s}=e,n=new _({functionName:"updateMyProfile",code:t,message:s});throw r.setError(n).end(),n}})}updateMyNickAndAvatar(r){return S(this,void 0,void 0,function*(){var e=p(),t=Date.now(),s=fl.getUserProfile(e),n={};(n=s?Object.assign(s,r):Su.createProfile(e,r)).lastUpdatedTime=t,fl.getUserProfileMap().set(e,n)})}_onProfileDataModify(n){var e,t=function(){var{Profile_Account:e,PushType:t,ProfileList:s}=n.ProfileDataMod[0];return{userId:e,pushType:t,profileList:Su.parseProfileList(s)}}();yu(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){k.notificationCenter.emitInnerEvent(d.PROFILE_UPDATE,{name:d.PROFILE_UPDATE,data:[e]}),k.notificationCenter.emitOuterEvent(kt.PROFILE_UPDATED,{name:kt.PROFILE_UPDATED,data:[e]}),_l.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,n=fl.getUserProfile(t);if(!(p()===t||Mu(t)&&n))return{isProfileUpdated:!1,profile:null};let r=Su.normalizeProfileFields(s),i=Object.keys(r).some(e=>e===vu?!Ut(n.profileCustomField,r.profileCustomField):n[e]!==r[e]);return i?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},n),r),{lastUpdatedTime:e}),fl.getUserProfileMap().set(t,e),{isProfileUpdated:i,profile:e}):{isProfileUpdated:!1,profile:n}}_filterRequestAndCacheUsers(e){let s=[],n=[];return e.forEach(e=>{var t=fl.getUserProfileMap().has(e);Mu(e)&&t?n.push(fl.getUserProfile(e)):this._isStrangerAndProfileValid(e)?n.push(this._strangerProfileMap.get(e)):s.push(e)}),{userIdListToRequest:s,profileFromCache:n}}_handleProfileFormResponse(e){e=e.userProfile;if(!Array.isArray(e))return[];let t=e.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!yu(e.profileItem)),s=Date.now();return t.map(e=>{e=Su.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!Mu(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=k.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,n){return Array.from({length:Math.ceil(s.length/n)},(e,t)=>s.slice(t*n,(t+1)*n))}_batchFetchUserProfiles(e){return S(this,void 0,void 0,function*(){let t=[],n=[],r={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(Cu(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);J(t)&&n.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};r={errorCode:e,message:t}}}),{data:n,error:r}})}_reset(){fl.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}var Au,Tu,Ru,Du=new Map,Lu=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Lu.length;e<t;e++)Du.set(e,Lu[e]);function Nu(e){if(!e)return"";var r=String(e).replace(/[=]+$/,"");let i="";if(r.length%4==1)return"";for(let e,t,s=0,n=0;t=r.charAt(n++);~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 bu=k.utils["isEmpty"],Pu=k.common["generateProtocolData"];function wu(r){return S(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",n=Pu({servcmd:s,data:{To_Account:r}}),s=n.head.seq+s,n=yield k.channel.sendPacket(n,{requestId:s});if(n)return{ErrorCode:s,ErrorInfo:n,ErrorList:e=[],UserStatusList:t=[]}=n,{errorCode:s,errorInfo:n,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:Nu(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:n}=e;return{userID:bu(t)?e:t,code:s,message:n}})}})}class Gu{constructor(){this._customStatus=""}init(){var e=k["notificationCenter"];P.getInstance().registerApi({apiName:"getUserStatus",context:this}),P.getInstance().registerApi({apiName:"setSelfStatus",context:this}),P.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),P.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}setSelfStatus(s){return S(this,void 0,void 0,function*(){let r=k.ssoLog.createSSOLogData({method:"setSelfStatus"}),e=p(),t=s["customStatus"];try{return yield function(r){return S(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=Pu({servcmd:e,data:{CustomStatus:r}}),s=""+t.head.seq+e,n=yield k.channel.sendPacket(t,{requestId:s});if(n){let{ErrorCode:e,ErrorInfo:t}=n;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,r.setLogInfo({message:"customStatus: "+t}).end(),{code:0,data:{userID:e,statusType:1,customStatus:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,n=new _({functionName:"setSelfStatus",code:t,message:s});throw r.setError(n).end(),n}})}getUserStatus(s){return S(this,void 0,void 0,function*(){var e=k.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:t=[]}=s;return e.setLogInfo({moreMessage:"userIDList length: "+t.length}),this._isOnlyMeInArray(t)?this._getMyStatus():this._getUserStatus(t)})}setCustomStatus(e){e=Nu(e);this._customStatus=e}subscribeUserStatus(n){return S(this,void 0,void 0,function*(){try{console.log("User subscribeUserStatus options: ",n);var{userIDList:e=[]}=n,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(n){return S(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_subscribe",s=Pu({servcmd:t,data:{To_Account:n}}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t));return{code:0,data:{failureUserList:this._parseResponse(s)}}}catch(e){throw console.error("User subscribeUserStatus error:",e),e}})}unsubscribeUserStatus(n){return S(this,void 0,void 0,function*(){try{console.log("User unsubscribeUserStatus options: ",n),this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=n,t=this._getMaxUserCount("unsubscribe"),s=yield function(n){return S(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_unsubscribe",s=0===n.length?{UnsubscribeAll:1}:{To_Account:n},s=Pu({servcmd:t,data:s}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t));return{code:0,data:{failureUserList:this._parseResponse(s)}}}catch(e){throw console.error("User unsubscribeUserStatus error:",e),e}})}_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:Nu(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=Nu(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:p(),statusType:1,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){k.notificationCenter.emitOuterEvent(kt.USER_STATUS_UPDATED,{name:kt.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:n}=e;return{userID:k.utils.isEmpty(t)?e:t,code:s,message:n}})}_checkBusinessCapabilityBits(e){if(!k.store.get("commercialConfig").get("USER_STATUS"))throw new _({functionName:e,code:ts.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=k.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(){var e=k.ssoLog.getSSOLogData("getUserStatus"),t=(e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"}),{userID:p(),statusType:1,customStatus:this._customStatus});return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(r){return S(this,void 0,void 0,function*(){var t=k.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");var s=this._getMaxUserCount("query"),{successUserList:n,failureUserList:e}=(yield wu(this._sliceUserIDList(r,s)))||{};return t.end(),{code:0,data:{successUserList:n,failureUserList:e}}}catch(e){s=e["errorCode"],n=new _({functionName:"getUserStatus",code:s});throw t.setError(n).end(),n}})}_isOnlyMeInArray(e){var t=p();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let Uu={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(mu))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}}},ku={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Fu{constructor(){this.userProfile=new Ou,this.userStatus=new Gu,this.userProfile.init(),this.userStatus.init(),Ls({auth:ku,params:Uu})}}function qu(t){var s=[];if(Y(t)){var n=t.length;if(0!==n)for(let e=n-1;0<=e;e--)"1"===t[e]&&s.push(2**(n-e-1))}return s}(e=Au=Au||{}).NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected",(m=Tu=Tu||{})[m.C2C=1]="C2C",m[m.GROUP=2]="GROUP",(i=Ru=Ru||{})[i.C2C=8]="C2C",i[i.GROUP=2]="GROUP";class xu{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Au.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=k["notificationCenter"];g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.CONVERSATION_RECOVER,this._syncConversationList,this),g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this),console.log(this._name+".init")}isSyncCompleted(){return this._pagingStatus===Au.RESOLVED}_syncConversationListAfterLogin(){return S(this,void 0,void 0,function*(){return this._pagingStatus=Au.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return S(this,void 0,void 0,function*(){let e=k["ssoLog"],t=e.createSSOLogData({method:"syncConversationList"});try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=Au.RESOLVED;var{conversationList:s=[]}=e||{};return t.setLogInfo({message:"count:"+s.length}).end(),console.log(this._name+"._syncConversationList ok, count:"+s.length),e}catch(e){var{errorCode:s,errorInfo:n}=e,s=new _({functionName:"syncConversationList",code:s,message:n});t.setError(s).end(),console.error(this._name+"._syncConversationList fail:",s)}})}_pagingGetConversationList(c){return S(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=Au.PENDING,yield function(i){return S(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:n,pagingPinnedStartIndex:r}=i;return ks({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:r,TopTimeStamp:n}})})}({fromAccount:p(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:n,SessionItem:r=[],TimeStamp:i,StartIndex:o,TopTimeStamp:a,TopStartIndex:l}=s||{};if(0<r.length){let e=this._getConversationOptions(r);t.push(...e);var u=k["notificationCenter"];u.emitInnerEvent(d.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=i,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=l,1!==n&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw console.error(this._name+"._pagingGetConversationList fail:",e),e}})}_getConversationOptions(e){let{isUndefined:t}=k["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===Tu.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===Tu.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(C.CONV_C2C)?e.replace(C.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+C.CONV_C2C+e.userID,type:C.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===Ru.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:qu(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=k.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===p()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+C.CONV_GROUP+e.groupID,type:C.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===Ru.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:qu(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.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(e){var t=k["utils"]["isEmpty"];if(t(e))return null;let s="",n=null;return e.MsgBody&&(s=null==(t=e.MsgBody[0])?void 0:t.MsgType,n=this._parseContent(s,e.MsgBody[0])),{event:e.Event,elements:[{type:s,content:n,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null==(t=e.RevokerInfo)?void 0:t.revoker}}}_parseContent(e,t){return t&&((e=k.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return I(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=C.MSG_REMIND_ACPT_AND_NOTE:1===e?t=C.MSG_REMIND_DISCARD:2===e?t=C.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=C.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=k["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:C.MSG_GRP_TIP,payload:{}}}_computeGroupUnreadCount(e){var{unreadCount:e=0,noUnreadCount:t=0}=e,e=e-t;return 0<e?e:0}_reset(){this._pagingStatus=Au.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class Vu{constructor(){this.syncConversationHandler=new xu,this.syncConversationHandler.init()}}return console.log("TencentCloudLiteChat.VERSION:1.5.1"),{create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:n=!1,scene:r="",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),bs.has(l))return bs.get(l);let u=null;if(o)(u=o)._workflowManager&&g.setInstance(u._workflowManager),u._pluginManager&&u._pluginManager.installBuiltInPlugin(ul),!o.isReady()||null!=(o=(e=g.getInstance()).executeWorkflow)&&o.call(e,h.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(c()+c())+c()+c()+c()+c()+c()+c();k.init({sdkAppId:l,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:n,disableIndependentDomain:a,scene:r,oversea:i,sdkEdition:ll}),g.getInstance().init(),k.message=new gu,k.user=new Fu,k.login=new Ml,k.conversation=new Vu,dl.getInstance().installBuiltInPlugin(ul),(u=P.getInstance().exposeApiForClient())._workflowManager=g.getInstance(),u._pluginManager=dl.getInstance()}function c(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return bs.set(l,u),u},TSignaling:xt,EVENT:kt,VERSION:nt,TYPES:C}});