@tencentcloud/lite-chat 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/standard.js CHANGED
@@ -1,5 +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(){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 P={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 x;(e=x=x||{})[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,q,V,e=Object.freeze({__proto__:null,get ConvModifyPushType(){return x},ENUM_PLATFORM:P,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 x.CONV_MARK_UPDATED:s.push(n.CONVERSATION_MARK_UPDATED);break;case x.CONV_GROUP_ADDED:s.push(n.CONVERSATION_GROUP_ADD);break;case x.CONV_GROUP_DELETED:s.push(n.CONVERSATION_GROUP_DELETED);break;case x.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:q.SERVER_PUSH_MESSAGE+":"+e,data:t})}):r.push({type:q.SERVER_PUSH_MESSAGE+":"+s,data:t})}),r}(t=q=q||{}).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={[q.SERVER_PUSH_MESSAGE]:K,[q.SERVER_PUSH_MESSAGE_MULTIPLE]:K,[q.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 S(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 I(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),X=e=>null!==e&&"object"==typeof e,Q=e=>J(e)||X(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(!Q(s)||!Q(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(Q(s[a])&&Q(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,_e="undefined"!=typeof uni,pe=ie||ae||le||ue||ce||he||de,me="undefined"==typeof window&&!pe&&"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),Se="undefined"!=typeof uni?!pe:"undefined"!=typeof window&&!pe&&!ve,Ie=ae?qq:le?tt:ue?swan:ce?my:ie?wx:he?uni:de?jd:{},s=Se&&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"),P[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))?(Xe=t[1]&&parseFloat(t[1]),V=t[2]&&parseFloat(t[2]),Xe&&V?parseFloat(t[1]+"."+t[2]):Xe||null):null,be=/Firefox/i.test(s),Ne=/Edge/i.test(s),Le=!Ne&&/Chrome/i.test(s),Ge=/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}(),Pe=/Safari/i.test(s)&&!Le&&!Re&&!Ne,Ue=/Windows/i.test(s),ke=/MAC OS X/i.test(s),Fe=Se&&"undefined"!=typeof Worker&&!Ge,xe=Re||Ae,qe=Se&&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||Pe));function Be(){let e="unknown";if(ke&&(e="mac"),Ue&&(e="windows"),Ae&&(e="ios"),Re&&(e="android"),pe)try{var t=wx.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 I(this,arguments,void 0,function*({method:r,url:i,data:o,timeout:a=3e3}){return new Promise(pe?(t,e)=>{Ie.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:Se,IN_DONUT_NATIVE_APP:ge,IN_JD_MINI_APP:de,IN_MINI_APP:pe,IN_NS_NATIVE_APP:me,IN_QQ_MINI_APP:ae,IN_RN_APP:ve,IN_TT_MINI_APP:le,IN_UNI_APP:_e,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:Le,IS_EDGE:Ne,IS_FIREFOX:be,IS_IE:Ge,IS_IOS:Ae,IS_IPAD:Me,IS_IPHONE:ye,IS_IPOD:Oe,IS_MAC:ke,IS_SAFARI:Pe,IS_WECHAT:Ee,IS_WIN:Ue,IS_WORKER_AVAILABLE:Fe,MINI_APP_NAMESPACE:Ie,USER_AGENT:s,base16EncodeBinaryString:ne,deepCopyWithMethods:We,deepMerge:se,generatePromise:$e,getPlatformType:Be,getType:z,httpRequest:Ke,isArray:J,isArrayOrObject:Q,isEmpty:He,isFlutterWeb:qe,isH5:xe,isIOSWebView:Ve,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:X,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=wx.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,Xe,c=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return pe?ce?my.getStorageSync({key:e}).data:Ie.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){pe?ce?my.setStorageSync({key:e,data:JSON.stringify(t)}):Ie.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}};(Xe=r=r||{})[Xe.CONNECTED=0]="CONNECTED",Xe[Xe.CONNECTING=1]="CONNECTING",Xe[Xe.DISCONNECTED=2]="DISCONNECTED";class Qe{constructor(e){this._url="",this._readyState=r.DISCONNECTED,this._url=e,this._id=te(),this._emitter=new w,ie?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",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",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",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",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",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",BACKUP:"wss://wssind.im.qcloud.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.18.188"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",STAT:"https://apijpn.my-imcloud.com"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.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",BACKUP:"wss://wssidn.my-imcloud.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(e){for(var t of Object.keys(et))for(var[s,n]of et[t])if(e>=s&&e<n)return t;return"CHINA"}var nt,rt="1.3.0";(i=nt=nt||{}).INITIAL="INITIAL",i.DEFAULT="DEFAULT",i.BACKUP="BACKUP",i.ANYCAST="ANYCAST";let it=nt.INITIAL;function ot(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:rt},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${n}&compress=gzip`:e+"/info?"+n}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:pt(),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:pt(),cs:0}),r=ct(s);return n.cs=dt(e,r),{head:n,body:r}}let _t=te();function pt(){return _t=_t<2415919103?_t+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.3.0",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:pt(),cs:0}),r=ct(s);return n.cs=dt(e,r),{head:n,body:r}},generateProtocolData:ht,generateSSOLogProtocolData:gt,generateSequence:pt,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 St{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=m=m||{}).RECONNECTED="reconnected",M.CLOUD_CONFIG_UPDATE="cloud_config_update",M.SOCKET_DISCONNECTED="socket_disconnected";var It=m;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(It.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 St(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 I(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 Pt.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 Se&&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(It.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",bt="network_status_change",Nt="send_fail";function Lt(e){return(Lt="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 Gt(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 wt=function s(n,r,i){function o(t,e){if(!r[t]){if(!n[t]){if(!e&&Gt)return Gt(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=Gt,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"!=Lt(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,_=h-(t-e.avail_out),p=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,S=l.wnext,I=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-_)<i){if(f<(n=i-n)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=I,(o=0)===S){if(o+=v-n,n<r){for(r-=n;g[h++]=I[o++],--n;);o=h-i,a=g}}else if(S<n){if(o+=v+S-n,(n-=S)<r){for(r-=n;g[h++]=I[o++],--n;);if(o=0,S<r){for(r-=n=S;g[h++]=I[o++],--n;);o=h-i,a=g}}}else if(o+=S-n,n<r){for(r-=n;g[h++]=I[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<p);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<p?p-h+257:257-(h-p),l.hold=E,l.bits=C}},{}],8:[function(e,t,s){var N=e("../utils/common"),L=e("./adler32"),G=e("./crc32"),w=e("./inffast"),P=e("./inftrees"),U=0,k=-2,F=1,n=852,r=592;function x(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function i(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=F,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new N.Buf32(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 q,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,S,I,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=G(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=G(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=G(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=G(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=G(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=G(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=G(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=G(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=x(u),c=u=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=o,e.avail_out=l,e.next_in=i,e.avail_in=a,s.hold=u,s.bits=c,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last)u>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:D=b=void 0;var D,b=s;if(B){for(q=new N.Buf32(512),V=new N.Buf32(32),D=0;D<144;)b.lens[D++]=8;for(;D<256;)b.lens[D++]=9;for(;D<280;)b.lens[D++]=7;for(;D<288;)b.lens[D++]=8;for(P(1,b.lens,0,288,q,0,b.work,{bits:9}),D=0;D<32;)b.lens[D++]=5;P(2,b.lens,0,32,V,0,b.work,{bits:5}),B=!1}if(b.lencode=q,b.lenbits=9,b.distcode=V,b.distbits=5,s.mode=20,6!==t)break;u>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}u>>>=2,c-=2}break;case 14:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=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=P(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=P(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=P(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(S=m,I=v,E=f;v=(A=s.lencode[E+((u&(1<<S+I)-1)>>S)])>>>16&255,f=65535&A,!(S+(m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}u>>>=S,c-=S,s.back+=S}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(S=m,I=v,E=f;v=(A=s.distcode[E+((u&(1<<S+I)-1)>>S)])>>>16&255,f=65535&A,!(S+(m=A>>>24)<=c);){if(0===a)break e;a--,u+=n[i++]<<c,c+=8}u>>>=S,c-=S,s.back+=S}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}_=g>s.wnext?(g-=s.wnext,s.wsize-g):s.wnext-g,g>s.length&&(g=s.length),p=s.window}else p=r,_=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?G:L)(s.check,r,h,o-h)),h=l,(s.flags?u:x(u))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=u=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,u+=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?G:L)(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&&L(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"),P=[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,S=0,I=0,E=0,C=0,M=0,y=0,O=0,A=0,T=0,R=null,D=0,b=new w.Buf16(16),N=new w.Buf16(16),L=null,G=0,f=0;f<=15;f++)b[f]=0;for(S=0;S<n;S++)b[t[s+S]]++;for(C=v,E=15;1<=E&&0===b[E];E--);if(E<C&&(C=E),0===E)r[i++]=20971520,r[i++]=20971520,a.bits=1;else{for(I=1;I<E&&0===b[I];I++);for(C<I&&(C=I),f=O=1;f<=15;f++)if((O=(O<<1)-b[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]+b[f];for(S=0;S<n;S++)0!==t[s+S]&&(o[N[t[s+S]]++]=S);if(g=0===e?(R=L=o,19):1===e?(R=P,D-=257,L=U,G-=257,256):(R=k,L=F,-1),f=I,h=i,y=S=T=0,c=-1,d=(A=1<<(M=C))-1,1===e&&852<A||2===e&&592<A)return 1;for(;;){for(m=o[S]<g?(p=0,o[S]):o[S]>g?(p=L[G+o[S]],R[D+o[S]]):(p=96,0),l=1<<(_=f-y),I=u=1<<M;r[h+(T>>y)+(u-=l)]=_<<24|p<<16|m,0!==u;);for(l=1<<f-1;T&l;)l>>=1;if(0!==l?T=(T&l-1)+l:T=0,S++,0==--b[f]){if(f===E)break;f=t[s+o[S]]}if(C<f&&(T&d)!==c){for(h+=I,O=1<<(M=f-(y=0===y?C:y));M+y<E&&!((O-=b[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"),_=e("./zlib/constants"),n=e("./zlib/messages"),r=e("./zlib/zstream"),i=e("./zlib/gzheader"),p=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!==_.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]"===p.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==_.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?_.Z_FINISH:_.Z_NO_FLUSH,"string"==typeof e?a.input=g.binstring2buf(e):"[object ArrayBuffer]"===p.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,_.Z_NO_FLUSH))===_.Z_NEED_DICT&&u?d.inflateSetDictionary(this.strm,u):s)===_.Z_BUF_ERROR&&!0===c&&(s=_.Z_OK,c=!1),s!==_.Z_STREAM_END&&s!==_.Z_OK)return this.onEnd(s),!(this.ended=!0)}while(!a.next_out||0!==a.avail_out&&s!==_.Z_STREAM_END&&(0!==a.avail_in||n!==_.Z_FINISH&&n!==_.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!==_.Z_STREAM_END);return(n=s===_.Z_STREAM_END?_.Z_FINISH:n)===_.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===_.Z_OK):n!==_.Z_SYNC_FLUSH||(this.onEnd(_.Z_OK),!(a.avail_out=0))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===_.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"),Pt=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=500,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}=c.get("instance"),n=st(t);return ot(s?Ze.TEST[n].DEFAULT:Ze.PRODUCTION[n].INITIAL.replace("*",""+t),{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);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 Qe(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=l+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._ssoLog({method:"connect",message:e}),console.log(e)}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=500,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 I(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=function(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),t=st(t);if(s)return ot(Ze.TEST[t].DEFAULT,{isBinary:e});let n=Ze.PRODUCTION[t],r=Se&&n.ANYCAST;return ot({[nt.INITIAL]:()=>(it=nt.DEFAULT,n.DEFAULT),[nt.DEFAULT]:()=>(it=nt.BACKUP,n.BACKUP),[nt.BACKUP]:()=>(it=r?nt.ANYCAST:nt.DEFAULT,r?n.ANYCAST:n.DEFAULT),[nt.ANYCAST]:()=>(it=nt.DEFAULT,n.ANYCAST="",n.DEFAULT)}[it](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Dt,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,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,reason:"socket_error"}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},t=l+` onSendFail sendFailSocketId: ${e} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:t}),console.warn(t),e===this._connectionId&&this._handleConnectStateChange({state:Dt,reason:Nt}),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=wt.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,ErrorCode:n=n,ErrorInfo:r=r}=(null==e?void 0:e.body)||{},t=""+t+s,{resolve:s,reject:i}=this._pendingRequests.get(t);this._pendingRequests.delete(t),n&&0!==n?(W.emitInnerEvent("error",{errorCode:n,errorInfo:r}),i({errorCode:n,errorInfo:r})):s(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(It.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Rt})}_sendAck(e){e=ht({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return I(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 I(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,reason:Nt})}})}_sendHeartbeatIfReady(){return I(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,reason:bt}):this._handleConnectStateChange({state:Dt,reason:bt})}isPrivateNetWork(){var e=c.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:t,reason:s}=e;if(this._currentConnectState!==t){let e=l+`._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: `+s;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,W.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===Dt&&W.emitInnerEvent(It.SOCKET_DISCONNECTED),t!==Dt&&t!==Rt||(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,reason:"activity_status_change"})}_resetReconnectDelay(){lt.removeTask(Tt);var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive;this._intendedDelay=e?500:1e3}_scheduleReconnectWithBackoff(){var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(500,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){I(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){I(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),Pt.init()},destroy:function(){Pt.dispose(),c.clear(),lt.dispose()},notificationCenter:W,channel:Pt,store:c,ssoLog:Ot,utils:t,common:i,constants:e};(M=L=L||{}).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";var u=L;(m=Ys=Ys||{}).LOGOUT="logout",m.DESTROY="destroy",m.CLOUD_CONFIG_UPDATE="cloud_config_update",m.PROFILE_UPDATE="profile_updated",m.ERROR="error",m.RECONNECTED="reconnected",m.FORCE_OFFLINE="im_open_status.stat_forceoffline",m.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",m.OVERLOAD_PUSH="OverLoadPush.notify2",m.NEW_MESSAGE="new_message",m.MESSAGE_PUSH="im_open_push.msg_push",m.MESSAGE_DELETED="message_deleted",m.MESSAGE_REVOKED="message_revoked",m.MESSAGE_MODIFIED="message_modified",m.SOCKET_DISCONNECTED="socket_disconnected",m.CONVERSATION_UPDATED="conversation_updated",m.TOPIC_MESSAGE_DELETED="topic_message_deleted",m.TOPIC_MESSAGE_REVOKED="topic_message_revoked",m.TOPIC_MESSAGE_MODIFIED="topic_message_modified",m.TOPIC_NEW_MESSAGE="topic_new_message",m.QUALITY_STAT="quality_stat";var Ut,o=Ys,kt=((t=ca=ca||{}).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",ca);let Ft=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"},qt=((i=Ut=Ut||{}).UNSENT="unSend",i.SUCCESS="success",i.FAIL="fail",{modify:o.MESSAGE_MODIFIED,delete:o.MESSAGE_DELETED,revoke:o.MESSAGE_REVOKED}),Vt=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:Ut}),Bt={[qt.modify]:o.TOPIC_MESSAGE_MODIFIED,[qt.delete]:o.TOPIC_MESSAGE_DELETED,[qt.revoke]:o.TOPIC_MESSAGE_REVOKED},jt={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"},Kt=Object.assign({},jt),Ht={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Wt=Object.assign(Object.assign(Object.assign(Object.assign({},Ht),{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"}),$t=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"}),Yt={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},zt={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Jt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Yt),{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:zt}),C=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Ft),Vt),Kt),Wt),$t),Jt),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),Xt={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,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},Qt={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},a={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"},d={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"},Zt={[a.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:d.USER_STATUS_UPDATE},{stepId:d.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:d.UNREAD_MESSAGE_SYNC},{stepId:d.CONVERSATION_RECOVER},{stepId:d.HISTORY_MESSAGE_RECOVER,dependency:d.CONVERSATION_RECOVER},{stepId:d.BLACKLIST_RECOVER},{stepId:d.FRIEND_RECOVER},{stepId:d.GROUP_REVOKED_NOTICE_RECOVER},{stepId:d.TOPIC_REQUEST_INFO_RESET},{stepId:d.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:d.UNREAD_MESSAGE_SYNC},{stepId:d.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:d.UNREAD_MESSAGE_SYNC},{stepId:d.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[d.UNREAD_MESSAGE_SYNC,d.CONVERSATION_RECOVER]},{stepId:d.EMIT_C2C_MESSAGE_EVENT,dependency:[d.UNREAD_MESSAGE_SYNC,d.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[a.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:d.COMMERCIAL_CONFIG_UPDATE},{stepId:d.CLOUD_CONFIG_SYNC},{stepId:d.USER_PROFILE_SYNC},{stepId:d.UNREAD_MESSAGE_SYNC},{stepId:d.FRIEND_AND_BLACKLIST_SYNC},{stepId:d.GROUP_LIST_SYNC},{stepId:d.CONVERSATION_LIST_SYNC},{stepId:d.SIGNALING_MESSAGE_RECOVER,dependency:d.UNREAD_MESSAGE_SYNC},{stepId:d.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[d.UNREAD_MESSAGE_SYNC]},{stepId:d.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[d.UNREAD_MESSAGE_SYNC,d.CONVERSATION_LIST_SYNC]},{stepId:d.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[d.GROUP_LIST_SYNC,d.CONVERSATION_LIST_SYNC]},{stepId:d.CONVERSATION_GROUP_LIST_SYNC},{stepId:d.CONVERSATION_GROUP_UPDATE,dependency:[d.CONVERSATION_LIST_SYNC,d.CONVERSATION_GROUP_LIST_SYNC]},{stepId:d.QUALITY_REPORT}],[a.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:d.HANDLE_C2C_NEW_MESSAGE},{stepId:d.UNREAD_MESSAGE_SYNC},{stepId:d.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:d.HANDLE_C2C_NEW_MESSAGE},{stepId:d.EMIT_C2C_MESSAGE_EVENT,dependency:[d.HANDLE_C2C_NEW_MESSAGE,d.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:d.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[d.UNREAD_MESSAGE_SYNC]}],[a.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:d.HANDLE_GROUP_NEW_MESSAGE},{stepId:d.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:d.HANDLE_GROUP_NEW_MESSAGE},{stepId:d.UPDATE_GROUP_NEXT_SEQUENCE,dependency:d.HANDLE_GROUP_NEW_MESSAGE},{stepId:d.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:d.HANDLE_GROUP_NEW_MESSAGE},{stepId:d.EMIT_GROUP_MESSAGE_EVENT,dependency:[d.HANDLE_GROUP_NEW_MESSAGE,d.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},es={REACT:"atomicx_react",VUE3:"atomicx_vue3"},ts={[es.REACT+"_web"]:40,[es.REACT+"_h5"]:41,[es.VUE3+"_web"]:42,[es.VUE3+"_h5"]:43},ss={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},ns={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var rs=Object.freeze({__proto__:null,ERROR_CODE:Xt,InnerEvent:o,OuterConstant:C,OuterEvent:u,QUALITY_METRICS:ss,SDK_EDITION:Qt,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:ns,SignalingEvent:kt,UIKIT_PREFIX:es,UI_PLATFORM:ts,WORKFLOW_DEFINITIONS:Zt,WORKFLOW_NAME:a,WORKFLOW_STEP:d});function is(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 h extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:n="",data:r=""}=e;let i=n;s&&!n&&(i=is(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 os(e,t){if(e&&!0!==(null==(e=k.store.get("login"))?void 0:e.isLoggedIn))throw new h({code:Xt.USER_NOT_LOGGED_IN,functionName:t})}let as=e=>"function"==typeof e;function ls(t,s,n){if(Array.isArray(t))for(let e=0;e<t.length;e++)us.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:n}));else for(var e in t)us.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:n,key:e}))}function us({required:e,rules:n,value:t,allowEmpty:r,name:i,key:o,customValidator:a}){if(void 0===t){if(e)throw new h({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 h({functionName:i,message:e})}if(!1===r){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new h({functionName:i,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new h({functionName:i,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new h({functionName:i,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let cs=[],ds={},hs={};function gs(e,t){var s;os(ds[e],e),ls(hs[e],t,e),s=e,cs.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function _s(e,t){cs.push({interceptor:e,context:t})}function ps(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(hs,e),t&&"object"==typeof t&&Object.assign(ds,t)}var ms=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_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=>{t.has(e)||(e&&as(e.install)?(t.add(e),as(e.getInstalledSubPlugins)?e.install(_l(),r):e.install(_l()),as(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):as(e)?(t.add(e),e(_l()),as(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isLoggedIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}};function vs(e){return k.store.get("commercialConfig").get(e)}let fs=new Map;var g=new class{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)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,n){this._handlers.has(e)?Zt[e].find(e=>e.stepId===t)?this._handlers.get(e).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 I(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){console.log(`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=Zt[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 I(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 h({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(Zt).forEach(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(Zt).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return Zt[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 Ss=({type:e,groupID:t})=>e===C.GRP_COMMUNITY||(""+t).startsWith(zt.COMMUNITY)&&!(""+t).includes(zt.TOPIC),Is=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(zt.COMMUNITY)&&(""+e).includes(zt.TOPIC)},Es="openim",Cs="million_group_open_http_svc";function Ms(s){return I(this,void 0,void 0,function*(){var{servcmd:e,data:t}=ys(e=s.data)||Os(e)?function(e){let{servcmd:t,data:s}=e;var n,r,i;return Os(s)?({servcmd:e,data:n}=e,{GroupId:r=""}=n,[r]=(i=r).split(zt.TOPIC),{servcmd:As(e),data:Object.assign(Object.assign({},n),{GroupId:r,TopicId:i})}):{servcmd:t=ys(s)?As(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 ys(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return Ss({type:e,groupID:t})}function Os(e){var{GroupId:e=""}=e;return Is(e)}function As(e){return e.includes(Es)?e:(e=e.split(".")[1],Cs+"."+e)}function _(){var e;return null==(e=k.store.get("login"))?void 0:e.userId}let Ts=e=>J(e)||X(e),Rs=(s,n,r,i)=>{if(!Ts(s)||!Ts(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(Ts(s[a])&&Ts(n[a]))o+=Rs(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},Ds=(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""}},bs=[{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}],Ns="im_sdk_config_mgr.fetch_config",Ls="im_sdk_config_mgr.push_configv2",Gs="cloud-config";var ws=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(Ls,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(bs),i.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t,s={code:0,data:""};return e&&(s.data=(null==(t=this._core.store.get("cloudConfig"))?void 0:t[e])||""),s}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 I(this,void 0,void 0,function*(){try{var e=(this._core.store.get("instance")||{})["sdkAppId"],t=this._core.helper.generateProtocolData({servcmd:Ns,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=""+t.head.seq+Ns;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 I(this,void 0,void 0,function*(){try{var e;this._canFetch()&&(e=yield this._fetchCloudConfig(),this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:Gs,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}})}_fetchCloudConfigIfReady(){return I(this,void 0,void 0,function*(){if(this._canFetch())try{var e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}})}_updateCloudConfig(e){e=this._parseCloudConfig(e);e&&(this._core.store.set("cloudConfig",e),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,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(){var e,t=null==(e=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(Gs),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(bs),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ls,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class p{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 Ps={SEARCH_GRP_SNS:new p(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new p(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new p(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new p(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new p(0,Math.pow(2,6)).toString(),USER_STATUS:new p(0,Math.pow(2,7)).toString(),CONV_MARK:new p(0,Math.pow(2,9)).toString(),CONV_GROUP:new p(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new p(0,Math.pow(2,11)).toString(),MSG_EXT:new p(0,Math.pow(2,13)).toString(),GRP_COUNTER:new p(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new p(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new p(Math.pow(2,7)).toString(),PLUGIN_CS:new p(Math.pow(2,8)).toString(),PLUGIN_PUSH:new p(Math.pow(2,9)).toString(),PLUGIN_BOT:new p(Math.pow(2,10)).toString(),MSG_REACTION:new p(Math.pow(2,16)).toString(),FOLLOW:new p(Math.pow(2,20)).toString()},Us="CommercialConfig",ks="commercial-config";var Fs,xs,qs=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map}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)}isCommercialAbilityEnabled(e){return I(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 p(0,2**t):new p(2**(t-32),0)).toString(),!this._featureMap.get(r))){i=!1;break}return console.log(Us+`.isFeatureEnabled decimalNumber:${e} key:${r} ret:`+i),{code:0,data:{enabled:i}}})}_fetchAndParseCommercialConfig(){return I(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 I(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:ks,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 I(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(Us+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(console.error(Us+`._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._featureMap.clear(),this._methodKeyMap.clear();var n;for(let e=s.length-1,t=0;0<=e;e--,t++)if(n=(t<32?new p(0,2**t):new p(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(n,!0);let e=this._getKeyByValue(Ps,n);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(n,!1);let e=this._getKeyByValue(Ps,n);e&&this._methodKeyMap.set(e,!1)}}else console.warn(Us+".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(ks),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}},Vs=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)}},e=new class{constructor(){this._core=null}install(e){return I(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 I(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}}};(M=Fs=Fs||{})[M.START_SYNC=0]="START_SYNC",M[M.SYNCING=1]="SYNCING",M[M.SYNC_COMPLETE=2]="SYNC_COMPLETE",(L=xs=xs||{})[L.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",L[L.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED";var m=new class{constructor(){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 I(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=Fs.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?xs.NEW_MESSAGE_RECEIVED:xs.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 I(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return I(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 I(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 I(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 I(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,I){let n=[],r=[];return null!=e&&e.forEach(S=>{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:_,IsPeerRead:p,MsgFlagBits:m,MsgVersion:v,EventArray:f}=S;return{from:e,avatar:t,nick:s,needReadReceipt:1===n,readReceiptSentByPeer:p,clientTime:i,messageFlagBits:m,random:o,sequence:a,time:l,messageControlInfo:u,isSupportExtension:c,to:d,tinyID:h,checkResult:g,cloudCustomData:_,messageVersion:v,eventArray:f,elements:I.message.messageHelper.parseServerPushMessageElement(r)}}();if(null!=(t=null==(e=null==(e=null==S?void 0:S.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))r.push(...function(){let e,t=[];return null!=(e=S.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=I.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===Fs.START_SYNC||t===Fs.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()}},Bs=new class{init(e){this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),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()}},js=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()}},Ks=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?js:Bs).init(e)}};var Hs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(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()}},Ws=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(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,{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()}},$s=new class{init(e){var t=e.helper["IN_WX_MINI_APP"];(t?Ws:Hs).init(e)}},Ys=new class{install(e){Ks.init(e),$s.init(e)}};let zs=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.*"]),Js="tui_room_svr.*",Xs=new class{constructor(){this._transferredCommands=zs}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 I(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=Js}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(i,o){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=Js,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=zs}_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",Qs="signaling-timeout";function Zs(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 en(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function tn(e,t){return e.toString(16).padStart(t,"0")}function sn(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 nn,rn,on,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()}},an=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[tn(sn(32),8),tn(sn(16),4),tn(16384|sn(12),4),tn(32768|sn(14),4),tn(sn(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},ln=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 I(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}=an.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:Qs+"-"+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 I(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,an.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 I(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,an.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 I(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,an.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 I(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=S(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!==Zs([e]).length)return e={businessID:(e=en(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 I(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 I(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}=an.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}},un=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=en(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){f.getSignalingListenStatus()&&0!==(e=Zs(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){f.getSignalingListenStatus()&&0<(e=Zs(e.data)).length&&e.forEach(e=>{var t=en(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:Qs+"-"+n,intervalMs:1e3*e,callback:ln.handleInvitationExpiryTimer.bind(ln,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)}},cn=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=Zs([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();un.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=en(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 dn={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}}},hn={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0},gn=new class{install(e){ln.init(e),un.init(e),an.init(e),f.init(e),cn.init(e),e.helper.registerValidateConfig({auth:hn,params:dn})}},E=new class{init(e){this.core=e}},_n=((t=nn=nn||{}).MSG_TEXT="TIMTextElem",t.MSG_CUSTOM="TIMCustomElem",t.MSG_LOCATION="TIMLocationElem",t.MSG_FACE="TIMFaceElem",(ca=rn=rn||{})[ca.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",ca[ca.HAS_MORE_DATA=1]="HAS_MORE_DATA",ca[ca.NO_MORE_DATA=2]="NO_MORE_DATA",(i=on=on||{})[i.FORWARD=0]="FORWARD",i[i.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"}),pn="16k_zh-PY",mn={[_n.ZH_CN]:"16k_zh",[_n.EN_US]:"16k_en",[_n.YUE_HK]:"16k_yue",[_n.JA_JP]:"16k_ja",[_n.ZH_PY]:pn},vn=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,fn={READ:0,UNREAD:1},Sn="C2C",In="GROUP";function En(i){return I(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(Sn,""),t=yield function(t){return I(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 Cn(a){return I(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 Mn(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 yn(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 On(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 An=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,_){return I(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,_),o===e.CONV_C2C?yield function(o,a){return I(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:_},this._core):o===e.CONV_GROUP&&(yield function(n,r){return I(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:_,sequence:h},this._core)),r.setLogInfo({message:`conversationID:${s} messageID:${i} reactionID:`+_}).end(),{code:0}}catch(e){this._removeMyReactionRecord(i,_);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 I(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 I(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 I(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 I(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 I(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 I(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 I(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 I(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 I(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 I(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 I(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=>I(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}},Tn=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 I(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 I(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 I(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 I(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 I(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 I(this,void 0,void 0,function*(){let{constants:e,common:n}=this._core,{message:t,filter:o=fn.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 I(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===fn.READ?r.readUserIDList=n.map(e=>e.Read_Account):o===fn.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=Mn({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=Mn({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 Rn(o,a,l){return I(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 Dn(n,r,i){return I(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 bn=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 I(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 Rn(d,c,1):s===e.CONV_GROUP&&(n=yield Dn(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 I(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 I(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 Rn(h,d,l):r===t.CONV_GROUP&&(n=yield Dn(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 I(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 Nn={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"}},Ln={setMessageExtensions:[Nn,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Nn],deleteMessageExtensions:[Nn]},Gn=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}}}),Ln),wn=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 Pn{constructor(e){this._core=e}deleteMessage(s){return I(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 I(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 Un{constructor(e){this._core=e}deleteMessage(s){return I(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 I(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 kn{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 I(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)}})}filterValidMessages(e){return e.filter(e=>{var t=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:`+e.sequence}).end(),t&&!s})}_fetchUserInfos(t){return I(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 Fn=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Un(e),this._c2cMessageAction=new Pn(e),this._messageHelper=new kn(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 I(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 I(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 I(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 I(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 xn{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new xn({index:e,data:t})}constructor(e){this.type=nn.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 qn{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new qn({description:e,longitude:t,latitude:s})}constructor(e){this.type=nn.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 Vn=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(nn.MSG_FACE,xn),e.message.messageFactory.registerElementClass(nn.MSG_LOCATION,qn),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 xn({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 qn({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 Bn=class{init(e){this._messageHelper=new kn(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 I(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return I(this,void 0,void 0,function*(){let o=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:a}}=this._core;s.forEach(e=>{var{MsgRand:e,MsgSeq:t,To_Account:s,From_Account:n,RevokerInfo:{Revoker_Account:r,Revoke_Reason:i,Reason:i=i}}=e,s=a()===n?"C2C"+s:"C2C"+n,n=this._messageHelper.generateRevokeMessage({conversationID:s,sequence:t,random:e,revoker:r,revokeReason:i});o.push(n)}),0<o.length&&(yield this._messageHelper.updateRevokerInfo(o),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:o}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return I(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)}},jn=class{init(e){this._messageHelper=new kn(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){e=e.GroupTips;null!=e&&e.forEach(e=>{var t;Array.isArray(null==(t=null==e?void 0:e.MsgBody)?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(n){return I(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e}}=n,u=[],{notificationCenter:t,OuterEvent:s}=this._core;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});u.push(i)}),0!==u.length&&(yield this._messageHelper.updateRevokerInfo(u),t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:u}))}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 Kn=new class{constructor(){this._c2cMessageReceiver=new Bn,this._groupMessageReceiver=new jn}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class Hn{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new kn(e)}getRoamingMessagesByAnchor(n){return I(this,void 0,void 0,function*(){try{var o=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:e,direction:a,sequence:l}=n,u=t.replace(In,"");let i=l;if(a===on.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};i=l+e-1}var s={GroupId:u,ReqMsgNumber:e,WithRecalledMsg:1,Version:1},c=(i&&(s.ReqMsgSeq=i),yield this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_get",data:s}));if(c){let{RspMsgList:t=[],NextReqMsgSeq:e=0,IsFinished:s,InvisibleMsgSeq:n}=c;o.setLogInfo({message:`groupID:${u} sequence:${l} reqSeq:${i} direction:${a}
3
- complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+n}).end();var d=[];for(let e=0;e<t.length;e++){var h=t[e],g=this._parseMessage(h);d.push(g)}d.reverse();let r=s===rn.NO_MORE_DATA;return a===on.BACKWARD&&(r=d[d.length-1].sequence>=l),{messageList:this._messageHelper.filterValidMessages(d),invisibleSequenceList:n,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:r}}}catch(e){t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(t).end()}})}recoverHistoryMessage(e){return I(this,void 0,void 0,function*(){let{message:{messageReceiver:d,messageDataHandler:h},notificationCenter:g,OuterEvent:_,constants:{OuterConstant:s}}=this._core,n=[];null!=e&&e.forEach(t=>I(this,void 0,void 0,function*(){let{conversationID:a,lastMessage:e}=t,l=this._getLocalLastMessageSequence(a);var u=e.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:l,serverLastMessageSequence:u})){let e=u-l;var c;let t=Math.ceil(e/20);for(let e=0;e<t;e++)try{let e=u-l,t=Math.min(20,e),s=yield this.getRoamingMessagesByAnchor({conversationID:a,sequence:l+t,direction:on.FORWARD,count:t}),{nextReqMessageIDFromServer:n,hasNoMoreHistoryMessage:r,messageList:i}=s,o=(c=r&&n<0,l=i[i.length-1].sequence,[]);if(Array.isArray(i)&&(i.forEach(e=>{d.groupMessageReceiver.updateMessageProfile(e),h.storeConversationMessage(e)&&o.push(e)}),0<o.length)&&g.emitOuterEvent(_.MESSAGE_RECEIVED,{name:_.MESSAGE_RECEIVED,data:o}),c)break}catch(e){console.debug(e);break}}else n.push(a.replace(s.CONV_GROUP,""))})),this._recoverGroupRevokeNotice(n)})}updateLastMessageSequenceMapOnDisconnect(){let e=this._core.message.messageDataHandler.getContinuousMessagesByConversation();for(var[t,s]of e)if(!t.startsWith("C2C")){let e=Array.from(s.values());0<(null==e?void 0:e.length)&&(s=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,s))}}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&e&&1<=t&&t<300}_getLocalLastMessageSequence(e){return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(e=this._core.message.messageDataHandler.getLocalMessageList(e))[e.length-1])?void 0:e.sequence}_parseMessage(e){var t=this._core["constants"]["OuterConstant"],t=(In,4===e.Event&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),this._core.message.messageHelper.parseServerGroupMessage(e)),e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:"GROUP",flow:"in"}));return e.setElement(t.elements),e}_recoverGroupRevokeNotice(e){let n=this._filterValidGroupIDList(e);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 I(this,void 0,void 0,function*(){var e;try{var t=yield function(i){return I(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 I(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 Wn{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new kn(e)}getRoamingMessagesByAnchor(_){return I(this,void 0,void 0,function*(){var r;try{var{conversationID:i,count:e,messageID:n,time:o,direction:a}=_;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(Sn,""),u=yield function(i){return I(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._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){Sn;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 $n=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new Hn(e),this._c2cMessageHistory=new Wn(e),this._messageHelper=new kn(e);var{InnerEvent:t,notificationCenter:s,constants:n}=e;e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerApi({apiName:"clearHistoryMessage",context:this}),e.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.HISTORY_MESSAGE_RECOVER,this._recoverHistoryMessage,this),s.subscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}getMessageList(e){return I(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(In)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:20,direction:on.FORWARD}):t.startsWith(Sn)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:20,direction:on.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 _=[];for(let e=0;e<g.length;e++)"in"!==g[e].flow?"out"!==g[e].flow||g[e].isRead||g[e].setIsRead(!0):_.push(g[e]);let t=0;if(c.type===h.CONV_C2C){let e=_.slice(-c.unreadCount).filter(e=>e.isRevoked).length;t=_.length-c.unreadCount-e}else t=_.length-c.unreadCount;for(let e=0;e<t&&!_[e].isRead;e++)_[e].setIsRead(!0)}yield Cn(t),t.startsWith(Sn)&&(yield En({messageList:a,conversationID:t}));var p=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,l.length+r),m=p.filter(e=>e.isRevoked),v=(yield this._messageHelper.updateRevokerInfo(m),{nextReqMessageID:o?"":String(i),messageList:p,isCompleted:o}),f=p.map(e=>e.sequence);return n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s}
4
- 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 I(this,void 0,void 0,function*(){var i,o;let{conversationID:e,sequence:a,time:t,direction:l=on.FORWARD}=n,u=this._core.helper["isEmpty"];if(![on.BACKWARD,on.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(In)){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===on.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:n,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==on.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(Sn)&&(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===on.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(g){return I(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 I(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(Sn)?r=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(In)&&(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 I(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(Sn)?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(Sn)&&(yield Cn(t),yield En({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)}_recoverHistoryMessage(){let{appStore:e,constants:{OuterConstant:{GRP_AVCHATROOM:t}}}=this._core,s=e.conversationStore.getConversationMap()||{};if(s instanceof Map){let e=[...s.values()].filter(e=>e.type===In&&e.groupProfile.type!==t);this._groupMessageHistory.recoverHistoryMessage(e)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}_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(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}},Yn=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(r){return I(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=r,n=yield function(i,o){return I(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})}})}},zn=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return I(this,void 0,void 0,function*(){let{message:e,language:t=_n.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=vn.exec(n))?void 0:i[1])||"mp3"),i=mn[t]||pn;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(!vn.test(e))throw new this._core.common.ChatError({code:2119})}};class Jn{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:_,groupID:p,_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?_.startsWith(t)?this.receiverUserID=a:_.startsWith(r)&&(this.receiverGroupID=a):p?(this.receiverGroupID=p,this.messageReceiver=p):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 Xn{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:n,PbMsgKey:r,JsonMsgKey:i}=e||{},e=e.map(e=>On(e));return new Xn({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 Jn(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:yn(a)}}}}var Qn=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:n}}=this._core=e;t.messageFactory.registerElementClass(n.MSG_MERGER,Xn),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 Xn(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 I(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 I(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:yn(e)};return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(n),s=n["payload"];r=new Xn(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 I(this,void 0,void 0,function*(){try{var e=i.payload,t=e["downloadKey"],s=S(e,["downloadKey","pbDownload","type","messageList"]),n=((yield function(e){return I(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=On(e);return new Jn(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)}})}},M=new class{install(e){this._core=e,E.init(e),Fn.init(e),Vn.init(e),Kn.init(e),$n.init(e),An.init(e),Yn.init(e),zn.init(e),Tn.init(e),Qn.init(e),bn.init(e),e.helper.registerValidateConfig({auth:wn,params:Gn}),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),Kn.dispose(),$n.dispose(),Tn.dispose(),bn.dispose()}_reset(){$n.reset()}},Zn=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(_,p){return I(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}=_,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)p(null,e);else{if(c&&!d.includes(c))return _.url=this._domainName2IP(d,c),_.uploadByIP=!0,this.request(_,p);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)};p(t,e)},_.onProgress&&h.upload&&(h.upload.onprogress=e=>{var{total:e,loaded:t}=e,s=Math.min(Math.floor(100*t/e),100);_.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 er=["unknown","image","video","audio","log"];var tr,sr=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":""},_={};if(o){let[e,t]=u.split("?sign=");t&&(d=e+"?sign="+encodeURIComponent(t),_.sign=decodeURIComponent(t),_.signature=decodeURIComponent(t))}let t={url:d,header:l,name:"file",filePath:a,formData:Object.assign(Object.assign({},g),_),timeout:s.timeout||3e5};if(i){let e=S(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?er[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 nr(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function rr(e){e=e||99999999;return Math.round(Math.random()*e)}function ir(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 or(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function ar(e,t){return Math.round(Number(e)*10**t)/10**t}function lr(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function ur(e){return e<=1048576?ar(e/1024,1)+"KB/s":ar(e/1048576,1)+"MB/s"}let cr="TIMImageElem",dr="TIMSoundElem",hr="TIMFileElem",gr="TIMVideoFileElem",y="RichMediaMessagePlugin",_r=["rich.my-imcloud.com","imrich.qcloud.com"],pr=((L=tr=tr||{}).UNSENT="unSend",L.SUCCESS="success",L.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 O=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(pr).some(e=>e.test(t))}extractFileFromInput(e){return nr(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?Array.isArray(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(s){return I(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=_r;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=_r}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})}},mr=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?sr:Zn,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return I(this,void 0,void 0,function*(){var t=y+" 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:${lr(e.size)} time:${o}ms speed:`+ur(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 ir(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:ir(Date.now(),!1),uploadSpeed:ur(1e3*e.size/ir(Date.now(),!1))}}_createCosOptions(h){return I(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=!O.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(y+" prepareUploadParams:",e);var t=e["file"],{IN_MINI_APP:s,IN_RN_APP:n}=O.getPlatformFlags(),s=s||n,n=s&&e.message.type!==hr,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+rr(999999)+e;return{fileName:or(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 I(this,void 0,void 0,function*(){var t=y+" fetchCosSignatureUrl",s=O.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 I(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=O.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 O.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:O.getPlatform(),uint32_sdkappid:O.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 I(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=O.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let vr=["jpg","jpeg","gif","png","bmp","image","webp"],fr={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Sr{constructor(e,t){this.instanceID=rr(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=O.addAuthToUrl(e.imageUrl||e.url||""),this.url=O.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=O.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Ir(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?S(i,["url"]):i}class Er{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=cr;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 Er({imageFormat:s,imageInfoArray:i,uuid:r})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:n,IN_BROWSER:r}=O.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 Sr(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=fr[e.toUpperCase()]||fr.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],Ir({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:O.removeAuthToUrl(e.imageUrl)}))}}var Cr=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(cr,Er),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(y+" 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:fr.UNKNOWN,uuid:O.generateUUID(n),file:n,imageInfoArray:[]},u=new Er(l);return s.setElement(u),this._messageOptionsMap.set(s.clientSequence,r),console.log(y+" 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(y+" createImageMessage error:",r),r}}upload(n){return I(this,void 0,void 0,function*(){console.log(y+" 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 I(this,void 0,void 0,function*(){var e=r["to"],{uploadOptions:e,response:t}=yield mr.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(y+" 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=O.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 Ir({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 I(this,void 0,void 0,function*(){console.log(y+" 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")),O.isSimpleCos()&&!O.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 I(this,void 0,void 0,function*(){try{var e=O.addAuthToUrl(n),{width:t=0,height:s=0}=yield O.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(y+" _processImage error:",e),e}}_processMiniAppImageFile(e){nr(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=O.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 I(this,void 0,void 0,function*(){var e=y+" getDownloadIP domainName: "+n;try{var t,s=yield function(o,a){return I(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 I(this,void 0,void 0,function*(){var t=y+"._getImageInfoArray";try{var e=yield function(o,a){return I(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)),vr.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: "+lr(20971520)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Mr=104857600;function yr(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}class Or{constructor(e){this.type=hr,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:O.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 Or({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:O.removeAuthToUrl(s),FileName:n,FileSize:r,UUID:e}}}_getFileInfo(e){return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(O.getPlatform().IN_UNI_NATIVE_APP&&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=rr(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 Ar=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(hr,Or),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(y+" 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:O.generateUUID(t),file:t},u=new Or(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,s),console.log(y+" 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(y+" createFileMessage error:",s),s}}upload(s){return I(this,void 0,void 0,function*(){console.log(y+" 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=O.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>Mr)throw new t({message:"File size exceeds limit: "+lr(Mr)});if(0===e.size)throw new t({code:2108})}_performFileUpload(n,r,t){return I(this,void 0,void 0,function*(){var e=r["to"],e=(yield mr.uploadToCOS({uploadFileType:1,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=O.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&&yr(e,"2.5.0")<0)throw new i({message:"WXChooseMessageFile requires SDK version 2.5.0 or higher"});if(n&&yr(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 Tr=["mp4","quicktime","mov"],Rr=104857600;class Dr{constructor(e){this.type=gr,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:O.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:O.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:O.addAuthToUrl(e.thumbUrl),snapshotUrl:O.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:_,ThumbUrl:p,SnapshotUrl:m}=e;return new Dr({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:_,thumbUrl:p,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;O.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),O.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),O.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:_,thumbUrl:p,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:O.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:_,ThumbUrl:O.removeAuthToUrl(p),SnapshotUrl:O.removeAuthToUrl(m)}}}}var br=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(gr,Dr),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(y+" 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:ar(t.videoFile.second,0),videoSize:t.videoFile.size,remoteVideoUrl:"",videoUrl:t.videoFile.url,videoUUID:O.generateUUID(t.videoFile),thumbUUID:O.generateUUID(t.videoFile,"jpg"),thumbWidth:t.width||200,thumbHeight:t.height||200,thumbUrl:t.thumbUrl,thumbSize:t.thumbSize,thumbFormat:"jpg"},u=new Dr(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(y+" createVideoMessage error:",s),s}}upload(n){return I(this,void 0,void 0,function*(){console.log(y+" 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=O.addAuthToUrl(t);return e.updateVideoUrl(t),O.isEmpty(s)||e.updateSnapshotInfo(s),n})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>Rr)throw new t({message:"File size exceeds limit: "+lr(Rr)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===Tr.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(n,r,s){return I(this,void 0,void 0,function*(){var e=r["to"],{response:e,uploadOptions:t}=yield mr.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),a){let e=O.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(y+" _processFile error:",e),e}}_processMiniVideoFile(e){var t=(null==(t=this._core)?void 0:t.utils)["IN_ALIPAY_MINI_APP"],s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(t)throw new s({message:"VideoUnsupportedInAlipay"});if(nr(e))throw new s({message:"FileUnsupportedInMiniApp"});return{url:(e=Array.isArray(e.tempFiles)?e.tempFiles[0]: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){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 I(this,void 0,void 0,function*(){try{console.log(y+" _getSnapshotInfoByUrl url:",r);var e,t,s,n=((yield function(i,o){return I(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:O.getPlatform(),cover_name:or(rr(99999)),snapshot_url:r},this._core))||{})["download_url"];return(console.log(y+" _getSnapshotInfoByUrl OK snapshotUrl:",n),O.isEmpty(n))?{}:(e=O.addAuthToUrl(n),{width:t=0,height:s=0}=yield O.probeImageWidthHeight(e),{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s})}catch(e){throw console.error(y+" _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 Nr{constructor(e){this.uploadProgress=0,this.type=dr,this.content={downloadFlag:2,second:e.second,size:e.size,url:O.addAuthToUrl(e.url),remoteAudioUrl:O.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 Nr({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:O.removeAuthToUrl(s),Download_Flag:t,Second:r,Size:n,UUID:e}}}}var Lr,Gr,wr,Pr,Ur,kr,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:"createAudioMessage",context:this}),null!=(t=null==n?void 0:n.messageFactory)&&t.registerElementClass(dr,Nr),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(y+" 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:O.generateUUID(i)},u=new Nr(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(y+" createAudioMessage error:",t),t}}upload(s){return I(this,void 0,void 0,function*(){console.log(y+" 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=O.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: "+lr(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(n,r,t){return I(this,void 0,void 0,function*(){var e=r["to"],e=(yield mr.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 xr={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}},qr={createImageMessage:xr,createAudioMessage:xr,createVideoMessage:xr,createFileMessage:xr},Vr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Br={TIMImageElem:Cr,TIMFileElem:Ar,TIMVideoFileElem:br,TIMSoundElem:Fr},jr=new class{install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:n,MSG_VIDEO:r}}=(this._core=e)["constants"];Cr.init(e),Ar.init(e),br.init(e),Fr.init(e),mr.init(e),O.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,n,r].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Vr,params:qr})}sendMessage(n,r){return I(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 I(this,void 0,void 0,function*(){var t,s;if(!0!==n._relayFlag)try{let t=Br[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=tr.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}})}},A=new class{init(e){this.core=e}},Kr=e=>{var{OuterConstant:t,utils:{isString:s}}=A["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},Hr=e=>{var{OuterConstant:t,utils:{isString:s}}=A["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},Wr=e=>{var{OuterConstant:t,utils:{isString:s}}=A["core"];return s(e)&&e===t.CONV_SYSTEM},$r=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:A.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 Yr(t){var{utils:{isString:e}}=A["core"],s=[];if(e(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}function zr(e){var t=A.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 Jr(e){var t=A.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}function Xr(e,t){var s=A.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}(t=Lr=Lr||{}).NOT_START="notStart",t.PENDING="pending",t.RESOLVED="resolved",t.REJECTED="rejected",(ca=Gr=Gr||{})[ca.C2C=1]="C2C",ca[ca.GROUP=2]="GROUP",(i=wr=wr||{})[i.C2C=8]="C2C",i[i.GROUP=2]="GROUP",(L=Pr=Pr||{})[L.OFF=0]="OFF",L[L.ON=1]="ON",Ur=Ur||{},Ur[Ur.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID",(t=kr=kr||{})[t.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",t[t.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",t[t.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE";class Qr{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=$r(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}}=A["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}}=A["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=$r(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=A["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}}=A["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var T=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:{MESSAGE_PUSH:i,NEW_MESSAGE:o,MESSAGE_DELETED:a,MESSAGE_REVOKED:l,MESSAGE_MODIFIED:u,CONVERSATION_UPDATED:c,LOGOUT:d,DESTROY:h}}=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(o,this._handleNewMessage,this),t.subscribeInnerEvent(i,s,this._handleNewGroupAtTips,this),t.subscribeInnerEvent(a,this._handleMessageDeleted,this),t.subscribeInnerEvent(l,this._handleMessageRevoked,this),t.subscribeInnerEvent(u,this._handleMessageModified,this),t.subscribeInnerEvent(c,this._handleConversationUpdated,this),t.subscribeInnerEvent(d,this._reset,this),t.subscribeInnerEvent(h,this._dispose,this),console.log(this._name+".init")}_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 Qr(o[r]),{conversationID:s,type:n}=t;if(!Jr(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 t,s,n,e=this.getLocalConversation(e);return!(!this._core.utils.isUndefined(e)&&(t=this._core.OuterConstant,s=e.type===t.CONV_TOPIC,n=e.type===t.CONV_GROUP&&e.subType===t.GRP_ROOM,e=e.type===t.CONV_GROUP&&e.subType===t.GRP_LIVE,s||n||e))}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 t=this._core["OuterConstant"],e=this.getLocalConversationList(),s=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||""!==e.messageRemindType&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(s+=e.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(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}}=this._core,{GROUP_AT_TIPS:l}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,l,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(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},Zr=new class{constructor(){this._name="SyncConversationList",this._pagingStatus=Lr.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:n}=this._core=e;s.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.CONVERSATION_RECOVER,this._syncConversationListOnReOnline,this),s.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,n.WORKFLOW_STEP.CONVERSATION_LIST_SYNC,this._syncConversationList,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),console.log(this._name+".init")}isSyncCompleted(){return this._pagingStatus===Lr.RESOLVED}_syncConversationListOnReOnline(){return I(this,void 0,void 0,function*(){return this._syncConversationList()})}_syncConversationList(){return I(this,void 0,void 0,function*(){yield this._pagingGetConversationList(!0),this._pagingStatus=Lr.RESOLVED,T.emitConversationListUpdate()})}_pagingGetConversationList(l){return I(this,void 0,void 0,function*(){try{this._pagingStatus=Lr.PENDING;var e=this._core["common"],t=yield function(i,o){return I(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:n,pagingPinnedStartIndex:r}=i;return o.common.buildAndSendPacket({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:r,TopTimeStamp:n}})})}({fromAccount:e.getCurrentUserID(),pagingTimeStamp:l?this._pagingTimeStamp:0,pagingStartIndex:l?this._pagingStartIndex:0,pagingPinnedTimeStamp:l?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:l?this._pagingPinnedStartIndex:0},this._core),{CompleteFlag:s,SessionItem:n=[],TimeStamp:r,StartIndex:i,TopTimeStamp:o,TopStartIndex:a}=t||{};if(0<n.length){let e=this._getConversationOptions(n);T.updateLocalConversationList({conversationUpdateFieldList:e,isFromGetConversations:!0,updateUnreadCount:!0}),T.emitConversationListUpdate()}this._pagingTimeStamp=r,this._pagingStartIndex=i,this._pagingPinnedTimeStamp=o,this._pagingPinnedStartIndex=a,1!==s&&this._pagingGetConversationList(l)}catch(e){throw console.error(this._name+"._pagingGetConversationList fail:",e),e}})}_getConversationOptions(e){let{isUndefined:t}=this._core["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===Gr.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===Gr.C2C&&!Jr(t)||2===e)}_assembleC2COption(e){var t=this._core["OuterConstant"],s=this._createUserprofile(e);return{conversationID:""+t.CONV_C2C+e.userID,type:t.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===wr.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:Yr(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t,{userID:e,nick:s,peerAvatar:n}=e;return null==(t=this._core.user.userProfile)?void 0:t.createProfile(e,[{tag:"Tag_Profile_IM_Nick",value:s},{tag:"Tag_Profile_IM_Image",value:n}])}_computeIsPeerRead(e){var t=this._core["common"],{lastC2CMsgFromAccount:e,time:s,c2cPeerReadTime:n}=e;return e===t.getCurrentUserID()&&s<=n}_assembleGroupOption(e){var t=this._core["OuterConstant"];return{conversationID:""+t.CONV_GROUP+e.groupID,type:t.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===wr.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:Yr(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;if(null!=(t=null==(t=this._core)?void 0:t.helper)&&t.isEmpty(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=this._core.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return S(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){var t=this._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}_patchTypeAndPayload(e){var{OuterConstant:t,utils:{isUndefined:s}}=this._core,{event:e,elements:n=[]}=e.lastMsg||{};return s(e)?{type:n[0]?n[0].type:null,payload:n[0]?this._amendLayersOverLimitProp(n[0].content):null}:{type:t.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=Lr.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}},ei=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return I(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:Zr.isSyncCompleted()}}})}_getConversationList(o){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(o))return T.getLocalConversationList();if(t(o))return 0===o.length?[]:T.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:n,hasUnreadCount:r,hasGroupAtInfo:i}=o;return T.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}},ti=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(n){return I(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,n){return I(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=zr(t);T.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},si=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return I(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,n){return I(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;T.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},ni=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return I(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=T.getLocalConversation(u);if(Wr(u))o.data.conversation=a;else{let t=!1;var l=Kr(u)?s:n;if(e(a)&&(t=!0,a=new Qr({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 ti.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 si.get([e]))}}}return o})}_handleC2CConversation(o,a){return I(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:kr.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=T.hasLocalConversation(i);console.log(this._name+`._handleC2CConversation conversationID:${i} hasLocalConversation: `+r),r?n.updateConversation(i,o):T.appendToPinnedConversation(o)})}_handleGroupConversation(n,r){return I(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(),T.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,n):T.appendToPinnedConversation(n)})}},ri=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return T.getTotalUnreadMessageCount()}},ii=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),T.markMessageAsRead({conversationID:e,lastReadTime:t}),T.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),T.markMessageAsRead({conversationID:e,lastReadSequence:t}),T.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(i){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=i["conversationID"],s={code:0,data:{}},n=T.getLocalConversation(t);if(console.log(this._name+`.setMessageRead conversationID:${t} unreadCount:`+((null==n?void 0:n.unreadCount)||0)),n){var r=!(null!=(r=null==(r=this._core)?void 0:r.helper)&&r.isEmpty(n.groupAtInfoList));if(n.type===e.CONV_GROUP&&r&&this._deleteGroupAtTips(t),0!==n.unreadCount){if(n.type===e.CONV_C2C){let e=this._getLocalMessageMaxTime(n);yield this._setC2CMessageRead(t,e)}if(n.type===e.CONV_GROUP){let e=this._getLocalMessageMaxSequence(n);yield this._setGroupMessageRead(t,e)}n.type===e.CONV_SYSTEM&&(n.unreadCount=0),T.emitConversationListUpdate()}}return s})}setAllMessageRead(){return I(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 I(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return A.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})&&T.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})&&T.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);T.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);T.markMessageAsRead({conversationID:s,lastReadSequence:e})}}T.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 I(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=T.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 I(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=T.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&T.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 I(this,void 0,void 0,function*(){try{yield function(e,t){return I(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),T.markMessageAsRead({conversationID:e,lastReadTime:t}),T.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(s,n){return I(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),T.markMessageAsRead({conversationID:e,lastReadSequence:t}),T.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)))}},oi=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=T.getLocalConversation(""+r.CONV_C2C+t):2===e&&(n=T.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&&T.emitConversationListUpdate(!0)}}pinConversation(e){return I(this,void 0,void 0,function*(){var{OuterConstant:t,common:s}=this._core,{conversationID:n,isPinned:r}=e,i={code:0,data:{conversationID:n}},o=T.getLocalConversation(n);if(o&&o.isPinned===r)return i;if(Wr(n))return o&&(o.isPinned=r),T.emitConversationListUpdate(!0),i;try{let e=null;Kr(n)?e={Type:1,To_Account:n.replace(t.CONV_C2C,"")}:Hr(n)&&(e={Type:2,GroupId:n.replace(t.CONV_GROUP,"")});var a=yield function(n,r){return I(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:s.getCurrentUserID(),operationType:!0===r?1:2,itemList:[e]},this._core);if(console.log(this._name+`.pinConversation ok, conversationID:${n} isPinned:${r}.`),a){if(o)o.isPinned!==r&&(o.isPinned=r);else{let e=new Qr({conversationID:n,type:Kr(n)?t.CONV_C2C:t.CONV_GROUP,isPinned:r});T.setLocalConversation(n,e)}T.emitConversationListUpdate(!0)}return i}catch(e){throw console.error(this._name+".pinConversation fail:",e),e}})}},ai=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 I(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:Ur.ONLY_CONVERSATIONID})):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return I(this,void 0,void 0,function*(){var{conversationIDList:s,clearHistoryMessage:n=!0,flag:r=0}=e;console.log(this._name+`._deleteConversation conversationIDList:${s} clearHistoryMessage:`+n);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:kr.CONV_NOT_FOUND});return console.log(this._name+"._deleteConversation ok."),{code:0,data:r===Ur.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t}}}catch(e){throw console.error(this._name+"._deleteConversation fail:",e),e}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!T.hasLocalConversation(e)&&((t=null==(t=T.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,i){return I(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;T.hasLocalConversation(e)&&(t=(null==(t=T.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 I(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=>{T.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&T.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=T.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(T.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&T.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)}},li=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return I(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),T.hasLocalConversation(e))return null!=(e=T.getLocalConversation(e))&&e.setDraftText(t),T.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:kr.CONV_NOT_FOUND})})}},ui=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return I(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}=A.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[l],t=yield function(s,n){return I(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})}),T.patchMessageRemindType(i,l),{code:0,data:{successUserIDList:r,failureUserIDList:n}}})}},ci=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(n,r){return I(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(n,r){return I(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;T.patchMessageRemindType([e],r)}return{code:0,data:{groupID:n,messageRemindType:r}}})}},di=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=zr(t);console.log(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+n),T.patchMessageRemindType(s,n)}})}setMessageRemindType(o){return I(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 ci.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 ui.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}})}},hi=new class{init(e){console.log("ConversationAction.init"),this._core=e,Zr.init(e),ei.init(e),ni.init(e),ri.init(e),ii.init(e),oi.init(e),ai.init(e),li.init(e),di.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)}handleLoginSuccess(){Zr.handleLoginSuccess()}_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"];ai.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];oi.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];oi.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;ii.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;di.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;ii.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)}},gi=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return I(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 I(this,void 0,void 0,function*(){var e=A.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?Pr.ON:Pr.OFF});return{code:0,data:{errorCode:i.ErrorCode,errorInfo:i.ErrorInfo}}}catch(e){Xr("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]}},_i=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 I(this,void 0,void 0,function*(){try{var e=yield function(){return I(this,void 0,void 0,function*(){var e=A.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){Xr("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===Pr.ON}}},pi=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,ui.init(e),ci.init(e),ti.init(e),si.init(e),gi.init(e),_i.init(e)}};let mi=e=>!Kr(e)&&!Hr(e)&&!Wr(e),vi={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!mi(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!mi(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!mi(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}}=A["core"];if(!n(e)&&!s(e))return"options is String or Object.";if(n(e)&&mi(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(mi(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=>!(!Kr(e)&&!Hr(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}}},fi={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0},Si=new class{install(e){A.init(e),hi.init(e),pi.init(e),T.init(e),e.helper.registerValidateConfig({auth:fi,params:vi})}handleLoginSuccess(){hi.handleLoginSuccess()}},Ii=new class{init(e){this.core=e}},Ei="AVChatRoom",Ci="GRP_COUNTER",Mi=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],yi=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Oi=["Role","JoinTime","MsgFlag","MsgSeq"],Ai=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Ti="notStart",Ri="resolved",Di="rejected",bi=["Owner","Admin","Member"],Ni=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Li={from:!0,groupID:!0,groupName:!0,to:!0},Gi={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},wi=e=>e===Ii.core.OuterConstant.GRP_PUBLIC,Pi=e=>e===Ii.core.OuterConstant.GRP_AVCHATROOM,Ui=(n,e)=>{var t=Ii.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},ki=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},Fi=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 xi(e,t){var s=Ii.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:3122,replacement1:e})}function qi(e,t){var s=Ii.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 Vi=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Bi{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}=Ii.core["utils"];for(t in e)Vi.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}}=Ii.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&&Ui(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=Ii.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 R=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 Bi(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 ji(o,a){return I(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 D(e){return{code:0,data:e||{}}}var Ki=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Ti,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 I(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}),R.updateLocalGroup(e),R.getLocalGroupList()}return console.log(this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===Di||this._pagingStatus===Ti?this._syncGroupList().then(()=>{var e=R.getLocalGroupList();return D({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw console.error(this._name+".getGroupList fail:",e),e}):(e=R.getLocalGroupList(),console.log(this._name+".getGroupList return group count:"+e.length),D({groupList:e,isSyncCompleted:this._isSyncCompleted()}))})}_syncGroupList(){return I(this,void 0,void 0,function*(){this._pagingStatus===Ti&&R.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Ri,this._groupListTreeShaking(t),R.updateLocalGroup(t);var s=R.getLocalGroupList();return console.log(this._name+"._syncGroupList ok, count:"+s.length),R.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Di,console.error(this._name+"._syncGroupList fail:",e),e}})}_pagingGetGroupList(e){return I(this,void 0,void 0,function*(){var{isCommunityRelay:r=!1,groupList:i}=e;let o,{limit:a,offset:l}=e;var u=[...Mi];r&&(o=this._core.OuterConstant.GRP_COMMUNITY,u.push("AtInfoList"));try{let e=yield ji({type:o,limit:a,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:u,SelfInfoFilter:[...Oi]}},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 I(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 ji({limit:a,offset:l,type:i.GRP_COMMUNITY,memberAccount:r(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...Mi],SelfInfoFilter:[...Oi]}},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([...R.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++)R.deleteLocalGroup(r[e])}_isSyncCompleted(){return this._pagingStatus===Ri}_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:_,MuteAllMember:p,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:S,Type:I,LastRecallTime:E,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],r=ki(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:_,muteAllMembers:p,name:m,nextMessageSeq:v,notification:f,ownerID:S,type:I,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}},Hi=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(a){return I(this,void 0,void 0,function*(){var i;this._preCheckParams(a);try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(g,_){return I(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?Fi(t):void 0}}):h,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return _.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},a),{ownerID:t()}),this._core),{GroupId:n,OverJoinedGroupLimit_Account:r=[]}=s||{};console.log(`${this._name}.createGroup ok, type:${a.type} groupID:${n} overLimitUserIDList:`+r),e(a.memberList)||e(r)||(a.memberList=null==(i=a.memberList)?void 0:i.filter(e=>r.includes(e.userID))),R.updateLocalGroup([Object.assign(Object.assign({},a),{groupID:n})]);var o=R.getLocalGroup(n);return this._notNeedSendCustomMessage(a)||(this._sendCustomMessage(n,a.type),R.emitGroupListUpdate()),D({group:o})}catch(e){throw console.error(this._name+".createGroup fail:",e),e}})}_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}=Ii.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!Pi(e)}_canIUseJoinOption(e){return wi(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,{})}},b=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={}}},Wi=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ei)})}dismissGroup(t){return I(this,void 0,void 0,function*(){console.log(this._name+".dismissGroup groupID:"+t);try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(t,this._core),console.log(this._name+".dismissGroup ok.");var e=R.getLocalGroup(t)["type"];return R.deleteLocalGroup(t),R.emitGroupListUpdate(),b.deleteGroupAttributesCache(t),D({groupID:t,type:e})}catch(e){throw console.error(this._name+".dismissGroup fail:",e),e}})}},$i=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return I(this,void 0,void 0,function*(){let{groupID:r,groupCustomFieldFilter:e}=t,i={groupIDList:[r],responseFilter:{GroupBaseInfoFilter:[...Mi],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...Ai]}};try{let e=yield this.getGroupProfileAdvance(i),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let n;return(n=!R.hasLocalGroup(r)&&Pi(t[0].type)?new Bi(t[0]):(R.updateLocalGroup(t),R.getLocalGroup(r))).isSupportTopic||R.updateConversationGroupProfile(r),console.log(this._name+".getGroupProfile ok."),D({group:n})}catch(e){throw console.error(this._name+".getGroupProfile fail:",e),e}})}getGroupProfileAdvance(a){return I(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 I(this,void 0,void 0,function*(){let{isCommunityProfile:t=!1}=e,o=S(e,["isCommunityProfile"]);if(0===o.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,n){return I(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:_,MemberNum:p,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:S,Owner_Account:I,ShutUpAllMember:E,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:O,ErrorInfo:A}=s[e],r=ki(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:_,memberCount:p,muteAllMembers:m,name:v,nextMessageSeq:f,notification:S,ownerID:I,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=ki(r);n.push({memberCustomField:r,joinTime:i,userID:o,messageRemindType:a,sequence:l,nameCard:u,role:c})}return n}},Yi=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()}},zi=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ei)})}joinGroup(e){return I(this,void 0,void 0,function*(){var t=e["groupID"];try{if(R.hasLocalGroup(t))try{return yield $i.getGroupProfile({groupID:t}),D({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS})}catch(e){console.warn(this._name+`.joinGroup ${t} was unjoined, start to join!`),R.deleteLocalGroup(t)}return yield this._applyJoinGroup(e)}catch(e){throw console.error(this._name+".joinGroup fail:",e),e}})}_applyJoinGroup(c){return I(this,void 0,void 0,function*(){var{OuterConstant:t,helper:e}=this._core,s=c["groupID"],n=Object.assign({},c),e=e.checkBusinessCapabilityBits("AV_HISTORY_MSG"),n=(e&&(n.historyMessageFlag=1),yield function(n,r){return I(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||{},e=`groupID:${s} joinedStatus:${r} longPollingKey:${i} startSeq:${o} avChatRoomFlag:${a} canGetAVChatRoomHistoryMsg:${e}, historyMessageCount:`+u.length;if(console.log(this._name+"._applyJoinGroup ok, "+e),r===t.JOIN_STATUS_WAIT_APPROVAL)return D({status:t.JOIN_STATUS_WAIT_APPROVAL,group:{groupID:s,type:n}});if(r!==t.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:2660});{let e=null;try{e=(yield $i.getGroupProfile({groupID:s})).data.group}catch(t){e=new Bi({groupID:s}),console.warn(this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${s}, errorCode:`,null==t?void 0:t.code)}return this._handleJoinResult({group:e,avChatRoomFlag:a,longPollingKey:i,startSequence:o,avChatRoomKey:l,historyMessageList:u})}})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:n}=e;return 1===s?(b.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:n}),Yi.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:n}),D(e)):(R.updateLocalGroup([t]),R.emitGroupListUpdate(),D({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}},Ji=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ei)})}quitGroup(t){return I(this,void 0,void 0,function*(){if(!R.hasLocalGroup(t))throw new this._core.helper.ChatError({code:2623});try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(t,this._core),console.log(this._name+".quitGroup ok, groupID:"+t);var e=R.getLocalGroup(t)["type"];return R.deleteLocalGroup(t),R.emitGroupListUpdate(),b.deleteGroupAttributesCache(t),D({groupID:t,type:e})}catch(e){throw console.error(this._name+".quitGroup fail:",e),e}})}},Xi=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return I(this,void 0,void 0,function*(){console.log(this._name+".searchGroupByID groupID:"+v);try{var e=yield function(t,s){return I(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...yi]};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:_}=t[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:_});console.log(this._name+".searchGroupByID ok.");var p=ki(s),m=new Bi({groupID:v,name:c,avatar:i,introduction:o,joinOption:n,inviteOption:a,maxMemberCount:l,memberCount:u,type:h,ownerID:d,createTime:r,groupCustomField:p});return D({group:m})}catch(e){throw console.error(this._name+".searchGroupByID fail:",e),e}})}},Qi=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(r){return I(this,void 0,void 0,function*(){let t=r["groupID"],{isUndefined:s}=this._core["utils"],n=R.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 I(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?Fi(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),R.emitGroupListUpdate()):n=new Bi(r),D({group:n})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}})}_canIUseJoinOption(e){return wi(e)||this._core.common.isCommunity({type:e})}},Zi=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(a){return I(this,void 0,void 0,function*(){let s="changeGroupOwner",{groupID:e,newOwnerID:t}=a,n=R.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 I(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,R.emitGroupListUpdate(),D({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}})}},eo=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(Ei)})}getGroupOnlineMemberCount(r){return I(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount",e=R.hasLocalGroup(r);if(console.log(`${this._name}.${s} groupID:${r} hasLocalGroup:`+e),!e)return D({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 D({memberCount:s})}try{let e=yield function(e,t){return I(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),D({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}})}},to=new class{init(e,t){console.log("GroupAction.init"),Ki.init(e),Hi.init(e),Wi.init(e,t),zi.init(e,t),Ji.init(e,t),Xi.init(e),$i.init(e),Qi.init(e),Zi.init(e),eo.init(e,t)}dismissGroup(e){return Wi.dismissGroup(e)}joinGroup(e){return zi.joinGroup(e)}quitGroup(e){return Ji.quitGroup(e)}getGroupOnlineMemberCount(e){return eo.getGroupOnlineMemberCount(e)}},so=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return I(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 D({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 I(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 I(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=S(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}}},no=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return I(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 I(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 I(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=R.getLocalGroup(n.groupID);return D({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}}},ro=new class{init(e){console.log("GroupApplication.init"),so.init(e),no.init(e)}};let io=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}}=Ii["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&&Ui(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function oo(a,l){return I(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?Fi(i):o};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var ao=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Ei)})}getGroupMemberList(n){return I(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=R.getLocalGroup(o),u=100<e?100:e,c={groupID:o,offset:a,limit:u,memberRoleFilter:bi.includes(t)?[t]:void 0,memberInfoFilter:Ni};try{let e=yield function(i,o){return I(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 D({memberList:[],offset:0});let r=a+u;g({groupID:o})&&(r=h(n)?0:n),t.length<u&&(r=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),p=this._generateGroupMember(_);return D({memberList:p,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=ki(r);n.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:r})}return n}_patchAvatarAndNick(i){return I(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 io(s[e]);n.push(r)}return n}},lo=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(t){return I(this,void 0,void 0,function*(){let s="getGroupMemberProfile",{groupID:n,userIDList:r,memberCustomFieldFilter:i}=t,e=R.getLocalGroup(n),{helper:o,utils:{isArray:a}}=this._core;if(e&&Pi(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 I(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:[...Ni]},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),D({memberList:u})):D({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=ki(r);n.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:r})}return n}_getMemberAvatarAndNick(i){return I(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 io(s[e]);n.push(r)}return n}},uo=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(t){return I(this,void 0,void 0,function*(){let o="addGroupMember",{groupID:a,userIDList:e}=t,l=R.getLocalGroup(a),s=this._core["helper"];if(l&&Pi(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 I(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),D({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(Ei)})}deleteGroupMember(o){return I(this,void 0,void 0,function*(){let s="deleteGroupMember",{groupID:e,userIDList:t}=o,n=R.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 I(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),D({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}})}},ho=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return I(this,void 0,void 0,function*(){let n="setGroupMemberMuteTime",t=this._core["helper"];this._preCheckSettingMuteParams(o);try{yield oo(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=R.getLocalGroup(e),i=new io({userID:t,muteTime:s});return D({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})}},go=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(o){return I(this,void 0,void 0,function*(){let n="setGroupMemberRole",t=this._core["helper"];this._preCheckSettingRoleParams(o);try{yield oo(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=R.getLocalGroup(e),i=new io({userID:t,role:s});return D({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=R.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=[...bi];if(o({groupID:e})&&a.push(i.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new r.ChatError({functionName:"setGroupMemberRole",code:2683})}},_o=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(l){return I(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 oo(n,this._core),console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} nameCard:`+s);var o=R.getLocalGroup(e),a=new io({userID:t,nameCard:s});return D({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=R.getLocalGroup(e);if(Pi(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:2687})}},po=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(l){return I(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 oo(n,this._core),console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} memberCustomField:`+JSON.stringify(s));var o=R.getLocalGroup(e),a=new io({userID:t,memberCustomField:s});return D({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=R.getLocalGroup(e);if(Pi(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:2687})}},mo=new class{init(e,t){console.log("GroupMember.init"),ao.init(e,t),lo.init(e),uo.init(e),co.init(e,t),ho.init(e),go.init(e),_o.init(e),po.init(e)}getGroupMemberList(e){return ao.getGroupMemberList(e)}deleteGroupMember(e){return co.deleteGroupMember(e)}},vo=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return I(this,void 0,void 0,function*(){var t="getGroupCounters";try{xi(t,Ci);var e,s,n,{groupID:r,keyList:i=[]}=l,{avChatRoomKey:o,lastUpdateTime:a}=Yi.getLocalGroupCounters(r);return Date.now()-a>=this._getExpireTime()&&(e=yield function(r){return I(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=r,n=Ii.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,Yi.updateLocalGroupCounters({groupID:r,counterList:s,groupCounterSeq:n})),{code:0,data:{counters:Yi.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)}},fo=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 I(this,void 0,void 0,function*(){return this._handleCounterOperation("Set",e)})}increaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Increase",e)})}decreaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Decrease",e)})}_handleCounterOperation(a,l){return I(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{xi(t,Ci);var{groupID:e,key:s,value:n=0}=l,r=Yi.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 Yi.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){qi(t,e)}})}_updateGroupCounters(i){return I(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:n}=i,r=Ii.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}))}},So=new class{init(e){this._core=e,vo.init(e),fo.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&&Yi.deleteLocalGroupCounters({groupID:n,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:n,notificationCenter:r}=this._core;Yi.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(){Yi.reset()}},Io=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return I(this,void 0,void 0,function*(){let n="initGroupAttributes",{groupID:r,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a}=b.getGroupAttributesCache(r),l=b.convertKeyValueMapToList(i);try{let e=yield function(r,i){return I(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 b.saveGroupAttributesCacheValuesCopy(r),b.refreshGroupAttributesCache({groupID:r,serverMainSequence:t,groupAttributeList:u,operation:1}),b.emitGroupAttributesUpdated(r),D({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}})}},Eo=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return I(this,void 0,void 0,function*(){let n="setGroupAttributes",{groupID:r,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a,values:l}=b.getGroupAttributesCache(r),u=b.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 I(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 b.saveGroupAttributesCacheValuesCopy(r),b.refreshGroupAttributesCache({groupID:r,serverMainSequence:t,groupAttributeList:c,operation:2}),b.emitGroupAttributesUpdated(r),D({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}})}},Co=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(a){return I(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),b.saveGroupAttributesCacheValuesCopy(e),b.refreshGroupAttributesCache({groupID:e,serverMainSequence:r,groupAttributeList:o,operation:i}),b.emitGroupAttributesUpdated(e),D({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 I(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=b.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 I(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 I(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=b.getGroupAttributesCache(n),s=[...s.keys()],t=((yield function(n,r){return I(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}})}},Mo=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(a){return I(this,void 0,void 0,function*(){let s="getGroupAttributes",t=a["groupID"],{avChatRoomKey:n,lastUpdateTime:e,localMainSequence:r,serverMainSequence:i}=b.getGroupAttributesCache(t);if(3e4<=Date.now()-e||r<i)try{yield this.getGroupAttributesFromServer({groupID:t,avChatRoomKey:n});let e=b.getGroupAttributesCacheValues(a);return console.log(this._name+`.${s} from server. groupID:`+t),D({groupAttributes: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}var o=b.getGroupAttributesCacheValues(a);return console.log(this._name+`.${s} from cache. groupID:`+t),D({groupAttributes:o})})}getGroupAttributesFromServer(n){return I(this,void 0,void 0,function*(){var e=this._core["utils"]["isUndefined"],{groupID:t,avChatRoomKey:s}=n,{AttrMainSeq:e=0,GroupAttrAry:s}=(yield function(n,r){return I(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))||{},s=(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}}));b.refreshGroupAttributesCache({groupID:t,serverMainSequence:e,groupAttributeList:s,operation:5})})}},yo=new class{init(e){console.log("GroupAttribute.init"),Io.init(e),Eo.init(e),Co.init(e),Mo.init(e),b.init(e)}isGroupAttributesUpdated(e){return b.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,n=s["groupAttributeOption"],{serverMainSequence:r,withChangedAttributeInfo:i}=n,o=b.getGroupAttributesCache(t)["localMainSequence"],a=r-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:`+a),0!=a)if(b.saveGroupAttributesCacheValuesCopy(t),1!==i||1!=a){if(b.hasGroupAttributesCache(t)){let e=b.getGroupAttributesCache(t)["avChatRoomKey"];Mo.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{b.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else b.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:n})}reset(){b.reset()}};function Oo(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?Ao:Ro)(h)}}function Ao(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=>To(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=To(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 To(e){var{ImageUrl:e,NickName:t,Role:s,UserId:n}=e;return{avatar:e,nick:t,role:s,userID:n}}function Ro(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 Do{constructor(e){this.type=Ii.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=Ao(e);return new Do(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];Li[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 bo=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{message:{messageFactory:e},OuterConstant:t}=this._core=e;null!=e&&e.registerElementClass(t.MSG_GRP_TIP,Do)}onNewGroupTips(e){var e=this._handleGroupTips(e)["messageList"],{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&(t.emitOuterEvent(s.MESSAGE_RECEIVED,{name:s.MESSAGE_RECEIVED,data:e}),this._handleGroupTipMessage(e))}_handleGroupTips(e){let{Event:s,GroupTips:n}=e,r=new Map,t=[],i=[];for(let t=0,e=n.length;t<e;t++){let e=Oo(n[t],"tips");if(6===s){if(yo.isGroupAttributesUpdated(e)){yo.handleGroupAttributesUpdated(e);continue}if(So.isGroupCounterUpdated(e)){So.handleGroupCounterUpdated(e);continue}}var o=e["groupProfile"]["groupID"];if(R.hasLocalGroup(o)){o=this._assembleMessage(e);if(6===s&&(o._onlineOnlyFlag=!0,i.push(o)),4===s){if(!this._core.message.messageDataHandler.storeConversationMessage(o))continue;i.push(o)}this._handleConversationOptions(r,o)}}return t.push(...r.values()),{conversationUpdateFieldList:t,messageList:i}}_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 Do(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{isEmpty:t}=this._core["utils"],{operationType:n,memberInfoList:r,operatorInfo:i}=e,o={};if(t(r)?t(i)||(o=i):1!==n&&3!==n&&4!==n&&5!==n||(o=Object.assign({},r[0])),!t(o)){let{nick:e="",avatar:t=""}=o;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{conversationID:s,conversationType:n}=t;let r;if(e.has(s))r=e.get(s),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||r.unreadCount++,r.type=n,r.lastMessage=t._isExcludedFromLastMessage?"":t;else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),r={conversationID:s,unreadCount:e,type:n,lastMessage:t._isExcludedFromLastMessage?"":t}}e.set(s,r)}_handleGroupTipMessage(e){e.forEach(e=>{var t=e.payload["operationType"];switch(t){case 1:this._handleNewMemberJoined(e);break;case 2:this._handleMemberQuitted(e);break;case 3:this._handleMemberKicked(e);break;case 6: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=R.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])}),R.emitGroupListUpdate(),R.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:n}=this._core,e=R.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=R.getLocalGroup(t),n=this._core["utils"]["isNumber"];s&&n(e)&&s.memberCount!==e&&(s.memberCount=e,R.emitGroupListUpdate(),R.updateConversationGroupProfile(t))}};class No{constructor(e){this.type=Ii.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=Ro(e);return new No(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];Gi[n]&&(this.content.groupProfile[n]=t[n])}}}var Lo=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,No)}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=Oo(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 No(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=R.hasLocalGroup(t);console.log(this._name+`._handleGroupJoinResult groupID:${t} type:${s} hasLocalGroup:`+n),n||Pi(s)||(R.updateLocalGroup([Object.assign({},e)]),R.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];R.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];R.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],t=e["groupID"],s=R.hasLocalGroup(t);console.log(this._name+`._handleGroupInvitedResult groupID:${t} hasLocalGroup:`+s),s||(R.updateLocalGroup([Object.assign({},e)]),R.emitGroupListUpdate())}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=R.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(Pi(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}R.deleteLocalGroup(s),R.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:n}}=this._core,n=""+n+e;s.getConversation(n)&&s.updateConversation(n,t)}},Go=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),bo.init(e),Lo.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){bo.onNewGroupTips(e)}_onNewGroupSystemNotification(e){Lo.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 N={required:!0,rules:["string"],allowEmpty:!1},wo={required:!0,rules:["number"],allowEmpty:!1},Po={required:!0,rules:["array"],allowEmpty:!1},Uo={required:!0,rules:["object"],allowEmpty:!1},ko={createGroup:{name:N,type:N},dismissGroup:[Object.assign({key:"groupID"},N)],joinGroup:{groupID:N,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},N)],searchGroupByID:[Object.assign({key:"groupID"},N)],getGroupProfile:{groupID:N,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:N,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:N,newOwnerID:N},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},N)],handleGroupApplication:{handleAction:N},getGroupMemberList:{groupID:N},getGroupMemberProfile:{groupID:N,userIDList:Po,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:N,userIDList:Po},deleteGroupMember:{groupID:N,userIDList:Po},setGroupMemberMuteTime:{groupID:N,userID:N,muteTime:Object.assign(Object.assign({},wo),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:N,userID:N,role:N},setGroupMemberNameCard:{groupID:N,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:N},setGroupMemberCustomField:{groupID:N,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Po},markGroupMemberList:{groupID:N,markType:Object.assign(Object.assign({},wo),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Po},initGroupAttributes:{groupID:N,groupAttributes:Uo},setGroupAttributes:{groupID:N,groupAttributes:Uo},deleteGroupAttributes:{groupID:N,keyList:Object.assign(Object.assign({},Po),{allowEmpty:!0})},getGroupAttributes:{groupID:N,keyList:Object.assign(Object.assign({},Po),{allowEmpty:!0})},getGroupCounters:{groupID:N,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:N,counters:Uo},increaseGroupCounter:{groupID:N,key:N,value:wo},decreaseGroupCounter:{groupID:N,key:N,value:wo}},Fo={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},xo=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=R,this.groupAction=to,this.groupAttribute=yo,this.groupMember=mo}install(e,t=[]){this._core=e,Ii.init(e),R.init(e),to.init(e,this),mo.init(e,this),ro.init(e),So.init(e),yo.init(e),Go.init(e),e.helper.registerValidateConfig({auth:Fo,params:ko}),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;null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name)})}_reset(){R.reset(),yo.reset(),So.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}},Vo={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},Bo={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21};class jo{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.getPollingInterval())}isRunning(){return this._isRunning}_request(){return I(this,void 0,void 0,function*(){try{var e=yield function(r,i){return I(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.getPollingInterval());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"),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class Ko{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 Ho=e=>e===Vo.GROUP_TIPS_HAS_NO_ROAMING||e===Vo.GROUP_TIPS_HAS_ROAMING,Wo=e=>e===Vo.GROUP_SYSTEM_MESSAGE;function $o(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=S(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}=e,e=S(e,["GN","GT","F_Hd","F_NN"]),t=Object.assign({GroupName:t,GroupType:s},e);return n&&(t.From_AccountHeadurl=n),r&&(t.From_AccountNick=r),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=S(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=S(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=l.map(e=>{var{Img:t,NN:s}=e,e=S(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((Ho(u)||Wo(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===Vo.BROADCAST_MESSAGE||u===Vo.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 Ho(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)),Wo(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 Yo=new class{constructor(){this._name="MessageParser",this._sequenceList=new Ko(200),this._messageIDList=new Ko(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=$o(e)),Wo(e.Event)&&Object.values(Bo).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),r=a.parseServerGroupMessage(e),i=this._createMessage(r),Ho(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(r)?this._avChatRoomHandler.handleGroupAttributesUpdated(r):null===this._filterDuplicateMessage(i)||o.isMessageSentByCurrentInstance(i)||(1===r.isModified&&(i.isModified=!0),Ho(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(i)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];Ho(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),Wo(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(Vo).includes(t)?t===Vo.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===Vo.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===Vo.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===Vo.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=$o(e));var a=n.parseServerGroupMessage(e);Object.values(Vo).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 zo=e=>{var{store:t}=qo["core"];return(t.get("cloudConfig")||{})[e]},Jo=e=>{var{utils:{isUndefined:t}}=qo["core"];return!t(e)},Xo=()=>{var e=zo("polling_interval");return Jo(e)?parseInt(e,10):300},Qo=()=>{var e=zo("polling_simplified_msg");return Jo(e)?parseInt(e,10):0};var Zo,ea=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,Yo.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(Bo).includes(n.ReportType);i===t&&n&&this.reset(r)}}getPollingInterval(){return this._pollingInterval}isPollingSimplifiedMessage(){return 0!==Qo()}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 e=0<this._joinedGroupMap.size?[...this._joinedGroupMap.values()].filter(e=>e.type===TYPES.GRP_LIVE):e}handleJoinGroupResult(l){return I(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&&Yo.onMessageReceived(a,o,!0),e(r)?{status:n.JOIN_STATUS_SUCCESS,group:i}:this.startMessageLongPolling(l)})}_preCheck(r){return I(this,void 0,void 0,function*(){var{common:e,OuterConstant:t,helper:s,apiMap:{quitGroup:n}}=this._core;if(e.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(e=zo("polling_count_limit"),Jo(e)&&0<e?parseInt(e,10):20))throw new s.ChatError({code:2688,message:"the count of longPolling exceeds the max limit"})}else 0!==this._joinedAVChatRoomCount()&&r.type!==t.GRP_LIVE&&([e,s]=this._joinedGroupMap.entries().next().value,s.selfInfo.role===t.GRP_MBR_ROLE_OWNER?this._parentPlugin.groupDataHandler.deleteLocalGroup(e):yield n(e),this.reset(e))})}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._pollingInterval=Xo(),this._startPolling(r),{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 jo({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:Qo()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Qo()}}_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(e,t){var{Key:t,NextSeq:s,NextBroadcastSeq:n,RspMsgList:r=[],RspBroadcastMsgList:i=[]}=t;t&&s&&this._pollingRequestInfoMap.set(e,{longPollingKey:t,startSequence:s}),n&&n>this._startBroadcastSequence&&(this._startBroadcastSequence=n),0<r.length?(0!==this._pollingNoMessageCount&&(this._pollingNoMessageCount=0,this._pollingInterval=Xo()),Yo.onMessageReceived(e,r)):(this._pollingNoMessageCount+=1,this._pollingNoMessageCount===(t=zo("polling_no_msg_count"),Jo(t)?parseInt(t,10):20)&&(this._pollingInterval=Xo()+(s=zo("polling_interval_plus"),Jo(s)?parseInt(s,10):2e3))),0<i.length&&Yo.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()]}_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);else{console.log(this._name+"._stopPolling all");for(let 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,Yo.reset()}},ta=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(n){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(n),{group:{type:s}}=t["data"];return s===e.GRP_AVCHATROOM?ea.handleJoinGroupResult(t.data):t})}},sa=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 I(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&&ea.reset(n),t})}},na=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 I(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&&ea.reset(n),t})}},ra=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 I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,n=r["groupID"],e=e.getGroup(n);return(null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits("AV_MBR_LIST")?this._getGroupMemberList(r):this._parentPlugin.groupMember.getGroupMemberList(r)})}_getGroupMemberList(i){return I(this,void 0,void 0,function*(){let r="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,n){return I(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}})}},ia=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 I(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 I(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=ea.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=ea.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 I(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return I(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 ea.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}})}},oa=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 I(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 I(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 I(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}})}},aa=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return I(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 I(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}}},la=new class{init(e,t){console.log("AVChatRoomAction.init"),ta.init(e,t),sa.init(e,t),na.init(e,t),ra.init(e,t),ia.init(e,t),oa.init(e,t),aa.init(e)}},ua=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({});ea.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=ea.getJoinedLiveList(),!t.isUnlimitedAVChatRoom()&&0<s.length&&this.stopMessageLongPolling({groupID:s[0]}),t={groupID:e,type:n.GRP_LIVE};return console.log(this._name+`.startMessageLongPolling groupID:${e} longPollingKey:${r} longPollingSequence:`+i),ea.startMessageLongPolling({group:t,longPollingKey:r,startSequence:i})}stopMessageLongPolling(e){e=e.groupID;return ea.reset(e),console.log(this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}},ca=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,qo.init(e),ea.init(e,t),la.init(e,t),ua.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){ea.onAVChatRoomSystemNotification(e)}_reset(){ea.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 da=new class{init(e){this.core=e}},ha="message",ga="user",_a={OR:"or",AND:"and"},pa={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},ma={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![_a.OR,_a.AND].includes(e)||"keywordListMatchType should be OR or AND"},va={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},fa={required:!1,rules:["string"],allowEmpty:!0},Sa={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=da.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"}},Ia={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=da.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"}},Ea={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=da.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Ca=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),Ma={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=da.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},ya={searchCloudMessages:{keywordList:pa,keywordListMatchType:ma,cursor:fa,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Ia,conversationID:Ea,timePosition:Ca("timePosition"),timePeriod:Ca("timePeriod")},searchCloudUsers:{keywordList:pa,keywordListMatchType:ma,cursor:fa,count:va,miniBirthday:Ca("miniBirthday"),maxBirthday:Ca("maxBirthday"),gender:Ma},searchCloudGroupMembers:{keywordList:pa,keywordListMatchType:ma,cursor:fa,count:va,groupTypeList:Sa,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:pa,keywordListMatchType:ma,cursor:fa,count:va,groupTypeList:Sa}},Oa={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0},Aa=new class{install(e){this._core=e,da.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:Oa,params:ya})}searchCloudMessages(v){return I(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=S(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 I(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 da.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:_=[]}=u;if(0!==c)throw{errorCode:c,errorInfo:d};var p=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} res: totalCount:`+h,m=(t.setLogInfo({message:p}).end(),_.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:ha,functionName:"searchCloudMessages"})}})}searchCloudUsers(f){return I(this,void 0,void 0,function*(){var s;try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:t,count:n=20}=f,r=S(f,["keywordListMatchType","count"]),i=Object.assign({count:n,keywordListMatchType:t===_a.AND?1:0},r),o=(this._setBirthdayRangeParams(i,f),yield function(a){return I(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 da.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&&(_=v.map(e=>({tag:e.Tag,value:e.StrValue})),p=null==(s=this._core.user.userProfile)?void 0:s.createProfile(m,_),g.push(p))}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:ga,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(h){return I(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:t=20,keywordListMatchType:s}=h,n=S(h,["count","keywordListMatchType"]),r=yield function(o){return I(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 da.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===_a.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:ga,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(d){return I(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:t=20,keywordListMatchType:s}=d,n=S(d,["count","keywordListMatchType"]),r=yield function(i){return I(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 da.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===_a.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:ga,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!==ha&&27003===e?o="SearchParamsError":s!==ha&&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 Ta(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Ra="qualityStat",Da="im-ssolog-quality-stat",ba=(Zo=Zo||{},Zo[Zo.ONLINE=8]="ONLINE","networkRTT"),Na="messageE2EDelay",La="sendMessageC2C",Ga="sendMessageGroup",wa="sendMessageGroupAV",Pa="sendMessageRichMedia",Ua="cosUpload",ka="messageReceivedGroup",Fa="messageReceivedGroupAVPush",xa="messageReceivedGroupAVPull",qa={networkRTT:2,messageE2EDelay:3,sendMessageC2C:4,sendMessageGroup:5,sendMessageGroupAV:6,sendMessageRichMedia:7,messageReceivedGroup:8,messageReceivedGroupAVPush:9,messageReceivedGroupAVPull:10,cosUpload:11},Va=[La,Ga,wa,Pa,Ua],Ba=[ka,Fa,xa],ja=[ba,Na,La,Ga,wa,Pa,Ua,ka,Fa,xa],Ka={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},Ha="quality_stat";var Wa=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(Ka))}init(e){this._core=e,Object.values(Va).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=Ta(s/t*100,2),i=Ta((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 Pa;if(s.conversationType===i)return La;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?wa:Ga}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Ua?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)}},$a=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(Ra+".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:Ta(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(Ba).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?xa:ka):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))}},Ya=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:Ta(this._totalDelay/e,1)}_calculatePercentage(e,t){return Ta(e/t*100,2)}},za=new class{init(e){this.core=e}},i=new class{constructor(){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;za.init(e),Wa.init(e),$a.init(e),Ya.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(Ra+".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:Ha,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...ja.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&&Wa.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:Zo.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case Na:return Ya.getStatResult();case La:case Ga:case wa:case Pa:case Ua:return Wa.getStatResult(e);case ka:case Fa:case xa:return $a.getStatResult(e);default:return null}}_uploadQualityReports(t){return I(this,void 0,void 0,function*(){try{var n={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=za.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=Ra+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(Da)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(Da,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(Ha)}_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(),Ya.dispose(),$a.dispose()}};let Ja,Xa;Ja=Qt.STANDARD,Xa=[e,function(e){ws.install(e),qs.install(e),Vs.install(e)},m,Ys,Xs,i,M,jr,Si,xo,ca,Aa,gn];var Qa,Za,el,L,F,tl,sl,nl,rl=Object.freeze({__proto__:null,ChatError:h,buildAndSendPacket:Ms,get builtInPlugins(){return Xa},checkBusinessCapabilityBits:vs,deepMerge:Rs,getCurrentUserID:_,getErrorMessage:is,getMessagePreviewText:Ds,isC2CConv:e=>Y(e)&&e.slice(0,3)===Ht.CONV_C2C,isCommunity:Ss,isGroupConv:e=>Y(e)&&e.slice(0,5)===Ht.CONV_GROUP,isTopic:Is,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=k.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:fs,registerInterceptor:_s,registerValidateConfig:ps,requireAuth:os,get sdkEdition(){return Ja},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 Ss({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:gs,validateParameters:ls,workflowManager:g}),il=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(o.CONVERSATION_UPDATED,{needSort:r})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),k.notificationCenter.emitInnerEvent(o.CONVERSATION_UPDATED))}},ol=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]})}},al=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let n,{operation:r,updateUnreadCount:i=!0}=e,o=S(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"];Is(s)?k.notificationCenter.emitInnerEvent(Bt[e],t):k.notificationCenter.emitInnerEvent(e,t)}},ll=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)}},ul=Object.freeze({__proto__:null,conversationStore:il,groupStore:ol,messageStore:al,userStore:ll});let cl={on:k.notificationCenter.subscribeOuterEvent.bind(k.notificationCenter),off:k.notificationCenter.unSubscribeOuterEvent.bind(k.notificationCenter),destroy:function(){return I(this,void 0,void 0,function*(){var e,t;try{null!=(e=k.store.get("login"))&&e.isLogin&&(yield cl.logout()),k.notificationCenter.emitInnerEvent(o.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{k.notificationCenter.emitOuterEvent(u.SDK_DESTROY,{SDKAppID:null==(t=k.store.get("instance"))?void 0:t.sdkAppId}),fs.clear(),ms.clear(),g.destroy(),k.destroy()}})},callExperimentalAPI:function(e,t){return dl[e]?dl[e](t):Promise.reject(new Error(`API ${e} is not found`))},use:ms.installExternalPlugin.bind(ms),registerPlugin:function(e){console.log("registerPlugin",e)},setLogLevel:function(e){console.log("setLogLevel",e),!k||"function"!=typeof k.setLogLevel||null!=k&&k.setLogLevel(e)}},dl={},hl={};function G(e){let{apiName:n,context:t,methodName:r=n,matcher:s}=e;hl[n]||(hl[n]=[]),hl[n].push({context:t,methodName:r,matcher:s}),cl[n]&&1!==hl[n].length||(cl[n]=(...t)=>{gs(r,t);var s=hl[n];for(let e of s)if(!e.matcher||e.matcher(t))return e.context[e.methodName].bind(e.context)(...t)})}function gl(e,t,s){s=s||e;dl[e]=t[s].bind(t)}function _l(){return Object.assign(Object.assign({InnerEvent:o,InnerEventSubType:k.notificationCenter.InnerEventSubType,OuterEvent:u,OuterConstant:C,SignalingEvent:kt,helper:Object.assign(Object.assign(Object.assign({},k.utils),k.common),{registerApi:G,registerExperimentalAPI:gl,registerInterceptor:_s,registerValidateConfig:ps,checkBusinessCapabilityBits:vs,registerWorkflowStep:g.registerWorkflowStep.bind(g),ChatError:h}),apiMap:cl},k),{constants:Object.assign(Object.assign({},rs),k.constants),common:Object.assign(Object.assign({},rl),k.common),utils:k.utils,appStore:ul})}dl.statTUIKeyFeatures=function(e){console.log("statTUIKeyFeatures",e)},(L=Qa=Qa||{})[L.USER_INITIATED=0]="USER_INITIATED",L[L.KICKED_OUT=1]="KICKED_OUT",(t=Za=Za||{})[t.multipleAccount=1]="multipleAccount",t[t.multipleDevice=2]="multipleDevice",t[t.restApi=3]="restApi",(e=el=el||{})[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi";let pl={[Za.multipleAccount]:"multipleAccount",[Za.multipleDevice]:"multipleDevice",[Za.restApi]:"REST_API_Kick",[el.multipleAccount]:"multipleAccount",[el.multipleDevice]:"multipleDevice",[el.restApi]:"REST_API_Kick",[el.usersigExpired]:"userSigExpired"},ml="login_online_presence_task",{ERROR:vl,DESTROY:fl,FORCE_OFFLINE:Sl}=o,{KICKED_OUT_MULT_ACCOUNT:Il,KICKED_OUT_MULT_DEVICE:El,KICKED_OUT_REST_API:Cl,ACCOUNT_A2KEY_EXPIRED:Ml,MSG_A2KEY_EXPIRED:yl}=Xt;class Ol{init(){var e=k["notificationCenter"];e.subscribeInnerEvent(Sl,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(vl,yl,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(vl,Ml,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(vl,Il,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(vl,El,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(vl,Cl,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fl,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 I(this,void 0,void 0,function*(){var e=t["kickedOutReasonCode"];try{yield k.login.loginAction.logout(Qa.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(t),k.notificationCenter.emitOuterEvent(u.KICKED_OUT,{data:{type:pl[e]},name:u.KICKED_OUT}),[Za.restApi,Ml,yl].includes(e)&&k.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,s=k.ssoLog.createSSOLogData({method:"kickedOut"}),e=`type:${pl[e]} newInstanceInfo: `+JSON.stringify(t);s.setLogInfo({message:e}).end(!0),console.warn("loginModule."+e)}_isKickedOut(e){return[Za.multipleAccount,Za.multipleDevice,Za.restApi].includes(e)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(Sl,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(vl,Ml,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(vl,yl,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(vl,Il,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(vl,El,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(vl,Cl,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fl,this._dispose,this)}}function Al(){return I(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}})}class Tl{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){var{notificationCenter:e,store:t}=k;t.set("login",{isReady:!1}),G({apiName:"login",context:this}),G({apiName:"logout",context:this}),G({apiName:"getLoginUser",context:this}),G({apiName:"isReady",context:this}),e.subscribeInnerEvent(o.RECONNECTED,this._reLogin,this),k.notificationCenter.subscribeInnerEvent(o.DESTROY,this._dispose,this)}login(s){return I(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 h({functionName:"login",code:Xt.REPEAT_LOGIN});let e=yield this._performLogin(s);return this._validateAfterLogin(e),this._handleLoginSuccess(e),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:0,data:e}}catch(e){let t=e["errorCode"],s=new h({functionName:"login",code:t});throw n.setError(s).end(!0),s}finally{this._latestLoginAt=0}})}_getUiPlatform(){var{store:e,utils:{IN_BROWSER:t,isH5:s}}=k,e=(null==(e=e.get("instance"))?void 0:e.scene)||"";let n=e;return t&&(n=e+"_web",s)&&(n=e+"_h5"),ts[n]}_reLogin(){return I(this,void 0,void 0,function*(){var e,t,s,n,r,i;try{this._isLoginIn()&&(t=k.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Al())&&({instanceID:n,customStatus:r}=s,k.store.set("login",{statusInstanceId:n}),g.executeWorkflow(a.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:jt.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 I(this,arguments,void 0,function*(s=Qa.USER_INITIATED){let e=k.ssoLog.createSSOLogData({method:"logout"});e.setLogInfo({moreMessage:"identifier:"+_()});try{yield this._performLogout(s),e.end(!0),k.ssoLog.uploadSSOLogData()}catch(s){let e=s["errorCode"],t=new h({functionName:"logout",code:e});this._handleLogoutError(t)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?_():""}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(u.SDK_READY,{name:u.SDK_READY})},1)}_updateAndEmitSDKNotReady(){k.store.set("login",{isReady:!1}),k.notificationCenter.emitOuterEvent(u.SDK_NOT_READY,{name:u.SDK_NOT_READY})}_validateAfterLogin(e){var t,s="login";if(!e)throw new h({functionName:s,message:"login response is empty"});var{tinyID:e,a2Key:n}=e||{},r=k.ssoLog.getSSOLogData(s);if(!e){let e=new h({functionName:s,code:Xt.NO_TINYID});throw null!=(t=null==r?void 0:r.setError)&&t.call(r,e).end(),e}if(!n){let e=new h({functionName:s,code:Xt.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:is({code:"RepeatLogin",replacement1:null==(e=k.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return I(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(),Al()})}_ensureAsyncComplete(){return I(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.executeWorkflow(a.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),k.common.taskScheduler.addTask({id:ml,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(s){return I(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.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}
5
- timeStamp:${n} offset:${o} customStatus:${r} href: ${l} appId: `+a;console.log("login ok. "+i),t.updateLogCreatedAtByTimeOffset(),t.setLogInfo({moreMessage:i}).end()}_sendOnlinePresenceRequest(){return I(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(ml),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(o.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(o.DESTROY,this._dispose,this)}}let Rl={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Dl={logout:!0};class bl{constructor(){this.loginAction=new Tl,this.kickedOutHandler=new Ol,this.loginAction.init(),this.kickedOutHandler.init(),ps({auth:Dl,params:Rl})}}(m=F=F||{}).CONV_C2C="C2C",m.CONV_GROUP="GROUP",m.CONV_TOPIC="TOPIC",m.CONV_SYSTEM="@TIM#SYSTEM",(Ys=tl=tl||{}).MSG_PRIORITY_HIGH="High",Ys.MSG_PRIORITY_NORMAL="Normal",Ys.MSG_PRIORITY_LOW="Low",Ys.MSG_PRIORITY_LOWEST="Lowest",(i=sl=sl||{}).MSG_TEXT="TIMTextElem",i.MSG_CUSTOM="TIMCustomElem",i.MSG_LOCATION="TIMLocationElem",i.MSG_FACE="TIMFaceElem",i.MSG_IMAGE="TIMImageElem",i.MSG_AUDIO="TIMSoundElem",i.MSG_FILE="TIMFileElem",i.MSG_VIDEO="TIMVideoFileElem",i.MSG_GRP_TIP="TIMGroupTipElem",i.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",i.MSG_MERGER="TIMRelayElem";let Nl={1:tl.MSG_PRIORITY_HIGH,2:tl.MSG_PRIORITY_NORMAL,3:tl.MSG_PRIORITY_LOW,4:tl.MSG_PRIORITY_LOWEST},Ll=((M=nl=nl||{}).IN="in",M.OUT="out",{});function Gl(e){var t,s,n;return e?(void 0===Ll[e]?(t=("3"+(n=new Date).getHours()).slice(-2),s=("0"+n.getMinutes()).slice(-2),n=("0"+n.getSeconds()).slice(-2),Ll[e]=parseInt([t,s,n,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Ll[e])):Ll[e]+=1,Ll[e]):0}class wl{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=tl.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:_,cloudCustomData:p="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:S,checkResult:I=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:O=Ut.SUCCESS,revokeReason:A="",conversationSubType:T,clientSequence:R,protocol:D="JSON",revokerInfo:b={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:L,groupProfile:G,atUserList:w,flow:P,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=n||_,this.needReadReceipt=!0===i||1===i,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=l,this.nick=c,this.avatar=d,this.protocol=D,this.random=void 0===L?(t=t||99999999,Math.round(Math.random()*t)):L,this.time=h||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==g||!g.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==g||!g.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=p,this.messageLifeTime=m,this.from=u||null,this.sequence=S||0,this.conversationType=f||F.CONV_C2C,this.hasRiskContent=1<I,this.version=v,this.isPlaceMessage=E,this.isRevoked=2===E||8===C,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=A,this.revokerInfo=b,this._receiverList=M,this.conversationSubType=T,this.revoker=(null==b?void 0:b.revoker)||"",this.clientSequence=R||S||0,this.status=O,this.atUserList=w||[],this.flow=P,this.isRead=U,this.reInitialize(r),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(G)}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=Gl(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 Pl{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new Pl({data:e,description:s,extension:t})}constructor(e){this.type=sl.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 Ul{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new Ul({text:e})}constructor(e){this.type=xt.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}}}}class kl{constructor(){this._elementClassMap={[sl.MSG_CUSTOM]:Pl,[sl.MSG_TEXT]:Ul}}init(){G({apiName:"createCustomMessage",context:this}),G({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=nl.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=nl.OUT),Object.assign(Object.assign({},e),{currentUser:n}));return new wl(t)}createCustomMessage(t){let e=_(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),n=this._elementClassMap[sl.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 Ul({text:t}),s=_(),(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=ll.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=Ut.UNSENT,e.flow=nl.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===nl.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===nl.OUT}}let Fl={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}},xl={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},ql={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Vl(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 Bl(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=Vl(e,ql),e=S(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=Vl(e,xl),e=S(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)}:Fl}function jl(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:_,MsgCheckResult:p,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:S}=e,I,{From_Account:E,To_Account:C}=e;if(1===i){let e=C;C=E,E=e}if(S){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=S;I={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:_,checkResult:p,cloudCustomData:m,revokerInfo:I,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:r,elements:Wl(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:Wl(t),messageVersion:a,cloudCustomData:l}}function Hl(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:_,NeedReadReceipt:p,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,S,I=tl.MSG_PRIORITY_NORMAL;if(Object.keys(Nl).includes(String(e.MsgPriority))&&(I=Nl[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;S={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:I,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:_,needReadReceipt:p,isPlaceMessage:m,revokerInfo:S,atUserList:E,elements:Wl(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 Wl(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 $l(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:Wl(t),messageVersion:l,cloudCustomData:u}}function Yl({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:n,conversationSubType:r,flow:i,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&i===nl.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})}var zl=Object.freeze({__proto__:null,autoIncrementIndex:Gl,parseServerGroupMessage:Hl,parseServerPushC2CModifyMessage:Kl,parseServerPushGroupModifyMessage:$l,parseServerPushMessage:jl,parseServerPushMessageElement:Wl,updateConversationFields:Yl});let Jl=k.utils["isPlainObject"];function Xl(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&&Jl(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 Ql(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 Zl(t,s){return I(this,void 0,void 0,function*(){var e=yield Ms((t.conversationType===F.CONV_GROUP?function(e,t){var s,{onlineUserOnly:n,cloudCustomData:r,messageControlInfo:i,offlinePushInfo:o}=Xl(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:Bl(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:Ql(t)}}}:function(e,t){var s,{onlineUserOnly:n,cloudCustomData:r,messageControlInfo:i,offlinePushInfo:o}=Xl(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:Bl(o),forbidCallbackControl:Ql(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let eu=k.utils["isPlainObject"],{MSG_AUDIO:tu,MSG_FILE:su,MSG_IMAGE:nu,MSG_VIDEO:ru,MSG_MERGER:iu}=C;class ou{init(){G({apiName:"sendMessage",context:this,matcher:e=>![tu,su,nu,ru,iu].includes(e[0].type)})}sendMessage(c,t){return I(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}=ns;if(!(c instanceof wl)){let e=new h({code:Xt.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 h({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 Zl(c,t)):c.conversationType===F.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),r=yield Zl(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=Ut.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=Ut.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 h({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=Is(s)?o.TOPIC_NEW_MESSAGE:o.NEW_MESSAGE;k.notificationCenter.emitInnerEvent(r,{result:{conversationUpdateFieldList:[{conversationID:s,type:n,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&eu(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 I(this,void 0,void 0,function*(){var{to:t,from:s}=r;let n=t,e=ol.getGroup(n);if(Ss({groupID:n})&&null!=e&&e.isSupportTopic)throw new h({code:Xt.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Is(t)&&([n]=t.split(zt.TOPIC),e=ol.getGroup(n)),!e&&"function"==typeof(null==cl?void 0:cl.getGroupProfile)){let e=yield cl.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=is({code:Xt.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:n});throw new h({code:Xt.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){k.notificationCenter.emitInnerEvent(o.QUALITY_STAT,{label:ss.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class au{constructor(e){this.value=e,this.next=null}}class lu{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new au(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}}class uu{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new lu(100),k.notificationCenter.subscribeInnerEvent(o.LOGOUT,this._reset,this),k.notificationCenter.subscribeInnerEvent(o.DESTROY,this._dispose,this)}get _messagesByConversation(){return al.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)?al.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:r,hasRiskContent:i,operation:qt.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 al.updateMessage(t,[e],{isRevoked:!0,revoker:r,operation:qt.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(o.LOGOUT,this._reset,this),k.notificationCenter.unSubscribeInnerEvent(o.DESTROY,this._dispose,this)}}function cu(e,t){var s,n,r,i,o,a,l,u=il.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=Ds(u.type,u.payload),u.cloudCustomData=l,u.version=o,il.updateConversation(e,{lastMessage:u}))}class du{init(){G({apiName:"modifyMessage",context:this})}modifyMessage(c){return I(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 I(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 Ms({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:Wl(e),messageVersion:t,cloudCustomData:s}}})}(c):o===F.CONV_GROUP&&(t=yield function(o){return I(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 Ms({servcmd:"openim.modify_group_msg",data:r});if(i){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=i;return{elements:Wl(e),messageVersion:t,cloudCustomData:s}}})}(c)),t){n.end();let e=""+o+r;return r===_()&&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 h({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(u.MESSAGE_MODIFIED,{name:u.MESSAGE_MODIFIED,data:[n]}),k.notificationCenter.emitInnerEvent(o.MESSAGE_MODIFIED,{conversationID:t,message:n}),cu(t,e)}_canModifyMessageElement(e){return[sl.MSG_TEXT,sl.MSG_CUSTOM,sl.MSG_LOCATION,sl.MSG_FACE].includes(e)}}class hu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];g.registerWorkflowStep(a.RECEIVE_C2C_NEW_MESSAGE,d.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),g.registerWorkflowStep(a.RECEIVE_C2C_NEW_MESSAGE,d.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),g.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_RE_ONLINE,d.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(o.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(o.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(o.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){g.executeWorkflow(a.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)):s.isInMessageList(e)||(s.storeConversationMessage(e)&&Yl({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[d.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[d.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=jl(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:nl.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={}}=il.getConversation(e)||{};n.avatar===s&&n.nick===t||il.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),cu(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(o.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),k.notificationCenter.unSubscribeInnerEvent(o.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),k.notificationCenter.unSubscribeInnerEvent(o.DESTROY,this._dispose,this)}}class gu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];g.registerWorkflowStep(a.RECEIVE_GROUP_NEW_MESSAGE,d.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),g.registerWorkflowStep(a.RECEIVE_GROUP_NEW_MESSAGE,d.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(o.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(o.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(o.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&g.executeWorkflow(a.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)):s.isInMessageList(e)||s.storeConversationMessage(e)&&(n.push(e),Yl({conversationUpdateFields:r,message:e})))}),{conversationUpdateFieldList:[...r.values()],messages:n}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[d.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=Hl(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:nl.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(e){var t=(k.message||{})["messageDataHandler"],{from:e,nick:s,avatar:n,conversationID:r=""}=e;if(e===(null==(e=k.store.get("login"))?void 0:e.userId)){let e=t.getLatestMsgSentByMe(r);!e||s===e.nick&&n===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:r,latestNick:s,latestAvatar:n,isSentByMe:!0})}}_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]}),cu(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=F.CONV_GROUP,{topicID:s,groupID:n}=e=$l(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(o.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(o.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(o.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===Yt.GRP_AVCHATROOM;return!(!ol.getGroup(e)&&t)}}class _u{constructor(){this.c2cMessageReceiver=new hu,this.groupMessageReceiver=new gu}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}let pu={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."}}}},mu={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class vu{constructor(){this.messageHelper=zl,this.messageFactory=new kl,this.messageSender=new ou,this.messageAction=new du,this.messageReceiver=new _u,this.messageDataHandler=new uu,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),ps({auth:mu,params:pu})}}let fu="Tag_Profile_IM_",Su={NICK:fu+"Nick",GENDER:fu+"Gender",BIRTHDAY:fu+"BirthDay",LOCATION:fu+"Location",SELFSIGNATURE:fu+"SelfSignature",ALLOWTYPE:fu+"AllowType",LANGUAGE:fu+"Language",AVATAR:fu+"Image",MESSAGESETTINGS:fu+"MsgSettings",ADMINFORBIDTYPE:fu+"AdminForbidType",LEVEL:fu+"Level",ROLE:fu+"Role"},Iu={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:[]},Eu=new Map([[Su.NICK,"nick"],[Su.GENDER,"gender"],[Su.BIRTHDAY,"birthday"],[Su.LOCATION,"location"],[Su.SELFSIGNATURE,"selfSignature"],[Su.ALLOWTYPE,"allowType"],[Su.LANGUAGE,"language"],[Su.AVATAR,"avatar"],[Su.MESSAGESETTINGS,"messageSettings"],[Su.ADMINFORBIDTYPE,"adminForbidType"],[Su.LEVEL,"level"],[Su.ROLE,"role"]]);var Cu=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf("Tag_Profile_Custom")?s.profileCustomField.push({key:e,value:t}):Eu.has(e)&&(s[Eu.get(e)]=t)}),Object.assign(Object.assign({},Iu),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=>{s.push({tag:Su[e.toUpperCase()],value:t[e]})}),s}normalizeProfileFields(e){let n={};return e.forEach(e=>{var{tag:t,value:s}=e;if(Eu.has(t)){let e=Eu.get(t);n[e]=s}}),n}};let Mu=k.common["generateProtocolData"];function yu(n){return I(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:_(),UserItem:[]};n.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var i=Mu({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=Cu.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 Ou(e){return ll.getFriendMap().has(e)}let Au=k.utils["isEmpty"];class Tu{init(){G({apiName:"getMyProfile",context:this}),G({apiName:"getUserProfile",context:this}),G({apiName:"updateMyProfile",context:this}),this.createProfile=Cu.createProfile.bind(Cu);var e=k["notificationCenter"];g.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_LOGIN,d.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(o.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(o.LOGOUT,this._reset,this),e.subscribeInnerEvent(o.DESTROY,this._dispose,this)}getMyProfile(){return I(this,void 0,void 0,function*(){let t=k.ssoLog.createSSOLogData({method:"getMyProfile"});try{var s=_(),n=yield yu([s]);if(n){let e=this._handleProfileFormResponse(n)[0];return ll.getUserProfileMap().set(s,e),{code:0,data:e}}t.end()}catch(e){var{errorCode:n,errorInfo:s}=e,n=new h({functionName:"getMyProfile",code:n,message:s});throw t.setError(n).end(),e}})}getUserProfile(l){return I(this,void 0,void 0,function*(){var r=k.ssoLog.createSSOLogData({method:"getUserProfile"});try{let e=l["userIDList"],{userIdListToRequest:t,userIdListToCache:s}=(100<e.length&&(e=e.slice(0,100)),this._filterRequestAndCacheUsers(e)),n=[];s.forEach(e=>{e=ll.getUserProfile(e);n.push(e)});var i="userIDList.length:"+e.length;if(0===t.length)return r.setLogInfo({message:i}).end(),{code:0,data:n};var o=yield yu(t);if(o){let e=this._handleProfileFormResponse(o);e.forEach(e=>{Ou(e.userID)&&ll.getUserProfileMap().set(e.userID,e)});var a=e.concat(n);return r.setLogInfo({message:i}).end(),{code:0,data:a}}}catch(e){o=e["errorCode"],i=new h({functionName:"getUserProfile",code:o});throw r.setError(i).end(),i}})}getMyProfileCacheThenServer(){return I(this,void 0,void 0,function*(){var e=_(),e=ll.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return I(this,void 0,void 0,function*(){let r=k.ssoLog.createSSOLogData({method:"updateMyProfile"}),t=_(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);let n=Cu.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:n};r.setLogInfo({message:JSON.stringify(n)}),yield function(n){return I(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Mu({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=ll.getUserProfile(t),o=i?Object.assign(Object.assign({},i),s):Cu.createProfile(t,n);return function t(s,n,r){let i=r||[];var e,o;return!(!s||!n)&&(e=Object.keys(s).filter(e=>!i.includes(e)),o=Object.keys(n).filter(e=>!i.includes(e)),e.length===o.length)&&e.every(e=>!!n.hasOwnProperty(e)&&("object"==typeof s[e]&&null!==s[e]?t(s[e],n[e],r):s[e]===n[e]))}(i,o,["lastUpdatedTime","profileCustomField"])||k.notificationCenter.emitOuterEvent(u.PROFILE_UPDATED,{name:u.PROFILE_UPDATED,data:[o]}),o.lastUpdatedTime=Date.now(),ll.getUserProfileMap().set(t,o),r.end(),{code:0,data:o}}catch(e){let{errorCode:t,errorInfo:s}=e,n=new h({functionName:"updateMyProfile",code:t,message:s});throw r.setError(n).end(),n}})}updateMyNickAndAvatar(r){return I(this,void 0,void 0,function*(){var e=_(),t=Date.now(),s=ll.getUserProfile(e),n={};(n=s?Object.assign(s,r):Cu.createProfile(e,r)).lastUpdatedTime=t,ll.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:Cu.parseProfileList(s)}}();Au(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&(k.notificationCenter.emitInnerEvent(o.PROFILE_UPDATE,{name:o.PROFILE_UPDATE,data:[e]}),k.notificationCenter.emitOuterEvent(u.PROFILE_UPDATED,{name:u.PROFILE_UPDATED,data:[e]})))}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(o.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(o.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(o.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,n=ll.getUserProfile(t);if(!n||!Ou(t))return{isProfileUpdated:!1,profile:null};let r=Cu.normalizeProfileFields(s),i=Object.keys(r).some(e=>n[e]!==r[e]);return i?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},n),r),{lastUpdatedTime:e}),ll.getUserProfileMap().set(t,e),il.updateConversation("C2C"+t,{userProfile:e}),{isProfileUpdated:i,profile:e}):{isProfileUpdated:!1,profile:n}}_filterRequestAndCacheUsers(e){let s=[],n=[];return e.forEach(e=>{var t=ll.getUserProfileMap().has(e);(Ou(e)&&t?n:s).push(e)}),{userIdListToRequest:s,userIdListToCache:n}}_handleProfileFormResponse(e){e=e.userProfile;if(!Array.isArray(e))return[];let t=e.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Au(e.profileItem)),s=Date.now();return t.map(e=>{e=Cu.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_reset(){ll.getUserProfileMap().clear()}}var Ru=new Map,Du=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Du.length;e<t;e++)Ru.set(e,Du[e]);function bu(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 Nu=k.utils["isEmpty"],Lu=k.common["generateProtocolData"];function Gu(r){return I(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",n=Lu({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:bu(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:n}=e;return{userID:Nu(t)?e:t,code:s,message:n}})}})}class wu{constructor(){this._customStatus=""}init(){var e=k["notificationCenter"];G({apiName:"getUserStatus",context:this}),G({apiName:"setSelfStatus",context:this}),G({apiName:"subscribeUserStatus",context:this}),G({apiName:"unsubscribeUserStatus",context:this}),g.registerWorkflowStep(a.SYNC_SERVER_INFO_AFTER_RE_ONLINE,d.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(o.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(o.LOGOUT,this._reset,this),e.subscribeInnerEvent(o.DESTROY,this._dispose,this)}setSelfStatus(s){return I(this,void 0,void 0,function*(){let r=k.ssoLog.createSSOLogData({method:"setSelfStatus"}),e=_(),t=s["customStatus"];try{return yield function(r){return I(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=Lu({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 h({functionName:"setSelfStatus",code:t,message:s});throw r.setError(n).end(),n}})}getUserStatus(s){return I(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=bu(e);this._customStatus=e}subscribeUserStatus(n){return I(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 I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_subscribe",s=Lu({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 I(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 I(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=Lu({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:bu(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=bu(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:_(),statusType:1,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){k.notificationCenter.emitOuterEvent(u.USER_STATUS_UPDATED,{name:u.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 h({functionName:e,code:Xt.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:_(),statusType:1,customStatus:this._customStatus});return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(r){return I(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 Gu(this._sliceUserIDList(r,s)))||{};return t.end(),{code:0,data:{successUserList:n,failureUserList:e}}}catch(e){s=e["errorCode"],n=new h({functionName:"getUserStatus",code:s});throw t.setError(n).end(),n}})}_isOnlyMeInArray(e){var t=_();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(o.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(o.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(o.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let Pu={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}}},Uu={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class ku{constructor(){this.userProfile=new Tu,this.userStatus=new wu,this.userProfile.init(),this.userStatus.init(),ps({auth:Uu,params:Pu})}}return console.log("TencentCloudLiteChat.VERSION:1.3.0"),{create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:n=!1,scene:r=""}=e;if("number"!=typeof e&&(i=Number(e),Number.isNaN(i)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(e=Number(e),fs.has(e))return fs.get(e);var i=""+(o()+o())+o()+o()+o()+o()+o()+o();function o(){return(65536*(1+Math.random())|0).toString(16).substring(1)}k.init({sdkAppId:e,instanceId:i,testEnv:t,devMode:s,unlimitedAVChatRoom:n,scene:r,sdkEdition:Ja}),g.init(),k.message=new vu,k.user=new ku,k.login=new bl,ms.installBuiltInPlugin(Xa);t=cl;return fs.set(e,t),t},TSignaling:kt,EVENT:u,VERSION:rt,TYPES:C}});
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 P{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,r){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!r||e.context===r;return!(t&&e)}))}emit(e,...s){e=this.listeners[e];e&&e.forEach(e=>{var{fn:e,context:t}=e;e.apply(t,s)})}once(t,s,r){let n=(...e)=>{s.apply(r,e),this.off(t,n)};this.on(t,n)}}let w={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 r,x,V,e=Object.freeze({__proto__:null,get ConvModifyPushType(){return q},ENUM_PLATFORM:w,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(r.TOPIC_TIPS_NOTIFICATION):s.push(r.GROUP_TIPS_NOTIFICATION)}),s}(t=r=r||{}).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:r.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:r.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:r.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:r.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:r.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:r.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:r.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:r.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:r.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:r.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(r.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(r.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(r.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(r.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(r.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(r.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(r.TOPIC_MESSAGE_READ_SYNC):s.push(r.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_SYSTEM_NOTIFICATION):s.push(r.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(r.TOPIC_AT_TIPS):s.push(r.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(r.CONVERSATION_MARK_UPDATED);break;case q.CONV_GROUP_ADDED:s.push(r.CONVERSATION_GROUP_ADD);break;case q.CONV_GROUP_DELETED:s.push(r.CONVERSATION_GROUP_DELETED);break;case q.CONV_GROUP_UPDATED:s.push(r.CONVERSATION_GROUP_UPDATED);break;default:s.push(r.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:r.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:r.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:r.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:r.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:r.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:r.ALL_MESSAGE_READ}];function K(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],n=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=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=>{n.push({type:x.SERVER_PUSH_MESSAGE+":"+e,data:t})}):n.push({type:x.SERVER_PUSH_MESSAGE+":"+s,data:t})}),n}(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 P,this._innerEventEmitter=new P,this.InnerEventSubType=r}subscribeInnerEvent(s,r,n,i){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=n;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,i)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,n)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(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,r,n,i){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=n;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,i)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,n)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function S(e,t){var s={};for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(s[n[r]]=e[n[r]]);return s}function I(e,o,a,l){return new(a=a||Promise)(function(s,t){function r(e){try{i(l.next(e))}catch(e){t(e)}}function n(e){try{i(l.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}i((l=l.apply(e,o||[])).next())})}let $=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,r,n,i)=>{if(!X(s)||!X(r))return 0;let o=0;var a,l=Object.keys(r);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!($(r[a])||n&&n.includes(a)))if(X(s[a])&&X(r[a]))o+=se(s[a],r[a],n,i);else{if(i&&i.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o};function re(s){let r,n,i=s,o="";for(let e=0,t=(i=s.length%8!=0?"0".repeat(8-s.length%8)+s:i)["length"];e<t;e+=8)r=parseInt(i.slice(e,e+4),2),n=parseInt(i.slice(e+4,e+8),2),o+=base16Map.get(r)+base16Map.get(n);return o}let ne="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)||ne,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),Se="undefined"!=typeof uni?!_e:"undefined"!=typeof window&&!_e&&!ve,Ie=ae?qq:le?tt:ue?swan:ce?my:ie?wx:he?uni:de?jd:{},s=Se&&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"),w[e]}(),Me=/iPad/i.test(s),ye=/iPhone/i.test(s)&&!Me,Oe=/iPod/i.test(s),Te=ye||Me||Oe,Ae=(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,be=/Firefox/i.test(s),Le=/Edge/i.test(s),Ne=!Le&&/Chrome/i.test(s),Ge=/MSIE/.test(s)||-1<s.indexOf("Trident")&&-1<s.indexOf("rv:11.0"),Pe=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}(),we=/Safari/i.test(s)&&!Ne&&!Re&&!Le,Ue=/Windows/i.test(s),ke=/MAC OS X/i.test(s),Fe=Se&&"undefined"!=typeof Worker&&!Ge,qe=Re||Te,xe=Se&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,Ve="undefined"!=typeof window&&void 0!==window.navigator&&(V=window.navigator["standalone"],!(!Te||V||we));function Be(){let e="unknown";if(ke&&(e="mac"),Ue&&(e="windows"),Te&&(e="ios"),Re&&(e="android"),_e)try{var t=wx.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 I(this,arguments,void 0,function*({method:n,url:i,data:o,timeout:a=3e3}){return new Promise(_e?(t,e)=>{Ie.request({url:i,data:o,method:n,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,r=setTimeout(()=>{s.abort(),e(new Error('{"message":"Request timeout","code":2801}'))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(r),200===s.status||304===s.status)try{t(s.responseText?JSON.parse(s.responseText):null)}catch(e){t(s.responseText)}else e(new Error('{"message":"Network error","code":2800}'))},s.open(n,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(r){if(null===r||"object"!=typeof r)return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp)return new RegExp(r.source,r.flags);if(r instanceof Map){let s=new Map;return r.forEach((e,t)=>{s.set(We(t),We(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(We(e))}),t}if(Array.isArray(r))return r.map(e=>We(e));let e=Object.getPrototypeOf(r),s=Object.create(e);return[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)].forEach(e=>{var t=Object.getOwnPropertyDescriptor(r,e);t&&(t.get||t.set?Object.defineProperty(s,e,t):s[e]=We(r[e]))}),s}function $e(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var t=Object.freeze({__proto__:null,ANDROID_VERSION:De,IE_VERSION:Pe,IN_ALIPAY_MINI_APP:ce,IN_BAIDU_MINI_APP:ue,IN_BROWSER:Se,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:ne,IN_WX_MINI_GAME:oe,IN_WX_MINI_PLUGIN:fe,IOS_VERSION:Ae,IS_ANDROID:Re,IS_CHROME:Ne,IS_EDGE:Le,IS_FIREFOX:be,IS_IE:Ge,IS_IOS:Te,IS_IPAD:Me,IS_IPHONE:ye,IS_IPOD:Oe,IS_MAC:ke,IS_SAFARI:we,IS_WECHAT:Ee,IS_WIN:Ue,IS_WORKER_AVAILABLE:Fe,MINI_APP_NAMESPACE:Ie,USER_AGENT:s,base16EncodeBinaryString:re,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:r,onSendFail:n}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,this._onSendFail=n)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class ze{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)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:n}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=n}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}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:r,onClose:n,onError:i,onSendFail:o}=e;if(this._worker){let s={OPEN:t,MESSAGE:r,CLOSE:n,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 n,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:Ie.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)}):Ie.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=n=n||{})[Qe.CONNECTED=0]="CONNECTED",Qe[Qe.CONNECTING=1]="CONNECTING",Qe[Qe.DISCONNECTED=2]="DISCONNECTED";class Xe{constructor(e){this._url="",this._readyState=n.DISCONNECTED,this._url=e,this._id=te(),this._emitter=new P,ie?this._socket=new ze:this._canUseWebWorker()?this._socket=new Je:this._socket=new Ye,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[n.CONNECTED,n.CONNECTING].includes(this._readyState)||(this._readyState=n.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==n.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[n.CONNECTED,n.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===n.CONNECTED}disconnect(){this._readyState=n.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===n.CONNECTING&&(this._readyState=n.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=n.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=n.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=n.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",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"}}},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,r]of et[e])if(t>=s&&t<r)return e;return"CHINA"}var rt,nt="1.4.0";(i=rt=rt||{}).INITIAL="INITIAL",i.DEFAULT="DEFAULT",i.BACKUP="BACKUP",i.ANYCAST="ANYCAST",i.IPV6="IPV6";let it=rt.INITIAL;function ot(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:n}=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=Ae||-1:"android"===e&&(t=De||-1),t}(),r=(s={sdkappid:r,instanceid:n,random:i,platform:Ce,host:o,version:a,sdkversion:nt},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}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:r=!1,intervalMs:n=16}=e,i=Math.max(n,16);return{id:e,nextExecuteTime:Date.now()+i,intervalMs:n,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((e,t)=>e.nextExecuteTime-t.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function ut(t){var s=[];for(let e=0;e<t.length;e+=1){var r,n=t.charCodeAt(e);55296<=n&&n<=56319?(r=t.charCodeAt(++e)-56320+(n-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):n<=127?s.push(n):n<=2047?s.push(192|n>>6,128|63&n):s.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(s)}function 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 r=4294967295;var n=s["length"];for(let e=0;e<n;e++){r^=s[e];for(let e=0;e<8;e++)1&~r?r>>>=1:r=r>>>1^3988292384}return(4294967295^r)>>>0}function ht(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=c.get("login")||{},n=c.get("instance")||{},{servcmd:r,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:n.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:re(""),cappid:t.cappid||0,tjgID:"",seq:_t(),cs:0}),n=ct(s);return r.cs=dt(e,n),{head:r,body:n}}function gt(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=c.get("login")||{},n=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ce,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:re(""),cappid:t.cappid||0,seq:_t(),cs:0}),n=ct(s);return r.cs=dt(e,n),{head:r,body:n}}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.4.0",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,r=(r=e,t=c.get("login")||{},n=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ce,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:re(""),cappid:t.cappid||0,seq:_t(),cs:0}),n=ct(s);return r.cs=dt(e,n),{head:r,body:n}},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 St{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:r}=e||{};this.eventType=t,this.method=e,this.uiPlatform=s,this.message=r||""}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=G=G||{}).RECONNECTED="reconnected",m.CLOUD_CONFIG_UPDATE="cloud_config_update",m.SOCKET_DISCONNECTED="socket_disconnected";var It=G;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(It.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:r=Ct,evt_rpt_tinyid_wl:n=Mt}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=n}createSSOLogData(e){var t=new St(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 I(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 Se&&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(It.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",Tt="channel_schedule_task",At="channel_reconnect_task",Rt="connected",Dt="disconnected",bt="network_status_change",Lt="send_fail";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 Gt(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(r,n,i){function o(t,e){if(!n[t]){if(!r[t]){if(!e&&Gt)return Gt(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=n[t]={exports:{}};r[t][0].call(e.exports,function(e){return o(r[t][1][e]||e)},e,e.exports,s,r,n,i)}return n[t].exports}for(var a=Gt,e=0;e<i.length;e++)o(i[e]);return o}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,n=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var n=r.shift();if(n){if("object"!=Nt(n))throw new TypeError(n+"must be non-object");for(var i in n)t=n,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=n[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,n){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),n);else for(var i=0;i<r;i++)e[n+i]=t[s+i]},flattenChunks:function(e){for(var t,s,r,n,i=t=0,o=e.length;i<o;i++)t+=e[i].length;for(n=new Uint8Array(t),i=s=0,o=e.length;i<o;i++)r=e[i],n.set(r,s),s+=r.length;return n}}),i={arraySet:function(e,t,s,r,n){for(var i=0;i<r;i++)e[n+i]=t[s+i]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,n)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(r)},{}],2:[function(e,t,s){var l=e("./common"),n=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var u=new l.Buf8(256),r=0;r<256;r++)u[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&n))return String.fromCharCode.apply(null,l.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}u[254]=u[254]=1,s.string2buf=function(e){for(var t,s,r,n,i=e.length,o=0,a=0;a<i;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<i&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new l.Buf8(o),a=n=0;n<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<i&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[n++]=s:(s<2048?t[n++]=192|s>>>6:(s<65536?t[n++]=224|s>>>12:(t[n++]=240|s>>>18,t[n++]=128|s>>>12&63),t[n++]=128|s>>>6&63),t[n++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new l.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,n,i=t||e.length,o=new Array(2*i),a=s=0;a<i;)if((r=e[a++])<128)o[s++]=r;else if(4<(n=u[r]))o[s++]=65533,a+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&a<i;)r=r<<6|63&e[a++],n--;1<n?o[s++]=65533:r<65536?o[s++]=r:(r-=65536,o[s++]=55296|r>>10&1023,o[s++]=56320|1023&r)}return c(o,s)},s.utf8border=function(e,t){for(var s=(t=(t=t||e.length)>e.length?e.length:t)-1;0<=s&&128==(192&e[s]);)s--;return!(s<0||0===s)&&s+u[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var n=65535&e,i=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;i=i+(n=n+t[r++]|0)|0,--o;);n%=65521,i%=65521}return n|i<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var n=a,i=r+s;e^=-1;for(var o=r;o<i;o++)e=e>>>8^n[255&(e^t[o])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,r,n,i,o,a,l=e.state,u=e.next_in,c=e.input,d=u+(e.avail_in-5),h=e.next_out,g=e.output,p=h-(t-e.avail_out),_=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,S=l.wnext,I=l.window,E=l.hold,C=l.bits,M=l.lencode,y=l.distcode,O=(1<<l.lenbits)-1,T=(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>>>=r=s>>>24,C-=r,0==(r=s>>>16&255))g[h++]=65535&s;else{if(!(16&r)){if(!(64&r)){s=M[(65535&s)+(E&(1<<r)-1)];continue}if(32&r){l.mode=12;break e}e.msg="invalid literal/length code",l.mode=30;break e}for(n=65535&s,(r&=15)&&(C<r&&(E+=c[u++]<<C,C+=8),n+=E&(1<<r)-1,E>>>=r,C-=r),C<15&&(E+=c[u++]<<C,C+=8,E+=c[u++]<<C,C+=8),s=y[E&T];;){if(E>>>=r=s>>>24,C-=r,!(16&(r=s>>>16&255))){if(!(64&r)){s=y[(65535&s)+(E&(1<<r)-1)];continue}e.msg="invalid distance code",l.mode=30;break e}if(i=65535&s,C<(r&=15)&&(E+=c[u++]<<C,(C+=8)<r)&&(E+=c[u++]<<C,C+=8),m<(i+=E&(1<<r)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(E>>>=r,C-=r,(r=h-p)<i){if(f<(r=i-r)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=I,(o=0)===S){if(o+=v-r,r<n){for(n-=r;g[h++]=I[o++],--r;);o=h-i,a=g}}else if(S<r){if(o+=v+S-r,(r-=S)<n){for(n-=r;g[h++]=I[o++],--r;);if(o=0,S<n){for(n-=r=S;g[h++]=I[o++],--r;);o=h-i,a=g}}}else if(o+=S-r,r<n){for(n-=r;g[h++]=I[o++],--r;);o=h-i,a=g}for(;2<n;)g[h++]=a[o++],g[h++]=a[o++],g[h++]=a[o++],n-=3;n&&(g[h++]=a[o++],1<n)&&(g[h++]=a[o++])}else{for(o=h-i;g[h++]=g[o++],g[h++]=g[o++],g[h++]=g[o++],2<(n-=3););n&&(g[h++]=g[o++],1<n)&&(g[h++]=g[o++])}break}}break}}while(u<d&&h<_);u-=n=C>>3,E&=(1<<(C-=n<<3))-1,e.next_in=u,e.next_out=h,e.avail_in=u<d?d-u+5:5-(u-d),e.avail_out=h<_?_-h+257:257-(h-_),l.hold=E,l.bits=C}},{}],8:[function(e,t,s){var L=e("../utils/common"),N=e("./adler32"),G=e("./crc32"),P=e("./inffast"),w=e("./inftrees"),U=0,k=-2,F=1,r=852,n=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 L.Buf16(320),this.work=new L.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 L.Buf32(r),t.distcode=t.distdyn=new L.Buf32(n),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):k}function l(e,t){var s,r;return!e||!e.state||(r=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t))?k:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=s,r.wbits=t,a(e))}function u(e,t){var s;return e?(s=new i,(e.state=s).window=null,(s=l(e,t))!==U&&(e.state=null),s):k}var x,V,B=!0;function j(e,t,s,r){var n,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new L.Buf8(e.wsize)),r>=e.wsize?(L.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(n=e.wsize-e.wnext)&&(n=r),L.arraySet(e.window,t,s-r,n,e.wnext),(r-=n)?(L.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=n,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=n))),0}s.inflateReset=a,s.inflateReset2=l,s.inflateResetKeep=o,s.inflateInit=function(e){return u(e,15)},s.inflateInit2=u,s.inflate=function(e,t){var s,r,n,i,o,a,l,u,c,d,h,g,p,_,m,v,f,S,I,E,C,M,y,O,T=0,A=new L.Buf8(4),R=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return k;12===(s=e.state).mode&&(s.mode=13),o=e.next_out,n=e.output,l=e.avail_out,i=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,d=a,h=l,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(2&s.wrap&&35615===u)A[s.check=0]=255&u,A[1]=u>>>8&255,s.check=G(s.check,A,2,0),c=u=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&u)<<8)+(u>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&u))e.msg="unknown compression method",s.mode=30;else{if(c-=4,C=8+(15&(u>>>=4)),0===s.wbits)s.wbits=C;else if(C>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<C,e.adler=s.check=1,s.mode=512&u?10:12,c=u=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(s.flags=u,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=u>>8&1),512&s.flags&&(A[0]=255&u,A[1]=u>>>8&255,s.check=G(s.check,A,2,0)),c=u=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.head&&(s.head.time=u),512&s.flags&&(A[0]=255&u,A[1]=u>>>8&255,A[2]=u>>>16&255,A[3]=u>>>24&255,s.check=G(s.check,A,4,0)),c=u=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.head&&(s.head.xflags=255&u,s.head.os=u>>8),512&s.flags&&(A[0]=255&u,A[1]=u>>>8&255,s.check=G(s.check,A,2,0)),c=u=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.length=u,s.head&&(s.head.extra_len=u),512&s.flags&&(A[0]=255&u,A[1]=u>>>8&255,s.check=G(s.check,A,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)),L.arraySet(s.head.extra,r,i,g,C)),512&s.flags&&(s.check=G(s.check,r,g,i)),a-=g,i+=g,s.length-=g),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(g=0;C=r[i+g++],s.head&&C&&s.length<65536&&(s.head.name+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=G(s.check,r,g,i)),a-=g,i+=g,C)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===a)break e;for(g=0;C=r[i+g++],s.head&&C&&s.length<65536&&(s.head.comment+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=G(s.check,r,g,i)),a-=g,i+=g,C)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(u!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=u=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}e.adler=s.check=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+=r[i++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:D=b=void 0;var D,b=s;if(B){for(x=new L.Buf32(512),V=new L.Buf32(32),D=0;D<144;)b.lens[D++]=8;for(;D<256;)b.lens[D++]=9;for(;D<280;)b.lens[D++]=7;for(;D<288;)b.lens[D++]=8;for(w(1,b.lens,0,288,x,0,b.work,{bits:9}),D=0;D<32;)b.lens[D++]=5;w(2,b.lens,0,32,V,0,b.work,{bits:5}),B=!1}if(b.lencode=x,b.lenbits=9,b.distcode=V,b.distbits=5,s.mode=20,6!==t)break;u>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}u>>>=2,c-=2}break;case 14:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[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;L.arraySet(n,r,i,g,o),a-=g,i+=g,l-=g,o+=g,s.length-=g}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(s.nlen=257+(31&u),u>>>=5,c-=5,s.ndist=1+(31&u),u>>>=5,c-=5,s.ncode=4+(15&u),u>>>=4,c-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;c<3;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}s.lens[R[s.have++]]=7&u,u>>>=3,c-=3}for(;s.have<19;)s.lens[R[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,y={bits:s.lenbits},M=w(0,s.lens,0,19,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;v=(T=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&T,!((m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(f<16)u>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(O=m+2;c<O;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(u>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}C=s.lens[s.have-1],g=3+(3&u),u>>>=2,c-=2}else if(17===f){for(O=m+3;c<O;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}C=0,g=3+(7&(u>>>=m)),u>>>=3,c=c-m-3}else{for(O=m+7;c<O;){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}C=0,g=11+(127&(u>>>=m)),u>>>=7,c=c-m-7}if(s.have+g>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;g--;)s.lens[s.have++]=C}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,y={bits:s.lenbits},M=w(1,s.lens,0,s.nlen,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,y={bits:s.distbits},M=w(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,y),s.distbits=y.bits,M){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=a&&258<=l){e.next_out=o,e.avail_out=l,e.next_in=i,e.avail_in=a,s.hold=u,s.bits=c,P(e,h),o=e.next_out,n=e.output,l=e.avail_out,i=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(T=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&T,!((m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(v&&!(240&v)){for(S=m,I=v,E=f;v=(T=s.lencode[E+((u&(1<<S+I)-1)>>S)])>>>16&255,f=65535&T,!(S+(m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}u>>>=S,c-=S,s.back+=S}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+=r[i++]<<c,c+=8}s.length+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(T=s.distcode[u&(1<<s.distbits)-1])>>>16&255,f=65535&T,!((m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}if(!(240&v)){for(S=m,I=v,E=f;v=(T=s.distcode[E+((u&(1<<S+I)-1)>>S)])>>>16&255,f=65535&T,!(S+(m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[i++]<<c,c+=8}u>>>=S,c-=S,s.back+=S}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+=r[i++]<<c,c+=8}s.offset+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===l)break e;if(s.offset>(g=h-l)){if((g=s.offset-g)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}p=g>s.wnext?(g-=s.wnext,s.wsize-g):s.wnext-g,g>s.length&&(g=s.length),_=s.window}else _=n,p=o-s.offset,g=s.length;for(l-=g=l<g?l:g,s.length-=g;n[o++]=_[p++],--g;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;n[o++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[i++]<<c,c+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?G:N)(s.check,n,h,o-h)),h=l,(s.flags?u:q(u))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=u=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,u+=r[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?G:N)(s.check,n,h,e.next_out-h)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),M=(0==d&&0===h||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&N(1,t,r,0)!==s.check?-3:j(e,t,r,r)?(s.mode=31,-4):(s.havedict=1,U)},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var P=e("../utils/common"),w=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],U=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],k=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],F=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,r,n,i,o,a){for(var l,u,c,d,h,g,p,_,m,v=a.bits,f=0,S=0,I=0,E=0,C=0,M=0,y=0,O=0,T=0,A=0,R=null,D=0,b=new P.Buf16(16),L=new P.Buf16(16),N=null,G=0,f=0;f<=15;f++)b[f]=0;for(S=0;S<r;S++)b[t[s+S]]++;for(C=v,E=15;1<=E&&0===b[E];E--);if(E<C&&(C=E),0===E)n[i++]=20971520,n[i++]=20971520,a.bits=1;else{for(I=1;I<E&&0===b[I];I++);for(C<I&&(C=I),f=O=1;f<=15;f++)if((O=(O<<1)-b[f])<0)return-1;if(0<O&&(0===e||1!==E))return-1;for(L[1]=0,f=1;f<15;f++)L[f+1]=L[f]+b[f];for(S=0;S<r;S++)0!==t[s+S]&&(o[L[t[s+S]]++]=S);if(g=0===e?(R=N=o,19):1===e?(R=w,D-=257,N=U,G-=257,256):(R=k,N=F,-1),f=I,h=i,y=S=A=0,c=-1,d=(T=1<<(M=C))-1,1===e&&852<T||2===e&&592<T)return 1;for(;;){for(m=o[S]<g?(_=0,o[S]):o[S]>g?(_=N[G+o[S]],R[D+o[S]]):(_=96,0),l=1<<(p=f-y),I=u=1<<M;n[h+(A>>y)+(u-=l)]=p<<24|_<<16|m,0!==u;);for(l=1<<f-1;A&l;)l>>=1;if(0!==l?A=(A&l-1)+l:A=0,S++,0==--b[f]){if(f===E)break;f=t[s+o[S]]}if(C<f&&(A&d)!==c){for(h+=I,O=1<<(M=f-(y=0===y?C:y));M+y<E&&!((O-=b[M+y])<=0);)M++,O<<=1;if(T+=1<<M,1===e&&852<T||2===e&&592<T)return 1;n[c=A&d]=C<<24|M<<16|h-i}}0!==A&&(n[h+A]=f-y<<24|64<<16),a.bits=C}return 0}},{"../utils/common":1}],10:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,s){var d=e("./zlib/inflate"),h=e("./utils/common"),g=e("./utils/strings"),p=e("./zlib/constants"),r=e("./zlib/messages"),n=e("./zlib/zstream"),i=e("./zlib/gzheader"),_=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options,e=(t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits)&&(t.windowBits=-15),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new n,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==p.Z_OK)throw new Error(r[e]);if(this.header=new i,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=g.string2buf(t.dictionary):"[object ArrayBuffer]"===_.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==p.Z_OK)throw new Error(r[e])}function a(e,t){t=new o(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}o.prototype.push=function(e,t){var s,r,n,i,o,a=this.strm,l=this.options.chunkSize,u=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?p.Z_FINISH:p.Z_NO_FLUSH,"string"==typeof e?a.input=g.binstring2buf(e):"[object ArrayBuffer]"===_.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new h.Buf8(l),a.next_out=0,a.avail_out=l),(s=(s=d.inflate(a,p.Z_NO_FLUSH))===p.Z_NEED_DICT&&u?d.inflateSetDictionary(this.strm,u):s)===p.Z_BUF_ERROR&&!0===c&&(s=p.Z_OK,c=!1),s!==p.Z_STREAM_END&&s!==p.Z_OK)return this.onEnd(s),!(this.ended=!0)}while(!a.next_out||0!==a.avail_out&&s!==p.Z_STREAM_END&&(0!==a.avail_in||r!==p.Z_FINISH&&r!==p.Z_SYNC_FLUSH)||("string"===this.options.to?(n=g.utf8border(a.output,a.next_out),i=a.next_out-n,o=g.buf2string(a.output,n),a.next_out=i,a.avail_out=l-i,i&&h.arraySet(a.output,a.output,n,i,0),this.onData(o)):this.onData(h.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(c=!0),(0<a.avail_in||0===a.avail_out)&&s!==p.Z_STREAM_END);return(r=s===p.Z_STREAM_END?p.Z_FINISH:r)===p.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===p.Z_OK):r!==p.Z_SYNC_FLUSH||(this.onEnd(p.Z_OK),!(a.avail_out=0))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===p.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=o,s.inflate=a,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,a(e,t)},s.ungzip=a},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js"),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=500,this._currentConnectState=Rt,this._beforeSendInterceptors=[]}init(){lt.addTask({id:Tt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),r=st(t);return ot(s?Ze.TEST[r].DEFAULT:Ze.PRODUCTION[r].INITIAL.replace("*",""+t),{isBinary:e})}(this._isBinarySupported),W.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),W.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:n=15e3,canResend:i=!0}=t||{};if(He(e))return console.warn(l+".sendPacket: packet is empty ",e),null;this._executeBeforeSendInterceptors(e);var o=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=$e();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:n,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(),e=l+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._ssoLog({method:"connect",message:e}),console.log(e)}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(Tt),lt.removeTask(At),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=500,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 I(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=function(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),t=st(t);if(s)return ot(Ze.TEST[t].DEFAULT,{isBinary:e});let r=Ze.PRODUCTION[t],n=Se&&r.ANYCAST;return ot({[rt.INITIAL]:()=>(it=rt.DEFAULT,r.DEFAULT),[rt.DEFAULT]:()=>(it=rt.IPV6,r.IPV6),[rt.IPV6]:()=>(it=rt.BACKUP,r.BACKUP),[rt.BACKUP]:()=>(it=n?rt.ANYCAST:rt.DEFAULT,n?r.ANYCAST:r.DEFAULT),[rt.ANYCAST]:()=>(it=rt.DEFAULT,r.ANYCAST="",r.DEFAULT)}[it](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Dt,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,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,reason:"socket_error"}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},t=l+` onSendFail sendFailSocketId: ${e} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:t}),console.warn(t),e===this._connectionId&&this._handleConnectStateChange({state:Dt,reason:Lt}),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 n=new Uint8Array(e);let i="",o=0;for(var a=n["length"];o<a;){let t=n[o],s=0,r=0;if(t<=127?(s=0,r=255&t):t<=223?(s=1,r=31&t):t<=239?(s=2,r=15&t):t<=244&&(s=3,r=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=n[o+e+1],r=r<<6|63&t;else r=65533,s=a-o;i+=String.fromCodePoint(r),o+=s+1}return i})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return this._ssoLog({method:"jsonParseError",message:e}),void console.error(s)}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:n,ErrorCode:r=r,ErrorInfo:n=n}=(null==e?void 0:e.body)||{},t=""+t+s,{resolve:s,reject:i}=this._pendingRequests.get(t);this._pendingRequests.delete(t),r&&0!==r?(W.emitInnerEvent("error",{errorCode:r,errorInfo:n}),i({errorCode:r,errorInfo:n})):s(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),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:r,resolve:n,reject:i,timeout:o}=e;if(r){this._pendingRequests.set(t,{resolve:n,reject:i,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:r});let e=this._isBinarySupported?ut(s).buffer:s;null!=(n=this._socketAdapter)&&n.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=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(It.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Rt})}_sendAck(e){e=ht({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return I(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 I(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,reason:Lt})}})}_sendHeartbeatIfReady(){return I(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,reason:bt}):this._handleConnectStateChange({state:Dt,reason:bt})}isPrivateNetWork(){var e=c.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:t,reason:s}=e;if(this._currentConnectState!==t){let e=l+`._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: `+s;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,W.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===Dt&&W.emitInnerEvent(It.SOCKET_DISCONNECTED),t!==Dt&&t!==Rt||(this._resetReconnectDelay(),lt.addTask({id:At,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,reason:"activity_status_change"})}_resetReconnectDelay(){lt.removeTask(At);var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive;this._intendedDelay=e?500:1e3}_scheduleReconnectWithBackoff(){var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(500,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(At,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){I(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){I(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:r}=t;Date.now()-s>=r&&(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};(m=L=L||{}).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";var u=L;(G=Ks=Ks||{}).LOGOUT="logout",G.DESTROY="destroy",G.CLOUD_CONFIG_UPDATE="cloud_config_update",G.PROFILE_UPDATE="profile_updated",G.ERROR="error",G.RECONNECTED="reconnected",G.FORCE_OFFLINE="im_open_status.stat_forceoffline",G.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",G.OVERLOAD_PUSH="OverLoadPush.notify2",G.NEW_MESSAGE="new_message",G.MESSAGE_PUSH="im_open_push.msg_push",G.MESSAGE_DELETED="message_deleted",G.MESSAGE_REVOKED="message_revoked",G.MESSAGE_MODIFIED="message_modified",G.SOCKET_DISCONNECTED="socket_disconnected",G.CONVERSATION_UPDATED="conversation_updated",G.TOPIC_MESSAGE_DELETED="topic_message_deleted",G.TOPIC_MESSAGE_REVOKED="topic_message_revoked",G.TOPIC_MESSAGE_MODIFIED="topic_message_modified",G.TOPIC_NEW_MESSAGE="topic_new_message",G.QUALITY_STAT="quality_stat",G.SYNC_CONVERSATION_LIST="sync_conversation_list";var Ut,kt,d=Ks,Ft=((t=N=N||{}).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",N);let 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"},Vt=((i=Ut=Ut||{}).UNSENT="unSend",i.SUCCESS="success",i.FAIL="fail",{modify:d.MESSAGE_MODIFIED,delete:d.MESSAGE_DELETED,revoke:d.MESSAGE_REVOKED}),Bt=((e=kt=kt||{})[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD",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:Ut,Direction:kt})),jt={[Vt.modify]:d.TOPIC_MESSAGE_MODIFIED,[Vt.delete]:d.TOPIC_MESSAGE_DELETED,[Vt.revoke]:d.TOPIC_MESSAGE_REVOKED},Kt={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"},Ht=Object.assign({},Kt),Wt={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},$t=Object.assign(Object.assign(Object.assign(Object.assign({},Wt),{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"}),Yt=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"}),zt={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},Jt={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Qt={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},Xt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zt),{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:Jt,GROUP_TIPS_OPERATION_TYPE:Qt}),C=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},qt),Bt),Ht),$t),Yt),Xt),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),Zt={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,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},es={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},o={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"},a={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"},ts={[o.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:a.USER_STATUS_UPDATE},{stepId:a.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:a.UNREAD_MESSAGE_SYNC},{stepId:a.CONVERSATION_RECOVER},{stepId:a.HISTORY_MESSAGE_RECOVER,dependency:a.CONVERSATION_RECOVER},{stepId:a.BLACKLIST_RECOVER},{stepId:a.FRIEND_RECOVER},{stepId:a.GROUP_REVOKED_NOTICE_RECOVER,dependency:a.HISTORY_MESSAGE_RECOVER},{stepId:a.GROUP_TIPS_RECOVER,dependency:a.HISTORY_MESSAGE_RECOVER},{stepId:a.TOPIC_REQUEST_INFO_RESET},{stepId:a.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:a.UNREAD_MESSAGE_SYNC},{stepId:a.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:a.UNREAD_MESSAGE_SYNC},{stepId:a.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[a.UNREAD_MESSAGE_SYNC,a.CONVERSATION_RECOVER]},{stepId:a.EMIT_C2C_MESSAGE_EVENT,dependency:[a.UNREAD_MESSAGE_SYNC,a.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[o.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:a.COMMERCIAL_CONFIG_UPDATE},{stepId:a.CLOUD_CONFIG_SYNC},{stepId:a.USER_PROFILE_SYNC},{stepId:a.UNREAD_MESSAGE_SYNC},{stepId:a.FRIEND_AND_BLACKLIST_SYNC},{stepId:a.GROUP_LIST_SYNC},{stepId:a.CONVERSATION_LIST_SYNC},{stepId:a.SIGNALING_MESSAGE_RECOVER,dependency:a.UNREAD_MESSAGE_SYNC},{stepId:a.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[a.UNREAD_MESSAGE_SYNC]},{stepId:a.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[a.UNREAD_MESSAGE_SYNC,a.CONVERSATION_LIST_SYNC]},{stepId:a.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[a.GROUP_LIST_SYNC,a.CONVERSATION_LIST_SYNC]},{stepId:a.CONVERSATION_GROUP_LIST_SYNC},{stepId:a.CONVERSATION_GROUP_UPDATE,dependency:[a.CONVERSATION_LIST_SYNC,a.CONVERSATION_GROUP_LIST_SYNC]},{stepId:a.QUALITY_REPORT}],[o.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:a.HANDLE_C2C_NEW_MESSAGE},{stepId:a.UNREAD_MESSAGE_SYNC},{stepId:a.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:a.HANDLE_C2C_NEW_MESSAGE},{stepId:a.EMIT_C2C_MESSAGE_EVENT,dependency:[a.HANDLE_C2C_NEW_MESSAGE,a.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:a.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[a.UNREAD_MESSAGE_SYNC]}],[o.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:a.HANDLE_GROUP_NEW_MESSAGE},{stepId:a.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:a.HANDLE_GROUP_NEW_MESSAGE},{stepId:a.UPDATE_GROUP_NEXT_SEQUENCE,dependency:a.HANDLE_GROUP_NEW_MESSAGE},{stepId:a.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:a.HANDLE_GROUP_NEW_MESSAGE},{stepId:a.EMIT_GROUP_MESSAGE_EVENT,dependency:[a.HANDLE_GROUP_NEW_MESSAGE,a.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},ss={REACT:"atomicx_react",VUE3:"atomicx_vue3"},rs={[ss.REACT+"_web"]:40,[ss.REACT+"_h5"]:41,[ss.VUE3+"_web"]:42,[ss.VUE3+"_h5"]:43},ns={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},is={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var os=Object.freeze({__proto__:null,ERROR_CODE:Zt,InnerEvent:d,OuterConstant:C,OuterEvent:u,QUALITY_METRICS:ns,SDK_EDITION:es,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:is,SignalingEvent:Ft,UIKIT_PREFIX:ss,UI_PLATFORM:rs,WORKFLOW_DEFINITIONS:ts,WORKFLOW_NAME:o,WORKFLOW_STEP:a});function as(t){var s;try{var r=c.getStorage("errorMessage");if(!t||!r)return"";var n=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:i=!1,code:o,replacement1:a="",replacement2:l=""}=t;if(!o)return"";var u=i?o+"_en":o+"_cn";let e=n[n[u]?u:o]||"";return e=e&&(a&&(e=e.replace("$replacement1",a)),l)?e.replace("$replacement2",l):e}catch(t){return console.warn("Error parsing stored error messages:",t),""}}class _ extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:n=""}=e;let i=r;s&&!r&&(i=as(e));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=n}}function ls(e,t){if(e&&!0!==(null==(e=k.store.get("login"))?void 0:e.isLoggedIn))throw new _({code:Zt.USER_NOT_LOGGED_IN,functionName:t})}let us=e=>"function"==typeof e;function cs(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)ds.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)ds.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function ds({required:e,rules:r,value:t,allowEmpty:n,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(!r.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<r.length;t++){let e=r[t];e=e.replace(e[0],e[0].toUpperCase()),s+=e+"/"}let e=`[${o}] must be type of ${s=s.substring(0,s.length-1)}, received type: ${Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}.`;throw new _({functionName:i,message:e})}if(!1===n){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 hs=[],gs={},ps={};function _s(e,t){var s;ls(gs[e],e),cs(ps[e],t,e),s=e,hs.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function ms(e,t){hs.push({interceptor:e,context:t})}function vs(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(ps,e),t&&"object"==typeof t&&Object.assign(gs,t)}var fs=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_installPlugin(e,t){var s=[];let r=(s=J(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),n=-1<r?s.splice(r,1):[];s.forEach(e=>{t.has(e)||(e&&us(e.install)?(t.add(e),us(e.getInstalledSubPlugins)?e.install(cl(),n):e.install(cl()),us(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):us(e)?(t.add(e),e(cl()),us(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isLoggedIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}};function Ss(e){return k.store.get("commercialConfig").get(e)}let Is=new Map;var h=new class{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 r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),console.log(`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),console.log(`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var n=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?n-t:0;this._stepStartTimes.delete(s+"-"+e),console.error(`[Workflow ${s}] Step ${e} failed at ${new Date(n).toISOString()} (${t}ms)`,r)}else{let e=this._workflowStartTimes.get(s),t=e?n-e:0;this._workflowStartTimes.delete(s),console.error(`[Workflow ${s}] failed at ${new Date(n).toISOString()} (${t}ms)`,r)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){this._handlers.has(e)?ts[e].find(e=>e.stepId===t)?this._handlers.get(e).set(t,r?s.bind(r):s):console.debug(`Step '${t}' not defined in workflow '${e}'`):console.debug(`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return I(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){console.log(`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=ts[o],i={cancelled:!1};this._activeWorkflows.set(o,{cancelToken:i});try{let t=new Map,n=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:o,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:i});yield new Promise((t,s)=>{let r=()=>{i.cancelled?t():this._getExecutableSteps({pendingSteps:n.pendingSteps,completedSteps:n.completedSteps,stepMap:n.stepMap,workflowName:o}).filter(e=>!n.runningSteps.has(e)).forEach(e=>{n.completedSteps.has(e)||n.runningSteps.has(e)||this._executeWorkflowStep(e,n,{onComplete:()=>{0===n.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:n.pendingSteps,completedSteps:n.completedSteps,stepMap:n.stepMap,workflowName:o}).filter(e=>!n.runningSteps.has(e)).length&&0===n.runningSteps.size&&(console.log(`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),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 I(this,void 0,void 0,function*(){let{workflowName:i,runningSteps:e,stepMap:s,stepResults:r,data:n}=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=r[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=r[e]})));var o=this._handlers.get(i).get(a);if(o){let e=yield Promise.resolve(o({data:n,result:t}));r[a]=e,this._logWorkflowExecution(i,a,"success")}l.completedSteps.add(a)}catch(e){let t=`[Workflow].${i}.`+a,{errorCode:s,errorInfo:r=t+" failed"}=e||{},n=new _({functionName:t,code:s,message:r});k.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${i}, stepId: `+a}).setError(n).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(ts).forEach(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(ts).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return ts[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:r,workflowName:n}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=r.get(e)||{};if(!t)return!0;if(Y(t))return this._isStepRegistered({workflowName:n,stepId:t})?s.has(t):!e;if(J(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:n,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,r){this._logHandlers[s](e,t)}};let Es=({type:e,groupID:t})=>e===C.GRP_COMMUNITY||(""+t).startsWith(Jt.COMMUNITY)&&!(""+t).includes(Jt.TOPIC),Cs=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(Jt.COMMUNITY)&&(""+e).includes(Jt.TOPIC)},Ms="openim",ys="million_group_open_http_svc";function Os(s){return I(this,void 0,void 0,function*(){var{servcmd:e,data:t}=Ts(e=s.data)||As(e)?function(e){let{servcmd:t,data:s}=e;var r,n,i;return As(s)?({servcmd:e,data:r}=e,{GroupId:n=""}=r,[n]=(i=n).split(Jt.TOPIC),{servcmd:Rs(e),data:Object.assign(Object.assign({},r),{GroupId:n,TopicId:i})}):{servcmd:t=Ts(s)?Rs(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 Ts(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return Es({type:e,groupID:t})}function As(e){var{GroupId:e=""}=e;return Cs(e)}function Rs(e){return e.includes(Ms)?e:(e=e.split(".")[1],ys+"."+e)}function g(){var e;return null==(e=k.store.get("login"))?void 0:e.userId}let Ds=e=>J(e)||Q(e),bs=(s,r,n,i)=>{if(!Ds(s)||!Ds(r))return 0;let o=0;var a,l=Object.keys(r);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!($(r[a])||n&&n.includes(a)))if(Ds(s[a])&&Ds(r[a]))o+=bs(s[a],r[a],n,i);else{if(i&&i.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o},Ls=(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""}},Ns=[{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}],Gs="im_sdk_config_mgr.fetch_config",Ps="im_sdk_config_mgr.push_configv2",ws="cloud-config";var Us=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n},channel:i}=this._core=e;e.subscribeInnerEvent(Ps,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Ns),i.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t,s={code:0,data:""};return e&&(s.data=(null==(t=this._core.store.get("cloudConfig"))?void 0:t[e])||""),s}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:n}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:n+=1}),t<n)throw new this._core.helper.ChatError({code:2996,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_fetchCloudConfig(){return I(this,void 0,void 0,function*(){try{var e=(this._core.store.get("instance")||{})["sdkAppId"],t=this._core.helper.generateProtocolData({servcmd:Gs,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=""+t.head.seq+Gs;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 I(this,void 0,void 0,function*(){try{var e;this._canFetch()&&(e=yield this._fetchCloudConfig(),this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:ws,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}})}_fetchCloudConfigIfReady(){return I(this,void 0,void 0,function*(){if(this._canFetch())try{var e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}})}_updateCloudConfig(e){e=this._parseCloudConfig(e);e&&(this._core.store.set("cloudConfig",e),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e))}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:n}=e;let i=null;if(0===t){if(this._version!==n)try{i=JSON.parse(s),this._version=n}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return i}_parseCmdFreqLimit(){var e,t=null==(e=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(ws),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Ns),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ps,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class p{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 ks={SEARCH_GRP_SNS:new p(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new p(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new p(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new p(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new p(0,Math.pow(2,6)).toString(),USER_STATUS:new p(0,Math.pow(2,7)).toString(),CONV_MARK:new p(0,Math.pow(2,9)).toString(),CONV_GROUP:new p(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new p(0,Math.pow(2,11)).toString(),MSG_EXT:new p(0,Math.pow(2,13)).toString(),GRP_COUNTER:new p(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new p(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new p(Math.pow(2,7)).toString(),PLUGIN_CS:new p(Math.pow(2,8)).toString(),PLUGIN_PUSH:new p(Math.pow(2,9)).toString(),PLUGIN_BOT:new p(Math.pow(2,10)).toString(),MSG_REACTION:new p(Math.pow(2,16)).toString(),FOLLOW:new p(Math.pow(2,20)).toString()},Fs="CommercialConfig",qs="commercial-config";var xs,Vs,Bs=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map}install(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n,InnerEvent:i}}=this._core=e;s.subscribeInnerEvent(i.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(i.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(i.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){return I(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let n,i=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(n=(t<32?new p(0,2**t):new p(2**(t-32),0)).toString(),!this._featureMap.get(n))){i=!1;break}return console.log(Fs+`.isFeatureEnabled decimalNumber:${e} key:${n} ret:`+i),{code:0,data:{enabled:i}}})}_fetchAndParseCommercialConfig(){return I(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 I(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 I(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,n;"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:n}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*n):void 0===t?(console.log(Fs+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(console.error(Fs+`._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._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new p(0,2**t):new p(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(ks,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(ks,r);e&&this._methodKeyMap.set(e,!1)}}else console.warn(Fs+".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()}},js=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)}},m=new class{constructor(){this._core=null}install(e){return I(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 I(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}})}_isExpired(e){return!e||(e=e["errorMessageSavedTime"],e&&6048e5<=(new Date).getTime()-e)}_parseResponse(e){if("string"==typeof e){var s=e.split(";\n"),r={},n=new RegExp(/'/g);for(let t=0;t<s.length;t++){var i=s[t].indexOf(":"),o=s[t].slice(0,i);let e=s[t].slice(i+1);o.startsWith("//")||""!==e&&(e=e.replace(n,""),r[o]=e)}return r}}};(L=xs=xs||{})[L.START_SYNC=0]="START_SYNC",L[L.SYNCING=1]="SYNCING",L[L.SYNC_COMPLETE=2]="SYNC_COMPLETE",(G=Vs=Vs||{})[G.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",G[G.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED";var Ks=new class{constructor(){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 I(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?Vs.NEW_MESSAGE_RECEIVED:Vs.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:n,groupTipList:i}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",l=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:n,overflowUnreadCountList:r,conversationUpdateFieldList:u}),Array.isArray(i)&&c.push(...i),o){let e=this._handleNewMessageList(t)["messages"];h.push(...e)}}return o?{conversationUpdateFieldList:u,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c,messages:h}:{conversationUpdateFieldList:u,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c}})}_syncUnreadDBMessageAfterLogin(){return I(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return I(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:r}=e,{OuterConstant:{CONV_C2C:n,CONV_SYSTEM:i}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==i){let e=r.find(({conversationID:e})=>e===""+n+t);e?e.unreadCount=s:r.push({conversationID:""+n+t,unreadCount:s,type:n})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===i||r.find(({conversationID:e})=>e===""+n+t)||r.push({conversationID:""+n+t,type:n,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return I(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let n=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:i,avatar:o,conversationID:a=""}=r;if(s!==t){let s=n.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;i&&o?i===e&&o===t||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=n.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!0})}}_handleNewMessageList(e){let t=(this._core.message||{})["messageDataHandler"],l=new Map,s=[];return e.forEach(a=>{this._updateMessageProfile(a);let e=1===a.isModified;if(t.isMessageSentByCurrentInstance(a)?a.isModified=e:e=!1,a.isOnlineMessage())a._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(a)||s.push(a);else if(!t.isInMessageList(a)){if(t.storeConversationMessage(a)){let{conversationID:e,conversationType:t,conversationSubType:s,flow:r,_isExcludedFromUnreadCount:n,_isExcludedFromLastMessage:i}=a,o=i?"":a;l.has(e)?(l.get(e).lastMessage=o,"in"!==r||n||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:n||"in"!==r?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:l}}_fetchUnreadDBMessage(l){return I(this,void 0,void 0,function*(){try{console.log("unread-message-synchronizer._fetchUnreadDBMessage options:",l);var e,t,s,r,n,i,o,a=yield function(n,l){return I(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=n,r="openim.getmsg",o=l.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+r;try{let e=yield l.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:n,revokedMessageList:i}=function(e,I){let r=[],n=[];return null!=e&&e.forEach(S=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:n,MsgClientTime:i,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,To_Account:d,TinyId:h,MsgCheckResult:g,CloudCustomData:p,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=S;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:i,messageFlagBits:m,random:o,sequence:a,time:l,messageControlInfo:u,isSupportExtension:c,to:d,tinyID:h,checkResult:g,cloudCustomData:p,messageVersion:v,eventArray:f,elements:I.message.messageHelper.parseServerPushMessageElement(n)}}();if(null!=(t=null==(e=null==(e=null==S?void 0:S.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))n.push(...function(){let e,t=[];return null!=(e=S.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=I.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:n}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:n,revokedMessageList:i,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}catch(e){console.warn(e)}})}(l,this._core);return a?({syncFlag:e,unreadMessageList:t,revokedMessageList:s,cookie:r,unreadCountList:n,overflowUnreadCountList:i,groupTipList:o}=a,this._parseAndSaveUnreadMessageList(t),{syncFlag:e,cookie:r,unreadMessageList:t,revokedMessageList:s,unreadCountList:n,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()}},Hs=new class{init(e){this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),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()}},Ws=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()}},$s=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Ws:Hs).init(e)}};var Ys=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(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()}},zs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(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,{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()}},Js=new class{init(e){var t=e.helper["IN_WX_MINI_APP"];(t?zs:Ys).init(e)}},t=new class{install(e){$s.init(e),Js.init(e)}};let Qs=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.*"]),Xs="tui_room_svr.*",Zs=new class{constructor(){this._transferredCommands=Qs}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 I(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=Xs}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(i,o){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=Xs,data:r}=i||{};let n={};try{n="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:n}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}})}_onCloudConfigUpdate(e={}){try{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=Qs}_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",er="signaling-timeout";function tr(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 sr(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function rr(e,t){return e.toString(16).padStart(t,"0")}function nr(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 ir,or,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 r=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${e} inviteeList:${r} groupID:`+t),t){if(s)return 0<r.length;let e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){let s=v+".updateSignaling",{inviteID:r,inviter:t,inviteeList:n,groupID:i}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+i),i&&this.hasSignaling(r)){let e=n[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},ar=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:n}=e,s=s||(t?r[0]:n);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:n}=e,s=(null==(s=null==(s=f.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,n)}}_createMessageControlInfo(e,t){t=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:r="",inviteeList:n=[]}=e,i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:1,inviter:i,inviteeList:r?n:[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:r}=f.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:3,groupID:r,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:r}=f.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:2,groupID:r,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:r}=f.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:4,groupID:r,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:r}=f.getSignaling(s),n=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:5,inviter:r,inviteeList:t?s:[n]});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[rr(nr(32),8),rr(nr(16),4),rr(16384|nr(12),4),rr(32768|nr(14),4),rr(nr(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},lr=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 I(this,void 0,void 0,function*(){var s;console.log(v+".invite params:"+JSON.stringify(t));try{this._validateBeforeInvite(t);var{signaling:r,signalingData:n,signalingExtensionOptions:e}=ar.createInviteSignaling(t),i=yield this._sendSignaling(r,e);if(0!==(null==i?void 0:i.code))return i;{let{inviteID:e,timeout:t}=n;return f.saveSignaling(e,Object.assign(Object.assign({},n),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:er+"-"+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 I(this,void 0,void 0,function*(){console.log(v+".accept params:"+JSON.stringify(i));try{var e=i["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,ar.createAcceptSignaling(i)),n=yield this._sendSignaling(t,r);return 0===(null==n?void 0:n.code)?(f.updateSignaling(s),Object.assign(Object.assign({},n),{inviteID:e})):n}catch(e){throw console.error(v+".accept error:"+e),e}finally{this._isProcessingSignaling=!1}})}cancel(n){return I(this,void 0,void 0,function*(){console.log(v+".cancel params:"+JSON.stringify(n));try{var e=n["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,ar.createCancelSignaling(n)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(f.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(v+".cancel error:"+e),e}finally{this._isProcessingSignaling=!1}})}reject(n){return I(this,void 0,void 0,function*(){console.log(v+".reject params:"+JSON.stringify(n));try{var e=n["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,ar.createRejectSignaling(n)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(f.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(v+".reject error:"+e),e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return I(this,void 0,void 0,function*(){console.log(v+".modifyInvitation params:"+JSON.stringify(e));var r,n,{inviteID:i,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(i);let e=f.getSignaling(i),t=e["signaling"],s=S(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var l=yield null==(n=null==(r=this._core)?void 0:r.message.messageAction)?void 0:n.modifyMessage(t);return 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!==tr([e]).length)return e={businessID:(e=sr(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 r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&f.setSignalingListenStatus(!0),null!=(r=this._core)&&r.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&f.setSignalingListenStatus(!1),null!=(r=this._core)&&r.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 I(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 I(this,void 0,void 0,function*(){var n;console.log(v+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:i,inviteID:o}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=ar.createTimeoutSignaling(s),t=yield this._sendSignaling(a,e);if(0===(null==t?void 0:t.code)){let{data:e,groupID:t,inviteeList:s,inviter:r}=l;null!=(n=this._core)&&n.notificationCenter.emitOuterEvent(null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),i?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 r=this._core.common.getCurrentUserID(),e=f.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t="cancel",s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=f.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s="reject";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=f.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){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}},ur=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=sr(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){f.getSignalingListenStatus()&&0!==(e=tr(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){f.getSignalingListenStatus()&&0<(e=tr(e.data)).length&&e.forEach(e=>{var t=sr(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){v;var{inviteID:r,inviteeList:n,groupID:i}=t,o=this._core.common.getCurrentUserID();if(console.log(`signaling._onNewInvitationReceived signalingData:${JSON.stringify(t)}}`),!i||n.includes(o)){let e=t["timeout"];var i=Date.now()/1e3-s.time,o=(0<e&&0<i&&e>i&&(e-=i),f.getSignaling(r));o!==t&&(o||f.saveSignaling(r,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(i=this._core)&&i.helper.taskScheduler.addOnceTask({id:er+"-"+r,intervalMs:1e3*e,callback:lr.handleInvitationExpiryTimer.bind(lr,r)})),this._emitEvent({name:null==(o=this._core)?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:n})}))}}_onInviteeRejected(e){v;var{inviteID:t,inviter:s,groupID:r,inviteeList:n}=e,i=f.hasSignaling(t);console.log(`signaling._onInviteeRejected inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+r),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:n[0]})}))}_onInviteeAccepted(e){v;var{inviteID:t,inviter:s,groupID:r,inviteeList:n}=e,i=f.hasSignaling(t);console.log(`signaling._onInviteeAccepted inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+r),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:n[0]})}))}_onInvitationCancelled(e){v;var{inviteID:t,inviter:s,groupID:r}=e,n=f.hasSignaling(t);console.log(`signaling._onInvitationCancelled inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(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,r=f.hasSignaling(t);console.log(`signaling._onInvitationTimeout inviteID:${t} hasInviteID:${r} data:`+e.data),r&&(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:r}=e,n=f.hasSignaling(s);console.log(`signaling._onInvitationModified inviteID:${s} data:`+r),n&&(f.saveSignaling(s,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:s,data:r}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},cr=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:n}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&f.getSignalingListenStatus()){e=tr([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();ur.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=sr(e);s&&(t=s["actionType"],1===t?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:n=0}=e,i=this._core.common.getCurrentUserID();r.includes(i)&&(r=Date.now()/1e3-t.time,0<n&&n<r&&0!==n||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let dr={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}}},hr={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0},gr=new class{install(e){lr.init(e),ur.init(e),ar.init(e),f.init(e),cr.init(e),e.helper.registerValidateConfig({auth:hr,params:dr})}},E=new class{init(e){this.core=e}},pr=((N=ir=ir||{}).MSG_TEXT="TIMTextElem",N.MSG_CUSTOM="TIMCustomElem",N.MSG_LOCATION="TIMLocationElem",N.MSG_FACE="TIMFaceElem",(i=or=or||{})[i.FORWARD=0]="FORWARD",i[i.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"}),_r="16k_zh-PY",mr={[pr.ZH_CN]:"16k_zh",[pr.EN_US]:"16k_en",[pr.YUE_HK]:"16k_yue",[pr.JA_JP]:"16k_ja",[pr.ZH_PY]:_r},vr=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,fr={READ:0,UNREAD:1},Sr="C2C",Ir="GROUP";function Er(i){return I(this,void 0,void 0,function*(){var e,s=E.core["appStore"],{messageList:t,conversationID:r}=i,s=s.conversationStore.getConversationMap();let n=null==(e=s.get(r))?void 0:e.peerReadTime;if(!n){let e=r.replace(Sr,""),t=yield function(t){return I(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"];n=null==e?void 0:e[0],s.has(r)&&(s.get(r).peerReadTime=n)}}t.forEach(e=>{e.time<=n&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)})})}function Cr(a){return I(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:n}}=E.core,i=r.conversationStore.getConversationMap();if(i.has(a)){let s=null==(e=i.get(a))?void 0:e.userProfile;if(s&&a.startsWith(n.CONV_C2C)){let{avatar:e,nick:t}=s;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 Mr(e){let t,s=E.core["message"],{conversationID:r,messageID:n}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===n))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===n)}function yr(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:n,nick:i,ID:o,clientSequence:a,clientTime:l,messageRandom:u,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:n,From_AccountNick:i,Id:o,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:l,MsgRandom:u,Random:u,MsgSeq:c,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function Or(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:n,MsgClientTime:i,ClientSeq:o,To_Account:a,MsgTimeStamp:l,TinyId:u,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:i,time:l,tinyID:u,random:c,sequence:d,to:a,groupID:n,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return E.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var Tr=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:n}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,n,this._handleReactionSync,this)}addMessageReaction(g,p){return I(this,void 0,void 0,function*(){let{OuterConstant:e,ssoLog:t,helper:r}=this._core;this._validateMessageReactionBusinessCapability();var n=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 I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:n,reactionID:i}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+n,Reaction:i,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return 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(r,n){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=n.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:l,reactionID:p,sequence:h},this._core)),n.setLogInfo({message:`conversationID:${s} messageID:${i} reactionID:`+p}).end(),{code:0}}catch(e){this._removeMyReactionRecord(i,p);let t=(e||{})["errorCode"],s=new r.ChatError({functionName:"addMessageReaction",code:t});n.setError(s).end(),console.error("addMessageReaction error: ",e)}})}removeMessageReaction(d,h){return I(this,void 0,void 0,function*(){let{OuterConstant:u,ssoLog:e,helper:r}=this._core;this._validateMessageReactionBusinessCapability();var c=e.createSSOLogData({method:"removeMessageReaction"});try{let{conversationID:e,ID:t,conversationType:s,from:r,to:n,clientSequence:i,random:o,time:a,sequence:l}=d;return this._removeMyReactionRecord(t,h),s===u.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:n,reactionID:i}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+n,Reaction:i,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:r,to:n,clientSequence:i,random:o,time:a,reactionID:h},this._core):s===u.CONV_GROUP&&(yield function(r,n){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=n.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},n)})}({to:n,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 r.ChatError({functionName:"removeMessageReaction",code:t});c.setError(s).end(),console.error("removeMessageReaction error: ",e)}})}getAllUserListOfMessageReaction(u){return I(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=u,s=100<u.count?100:u.count,n=e["conversationID"],{ssoLog:i,helper:o,constants:a}=this._core;try{var l;if(l=n.startsWith(a.OuterConstant.CONV_C2C)?yield function(l){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=l,{from:e,to:n,clientSequence:i,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:n,MsgKey:i+`_${o}_`+a};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(i){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=i,{sequence:e,to:n}=e,s={Reaction:s,NextSeq:t,GroupId:n,Count:r,MsgSeq:e};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s})){let{Reaction_Account:e,NextSeq:t}=l,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,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 I(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),g),r=t[0];let n=null,i=new Map,{from:o,to:a,conversationType:l}=r,u=this._generateMessageKeyList(t,i),{Results:c=[]}=(l===e.OuterConstant.CONV_C2C?n=yield function(n){return I(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=n,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return 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&&(n=yield function(r){return I(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,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})),n||{}),d=this._extractUserIDsFromReactionResults(c),h=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:i}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:h}),reactedByMyself:1===r}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){let t=[];return null!=e&&e.forEach(e=>{var{ReactionList:e=[]}=e;e.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(s){return I(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 I(this,void 0,void 0,function*(){let r=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;r.set(s,{nick:e,avatar:t,userID:s})}),r})}_recordMessageReactedByMe(e,t){e=e+"-"+t;this._reactionsMap.has(e)?this._reactionsMap.get(e).reactedByMe=!0:this._reactionsMap.set(e,{reactedByMe:!0})}_removeMyReactionRecord(e,t){e=e+"-"+t;this._reactionsMap.has(e)&&(this._reactionsMap.get(e).reactedByMe=!1)}_recordMessageReactionInfo(e){var{messageID:e,reactionID:t,reactionInfo:s}=e,e=e+"-"+t,t=this._reactionsMap.get(e)||{};this._reactionsMap.set(e,Object.assign(Object.assign({},t),s))}_validateMessageReactionBusinessCapability(){var{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits("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=>I(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:n,MsgRandom:i}=Object.assign(Object.assign({},e),t),o=r+`-${n}-`+i,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),u=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:l}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(o+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:o,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(h.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:h.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:o,reactionList:u}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:n,OperateType:i}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+o,o=r+"-"+n;if(1===i?this._recordMessageReactedByMe(r,n):this._removeMyReactionRecord(r,n),null!=(e=this._reactionsMap.get(o))&&e.reactionID){let e=this._reactionsMap.get(o);e.reactedByMyself=1===i,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,n){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return n.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return n.set(t,e),t})),r}},Ar=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:n}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),n.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),n.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new r.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(r){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:n,clientTime:i}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:n,MsgClientTime:i}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return I(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 r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(n){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=n[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(n);if(0<(null==s?void 0:s.length)){let e=yield function(s){return I(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:n,readReceiptList:t})}}return{code:0,data:{messageList:n}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(i){return I(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:o=fr.READ,cursor:s=""}=i,{conversationID:n,sequence:a,ID:l}=t,u=n.replace(e.OuterConstant.CONV_GROUP,""),c=100<=i.count?100:i.count;try{let i=yield function(i){return I(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:n}=i,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:n};return 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:r}=i,n={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return o===fr.READ?n.readUserIDList=r.map(e=>e.Read_Account):o===fr.UNREAD&&(n.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:n}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let n=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:i,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(i)){let r=""+t.OuterConstant.CONV_C2C+a;null!=i&&i.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=Mr({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,n.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(n)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:i}}=e,o=""+s.OuterConstant.CONV_GROUP+i;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:n}=e,e=e+`-${t}-`+s,t=Mr({conversationID:o,messageID:e}),s={groupID:i,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof n&&(t.readReceiptInfo.unreadCount=n,s.unreadCount=n),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Rr(o,a,l){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{from:t,to:s,clientSequence:r,random:n,time:i}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${n}_`+i,OperateType:l,ExtensionList:a}})})}function Dr(r,n,i){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:i,ExtensionList:n}})})}var br=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:n}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(d,r){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:n,conversationID:i,sequence:o,time:a,conversationType:s}=d,l=t.createSSOLogData({method:"setMessageExtensions"}),u=r;20<r.length&&(u=r.slice(0,20),console.warn("the length of extensions cannot exceed 20"));var c=this._generateServerExtensions(d,u);try{let r;if(s===e.CONV_C2C?r=yield Rr(d,c,1):s===e.CONV_GROUP&&(r=yield Dr(d,c,1)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return l.setLogInfo({message:`convID:${i} messageID:${n} 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 I(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:n}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),i=this._core.ssoLog.createSSOLogData({method:"getMessageExtensions"});i.setLogInfo({message:`convID:${e} messageID:${r} sequence:${t} time:`+n});try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),i.end(),{code:0,data:{extensions:t}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{},r=new this._core.common.ChatError({code:t,message:s});throw i.setError(r).end(),r}})}deleteMessageExtensions(h,g){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t},ssoLog:s}=this._core,{conversationType:n,conversationID:r,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:${r} messageID:${o} sequence:${i} time:${a} operateType:`+l}),this._generateServerExtensions(h,u));try{let r;if(n===t.CONV_C2C?r=yield Rr(h,d,l):n===t.CONV_GROUP&&(r=yield Dr(h,d,l)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(h,r);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:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],n=t.ExtensionList||[],i=[],o=0,a=0,l=[];return n.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;i.push({code:e,key:t,value:s}),0===e?o++:a++,l.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<l.length&&this._updateLocalExtensions(e.ID,l),{resultList:i,successCount:o,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);let r=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=r&&r.set(e,{value:s,seq:t})})}_fetchMessageExtensions(l,s){return I(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:r,clientSequence:n,random:i,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:n+`_${i}_`+o,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(i=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(l,s)),i){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=i,r=(i.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let n=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||n.push({key:t,value:e})})}return n}}catch(e){console.error(e)}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits("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:r,TinyId:n,MsgLastSeq:i,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},n=n+`-${o}-`+a;this._extensionsLatestSequenceMap.set(n,i),1===r?this._handleMessageExtensionsUpdated({messageID:n,updateMessageExtensionsInfo:e}):2===r?this._handleMessageExtensionsDeleted({messageID:n,deleteMessageExtensionsInfo:t}):3===r&&this._handleMessageExtensionsCleared({messageID:n,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:n=[]}=e,i=[];n.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(i.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:i}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:n=[]}=e,i=[];n.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(i.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:i}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:n,clearMessageExtensionsInfo:i=[]}=e,o=[];i.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(n)&&(this._messageExtensionsMap.get(n)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&o.push(t)}),this._clearLocationExtensions(n,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:n,keyList:o}})}};let Lr={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"}},Nr={setMessageExtensions:[Lr,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Lr],deleteMessageExtensions:[Lr]},Gr=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}}}),Nr),Pr=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 wr{constructor(e){this._core=e}deleteMessage(s){return I(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 I(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:n}=i;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:n,MsgTimeStamp:r}}})})}}class Ur{constructor(e){this._core=e}deleteMessage(s){return I(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 I(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 kr{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:n,revokeReason:i,revoker:o}=e;let a={};var l=this._core.message["messageDataHandler"];return(a=l.revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}))||(a={conversationID:e,sequence:t},r&&n&&s&&(a.ID=r+`-${n}-`+s)),a=Object.assign(Object.assign({},a),{revoker:o,revokeReason:i,revokerInfo:{userID:o,nick:"",avatar:""}})}updateRevokerInfo(t){return I(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 I(this,void 0,void 0,function*(){var e=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t});return null!=e&&e.data?null==(e=e.data)?void 0:e.reduce((e,{userID:t,nick:s,avatar:r})=>(e[t]={nick:s||"",avatar:r||""},e),{}):null})}}var Fr=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Ur(e),this._c2cMessageAction=new wr(e),this._messageHelper=new kr(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 I(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:r,_onlineOnlyFlag:n,sequence:i,random:o,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!n){let e="C2C"===s?i+`_${o}_`+a:String(i);l.push(e)}u.push(e)}}),0===l.length)return this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}};30<l.length&&(l=l.slice(0,30),u=u.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:l}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:l}),this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(i){return I(this,void 0,void 0,function*(){var s;let r=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:e,isRevoked:t}=i;var n;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"});r.setLogInfo({message:`type:${i.type} from:${i.from} to:`+i.to});try{if(n="C2C"===e?yield this._c2cMessageAction.revokeMessage(i):yield this._groupMessageAction.revokeMessage(i)){let e=n["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 r.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 I(this,void 0,void 0,function*(){var e;return t.isResend=!0,t.status="unSend",null==(e=null==(e=this._core)?void 0:e.apiMap)?void 0:e.sendMessage(t,s)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(n){if(0!==n.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;n.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:n=""}=n[0];e(n)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,n):t.emitInnerEvent(r.MESSAGE_DELETED,n)}}_handleRevokeMessageSuccess(n){return I(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:r}=n;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([n])})}};class qr{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new qr({index:e,data:t})}constructor(e){this.type=ir.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 xr{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new xr({description:e,longitude:t,latitude:s})}constructor(e){this.type=ir.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 Vr=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(ir.MSG_FACE,qr),e.message.messageFactory.registerElementClass(ir.MSG_LOCATION,xr),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 qr({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],n=this._core.apiMap.createTextMessage(e),i=this._core["OuterConstant"];if(!n)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==i.MSG_AT_ALL?(t.push({GroupAtAllFlag:0,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:1}),s.push(i.MSG_AT_ALL))}),n._groupAtInfoList=t,n.atUserList=s}return n}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:n,payload:i,needReadReceipt:o,receiverList:a,cloudCustomData:l="",isSupportExtension:u=!1}=e;if(!Array.isArray(i._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(i.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:n,payload:i,needReadReceipt:o,isSupportExtension:u,cloudCustomData:l,receiverList:a});return t.setRelayFlag(!0),t.setElement(i._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new xr({description:t,longitude:s,latitude:r}),s=this._core.common.getCurrentUserID(),(r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),r):null}};let Br=class{init(e){this._messageHelper=new kr(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return I(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return I(this,void 0,void 0,function*(){let o=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:a}}=this._core;s.forEach(e=>{var{MsgRand:e,MsgSeq:t,To_Account:s,From_Account:r,RevokerInfo:{Revoker_Account:n,Revoke_Reason:i,Reason:i=i}}=e,s=a()===r?"C2C"+s:"C2C"+r,r=this._messageHelper.generateRevokeMessage({conversationID:s,sequence:t,random:e,revoker:n,revokeReason:i});o.push(r)}),0<o.length&&(yield this._messageHelper.updateRevokerInfo(o),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:o}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return I(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)}},jr=class{init(e){this._messageHelper=new kr(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 I(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:u}=i,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:n}}=this._core,h=!1;u&&(h=n({groupID:u.GroupId})||!r(u.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:n,TopicId:i,RevokerInfo:{Revoker_Account:o=(null==l?void 0:l.Revoker_Account)||"",Reason:a=(null==l?void 0:l.Reason)||""}}=e,i=this._messageHelper.generateRevokeMessage({conversationID:i?"GROUP"+i:"GROUP"+s,sequence:t,random:e,tinyID:n,clientTime:r,revoker:o,revokeReason:a});(h?(i.revokerInfo.nick=u.From_AccountNick,i.revokerInfo.avatar=u.From_AccountHeadurl,c):d).push(i)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),c.push(...d)),0!==c.length&&t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:c})}catch(e){console.debug(e)}})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var Kr=new class{constructor(){this._c2cMessageReceiver=new Br,this._groupMessageReceiver=new jr}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class Hr{constructor(e){var t=(this._core=e)["constants"];this._messageHelper=new kr(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield function(i){return I(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=E.core,n=e.groupStore.getGroupMap(),t={NotifyReqList:i.map(e=>{var t=n.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*E.core.common.timeManager.getServerTimeMs()}})||[]};return r.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:t})})}(s);if(t){let s=[];null!=(e=null==t?void 0:t.NotifyRspList)&&e.forEach(e=>{var{GroupId:e,NotifyMsgList:t}=e,e=this._parseServerRevokeMessageList({groupID:e,serverRevokeMessageList:t});s.push(...e)}),0!==s.length&&(yield this._emitMessageRevokedEvent(s))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){let{serverRevokeMessageList:t,groupID:o}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:n=""}}=e,i="GROUP"+o,i=this._messageHelper.generateRevokeMessage({conversationID:i,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:n});a.push(i)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return I(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 Wr{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new kr(e)}getRoamingMessagesByAnchor(p){return I(this,void 0,void 0,function*(){var n;try{var{conversationID:i,count:e,messageID:r,time:o,direction:a}=p;let t=o,s="";if(!o){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(i)){let e=this._historyMessageListFetchAnchors.get(i);t=e.lastMessageTime,s=e.messageKey}}var l=i.replace(Sr,""),u=yield function(i){return I(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:n}=i,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:n};return 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:r}=u;this._historyMessageListFetchAnchors.set(i,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],h=this._parseMessage(d);c.push(h)}var g=this._core.message.messageHelper.filterValidMessages(c);return{messageList:g,nextReqMessageIDFromServer:null==(n=g[0])?void 0:n.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){Sr;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 $r=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new Hr(e),this._c2cMessageHistory=new Wr(e),this._messageHelper=new kr(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 I(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 r=this._core.ssoLog.createSSOLogData({method:"getMessageList"}),n=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:n,targetCount:20})){let e=null;if(t.startsWith(Ir)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:20,direction:or.FORWARD}):t.startsWith(Sr)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:20,direction:or.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 Cr(t),t.startsWith(Sr)&&(yield Er({messageList:a,conversationID:t}));var _=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,l.length+n),m=_.filter(e=>e.isRevoked),v=(yield this._messageHelper.updateRevokerInfo(m),{nextReqMessageID:o?"":String(i),messageList:_,isCompleted:o}),f=_.map(e=>e.sequence);return r.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s}
3
+ availableLocalMessagesCount: ${n} sequenceList: ${JSON.stringify(f)} `}).end(),{code:0,data:v}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return r.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${n}}`}).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(r){return I(this,void 0,void 0,function*(){var i,o;let{conversationID:e,sequence:a,time:t,direction:l=or.FORWARD}=r,u=this._core.helper["isEmpty"];if(![or.BACKWARD,or.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=20}=r,c=(s=20<s?20:s,null);if(e.startsWith(Ir)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:n}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),l===or.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==or.BACKWARD)return{code:0,data:c};{if(u(r)&&u(n))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(i=null==r?void 0:r[r.length-1])?void 0:i.sequence)||0,t=(null==(o=null==n?void 0:n[n.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:r.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(Sr)&&(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===or.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(g){return I(this,void 0,void 0,function*(){var t;let{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:n,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:r()}),h=u["type"];h===n?(d.type=1,d.toAccount=g.replace(n,"")):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(n){return I(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=n,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return 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),r=s["length"];if(!t)return r;let n=-1;return null!=e&&e.startsWith(Sr)?n=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(Ir)&&(n=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===n?0:n}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return I(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),n=r.length;let i=n,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=n;return s?(l=r.findIndex(e=>t.startsWith(Sr)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,i=l):a=e<n?n-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=r.slice(a,l),o.isCompleted=i<=e,t.startsWith(Sr)&&(yield Cr(t),yield Er({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()}},Yr=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(n){return I(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=n,r=yield function(i,o){return I(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=i,{store:r,common:n}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=r.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=r.get("instance"))?void 0:e.sdkAppId},s=yield n.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},zr=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return I(this,void 0,void 0,function*(){let{message:e,language:t=pr.ZH_PY}=s,r=(e.payload||{})["url"];var n=null==(n=this._core.store.get("login"))?void 0:n.userID,n=(e.from===n&&"out"===e.flow&&(r=e.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(i=vr.exec(r))?void 0:i[1])||"mp3"),i=mr[t]||_r;try{let s=yield function(e){var{store:t,common:s}=E.core,{url:e,format:r,serverLanguageType:n}=e,n={BytesUrl:e,BytesEngServiceType:n,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:n})}({url:r,format:n,serverLanguageType:i});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{},r=new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s});console.error(r),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(r).end()}})}_validateVoiceFormat(e){if(!vr.test(e))throw new this._core.common.ChatError({code:2119})}};class Jr{constructor(e){var{constants:t,common:s,utils:r}=E.core,{CONV_C2C:t,CONV_GROUP:n}=t.OuterConstant,{ID:e,tinyID:i,from:o,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:l,sequence:u,cloudCustomData:c="",nick:d="",avatar:h="",clientSequence:g,conversationType:p,groupID:_,_elements:m,time:v}=e,i=(this.ID=e||i+`-${s}-`+l,this.messageRandom=l,this.from=o,this.messageSender=o,this.time=v,this.messageSequence=u,this.clientSequence=g||u,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=h,this.nick=d,r.deepCopyWithMethods(m));i.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=i,e?p.startsWith(t)?this.receiverUserID=a:p.startsWith(n)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Qr{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:n,JsonMsgKey:i}=e||{},e=e.map(e=>Or(e));return new Qr({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:n,downloadKey:i})}constructor(e){this.type=E.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:n,pbDownloadKey:i="",downloadKey:o="",version:a=0,layersOverLimit:l=!1}=e,u=[];t.forEach(e=>{e&&(e=new Jr(e),u.push(e))}),this.content={messageList:u,title:s,abstractList:r,compatibleText:n,version:a,downloadKey:o,pbDownloadKey:i,layersOverLimit:l}}validateBeforeSend(){var e=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:r,pbDownloadKey:n,title:i,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:n,Title:i,Version:o,MsgList:yr(a)}}}}var Xr=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Qr),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===r.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){var t,s=this._core["common"];return e?(t=new Qr(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 I(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,r=0,n;if(n=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<n;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<n;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,n=null;if(11264<i){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return I(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:yr(e)};return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];n=new Qr(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(n)}catch(e){console.error(e)}}var{message:o}=(yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,l))["data"];return n&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){throw console.error(e),e}})}downloadMergerMessage(i){return I(this,void 0,void 0,function*(){try{var e=i.payload,t=e["downloadKey"],s=S(e,["downloadKey","pbDownload","type","messageList"]),r=((yield function(e){return I(this,void 0,void 0,function*(){return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(t))||{})["MsgList"],n=null==r?void 0:r.map(e=>{e=Or(e);return new Jr(e)});return"function"==typeof i.isOnlineMessage?i.setElement({type:i.type,content:Object.assign({messageList:n},s)}):(i.payload.messageList=n,i.payload.downloadKey="",i.payload.pbDownloadKey=""),i}catch(e){console.error(e)}})}},e=new class{install(e){this._core=e,E.init(e),Fr.init(e),Vr.init(e),Kr.init(e),$r.init(e),Tr.init(e),Yr.init(e),zr.init(e),Ar.init(e),Xr.init(e),br.init(e),e.helper.registerValidateConfig({auth:Pr,params:Gr}),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),Kr.dispose(),$r.dispose(),Ar.dispose(),br.dispose()}_reset(){$r.reset()}},Zr=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(p,_){return I(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:n,qs:i,headers:o={},resources:a,dataType:l="text",uploadByIP:u,uploadIP:c}=p,d=n;if(i){let e=this._queryString(i);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(r.toUpperCase(),d,!0),h.responseType=l;var g=Object.assign({},o);if(u&&c&&(g.host=c),!t(g))for(let e in g)g.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&h.setRequestHeader(e,g[e]);return h.onload=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e);if(200===h.status)_(null,e);else{if(c&&!d.includes(c))return p.url=this._domainName2IP(d,c),p.uploadByIP=!0,this.request(p,_);_({code:h.status,message:JSON.stringify(h.responseText)},e)}},h.onerror=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e),t={code:h.status,message:0===h.status?"CORS blocked or network error":JSON.stringify(h.responseText)};_(t,e)},p.onProgress&&h.upload&&(h.upload.onprogress=e=>{var{total:e,loaded:t}=e,s=Math.min(Math.floor(100*t/e),100);p.onProgress({total:e,loaded:t,percent:s/100})}),h.send(a),h})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(s,r="&",n="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+n;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let en=["unknown","image","video","audio","log"];var tn,sn=new class{init(e){this._core=e}request(s,r){let e,{MINI_APP_NAMESPACE:n,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=S(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?en[s.fileType]:"image"})}return(h=n.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:c,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:c,callback:r})}}))).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,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var n=+t.statusCode;200==n?s(null,{statusCode:n,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:n,message:JSON.stringify(t.data)},{statusCode:n,headers:r,data:void 0})}};function rn(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function nn(e){e=e||99999999;return Math.round(Math.random()*e)}function on(e,t=!0,s=!0){var r=Date.now();return t?s?r-e+" ms":Math.round((r-e)/1e3)+" s":s?r-e:Math.round((r-e)/1e3)}function an(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function ln(e,t){return Math.round(Number(e)*10**t)/10**t}function un(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function cn(e){return e<=1048576?ln(e/1024,1)+"KB/s":ln(e/1048576,1)+"MB/s"}let dn="TIMImageElem",hn="TIMSoundElem",gn="TIMFileElem",pn="TIMVideoFileElem",M="RichMediaMessagePlugin",_n=["rich.my-imcloud.com","imrich.qcloud.com"],mn=((L=tn=tn||{}).UNSENT="unSend",L.SUCCESS="success",L.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,r]=s.split("?");if(!r)return s;let t=r.split("&").reduce((e,t)=>{var[t,s]=t.split("=");return t&&"authKey"!==t&&(e[t]=s||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?s+"?"+e:s}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(mn).some(e=>e.test(t))}extractFileFromInput(e){return rn(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?Array.isArray(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(s){return I(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=_n;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=_n}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),n=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,n));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,s=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:s}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===s}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,s=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),s()},t.onerror=()=>{e({width:0,height:0}),s()},t.src=r})}},vn=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?sn:Zr,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return I(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(),r=yield this._createCosOptions(l),n=yield this._uploadFile(r),i=(this._handleUploadError(n,l),this._createUploadResult(e,n)),o=Date.now()-s,a=`size:${un(e.size)} time:${o}ms speed:`+cn(1e3*e.size/o);return console.log(t+` ok. name:${e.name} `+a),{uploadOptions:r,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 on(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:on(Date.now(),!1),uploadSpeed:cn(1e3*e.size/on(Date.now(),!1))}}_createCosOptions(h){return I(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:s}=this._prepareUploadParams(h),r=this._isC2CConversation(h.message.conversationID)?1:2;try{var n=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:h.message.from,conversationType:r}),{uploadUrl:i,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c}=n,d=!y.isPrivateNetWork()&&n.uploadIP;return{url:this._getRawOrUploadProxyUrl(i),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,uploadIP: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:r}=y.getPlatformFlags(),s=s||r,r=s&&e.message.type!==gn,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+nn(999999)+e;return{fileName:an(r?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 I(this,void 0,void 0,function*(){var t=M+" fetchCosSignatureUrl",s=y.isSimpleCos(),r=this._prepareCosRequestData(e),n=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(n,i,o){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:n,data:i}),r=s.head.seq+n;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(n,r,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:r,str_download_url:n,str_upload_url:i,str_snapshot_url:o,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:n,uploadUrl:i,requestSnapshotUrl:o,fileKey:a}}let{upload_url:r,download_url:n,snapshot_url:i,thumb_url:o,large_url:a,file_key:u}=l;return{uploadUrl:r,downloadUrl:n,requestSnapshotUrl:i,thumbUrl:o,largeUrl:a,fileKey:u}}_prepareCosRequestData(e){return 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(n){return I(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(n,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(n).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{var r=null==(t=e.error)?void 0:t.Code,n=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===n}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=y.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let fn=["jpg","jpeg","gif","png","bmp","image","webp"],Sn={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class In{constructor(e,t){this.instanceID=nn(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 En(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,n=parseInt(e)||0,s=parseInt(s)||0,i={url:void 0,width:0,height:0};if((n<=s?n:s)<=r)i.url=t,i.width=n,i.height=s;else{s<=n?(i.width=Math.ceil(n*r/s),i.height=r):(i.width=r,i.height=Math.ceil(s*r/n));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";i.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?S(i,["url"]):i}class Cn{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=dn;var{uuid:e,file:t,imageFormat:s,imageInfoArray:r=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:s,uuid:e,imageInfoArray:[]},this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:s,ImageInfoArray:r,UUID:n}=t,i=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new Cn({imageFormat:s,imageInfoArray:i,uuid:n})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:n}=y.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),n)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new In(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,s;e.url&&""!==e.imageUrl&&([t,...s]=e.imageUrl.split("://"),s=s.join("://"),r.includes(t)||e.setImageUrl("https://"+s))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=Sn[e.toUpperCase()]||Sn.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var s,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)s=this.content.imageInfoArray[e],t[e].size&&(s.size=t[e].size),t[e].url&&s.setImageUrl(t[e].url),t[e].width&&(s.width=t[e].width),t[e].height&&(s.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,s=t[2];t[2]=t[1],t[1]=s;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],En({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 Mn=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(dn,Cn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(n){var i,o,a,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createImageMessage"}),t=(console.log(M+" createImageMessage options:",n),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({},n),{from:t})),r=this._processImage(n);n.payload.file=r;var l={imageFormat:Sn.UNKNOWN,uuid:y.generateUUID(r),file:r,imageInfoArray:[]},u=new Cn(l);return s.setElement(u),this._messageOptionsMap.set(s.clientSequence,n),console.log(M+" createImageMessage OK imageMessage:",s),e.end(),s}catch(n){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)&&t.call(e,n).end(),console.error(M+" createImageMessage error:",n),n}}upload(r){return I(this,void 0,void 0,function*(){console.log(M+" uploadImage message:",r);var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,n,s){return I(this,void 0,void 0,function*(){var e=n["to"],{uploadOptions:e,response:t}=yield vn.uploadToCOS({uploadFileType:1,file:s,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){console.log(M+" generateImageInfo");var{location:e,fileSize:t,width:s,height:r,smallImageUrl:n,smallImageWidth:i,smallImageHeight:o,largeImageUrl:a,largeImageWidth:l,largeImageHeight:u,imageInfoArray:c}=e,e=y.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):n&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:n,smallImageWidth:i,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return En({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,n;for(var i of e)1===i.type?(r=i,r.size=t):2===i.type?(n=i,n.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},n),Object.assign({},r)]}_parseResponse(r,n){return I(this,void 0,void 0,function*(){console.log(M+" parseResponse");try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,n,"thumb"),yield this._getImageInfoByUrl(t,n,"large")),y.isSimpleCos()&&!y.isPrivateNetWork()&&(yield this._getImageInfoArray(s,n),null!=n)&&n.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,n))}return n}catch(e){throw 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(r,n,i){return I(this,void 0,void 0,function*(){try{var e=y.addAuthToUrl(r),{width:t=0,height:s=0}=yield y.probeImageWidthHeight(e);n.width=t,n.height=s,"thumb"===i?(n.smallImageUrl=r,n.smallImageWidth=t,n.smallImageHeight=s):(n.largeImageUrl=r,n.largeImageWidth=t,n.largeImageHeight=s)}catch(e){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"],r=e.payload["file"];return s?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw console.warn(M+" _processImage error:",e),e}}_processMiniAppImageFile(e){rn(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(r,n){return I(this,void 0,void 0,function*(){var e=M+" getDownloadIP domainName: "+r;try{var t,s=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:o},n=e.generateProtocolData({servcmd:s,data:r}),i=n.head.seq+s;return yield t.sendPacket(n,{requestId:i})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=n.location.split("/"))[0]=s.str_final_ip,n.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(s,r){return I(this,void 0,void 0,function*(){var t=M+"._getImageInfoArray";try{var e=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:o},n=e.generateProtocolData({servcmd:s,data:r}),i=n.head.seq+s;return yield t.sendPacket(n,{requestId:i})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(s,this._core);return r.imageInfoArray=this._processImageInfoResponse(e),console.log(t+" ok"),r}catch(e){throw r.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 r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),fn.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:s}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new s.ChatError({code:2108});if(20971520<=r)throw new s.ChatError({message:"File size exceeds limit: "+un(20971520)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let yn=104857600;function On(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(;r.length<i;)r.push("0");for(;n.length<i;)n.push("0");for(let s=0;s<i;s++){let e=parseInt(r[s]),t=parseInt(n[s]);if(e>t)return 1;if(e<t)return-1}return 0}class Tn{constructor(e){this.type=gn,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:r,UUID:n}=e;return new Tn({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:s,fileName:r,fileSize:n}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:y.removeAuthToUrl(s),FileName:r,FileSize:n,UUID:e}}}_getFileInfo(e){return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(y.getPlatform().IN_UNI_NATIVE_APP&&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=nn(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 An=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(gn,Tn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(s){var r,n,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==(r=this._core.store.get("login"))?void 0:r.userId,a=null==(i=null==(n=this._core)?void 0:n.message.messageFactory)?void 0:i.createMessage(Object.assign(Object.assign({},s),{from:o})),l={uuid:y.generateUUID(t),file:t},u=new Tn(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 I(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>yn)throw new t({message:"File size exceeds limit: "+un(yn)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,n,t){return I(this,void 0,void 0,function*(){var e=n["to"],e=(yield vn.uploadToCOS({uploadFileType:1,file:t,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e||i){let e=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(r||n){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(e){if(!(s||r||n))throw new i({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&On(e,"2.5.0")<0)throw new i({message:"WXChooseMessageFile requires SDK version 2.5.0 or higher"});if(r&&On(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 Rn=["mp4","quicktime","mov"],Dn=104857600;class bn{constructor(e){this.type=pn,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:r,VideoDownloadFlag:n,VideoUUID:i,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:_,SnapshotUrl:m}=e;return new bn({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:n,videoUUID:i,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s}=e;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:r,videoDownloadFlag:n,videoUUID:i,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:y.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:n,VideoUUID:i,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:y.removeAuthToUrl(_),SnapshotUrl:y.removeAuthToUrl(m)}}}}var Ln=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(pn,bn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(s){var r,n,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==(r=this._core.store.get("login"))?void 0:r.userId,a=null==(i=null==(n=this._core)?void 0:n.message.messageFactory)?void 0:i.createMessage(Object.assign(Object.assign({},s),{from:o})),l={videoFormat:t.videoFile.type,videoSecond:ln(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 bn(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(r){return I(this,void 0,void 0,function*(){console.log(M+" uploadVideo message:",r);var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:s}=t,t=y.addAuthToUrl(t);return e.updateVideoUrl(t),y.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>Dn)throw new t({message:"File size exceeds limit: "+un(Dn)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===Rn.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(r,n,s){return I(this,void 0,void 0,function*(){var e=n["to"],{response:e,uploadOptions:t}=yield vn.uploadToCOS({uploadFileType:2,file:s,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,n;try{var i=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(n=this._core)?void 0:n.utils;let t=e.payload["file"],s={};if(o&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url),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 t=(null==(t=this._core)?void 0:t.utils)["IN_ALIPAY_MINI_APP"],s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(t)throw new s({message:"VideoUnsupportedInAlipay"});if(rn(e))throw new s({message:"FileUnsupportedInMiniApp"});return{url:(e=Array.isArray(e.tempFiles)?e.tempFiles[0]: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){var{name:t,size:s=1,duration:r=0,type:n}=e,n=n.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:n}}_getSnapshotInfoByUrl(n){return I(this,void 0,void 0,function*(){try{console.log(M+" _getSnapshotInfoByUrl url:",n);var e,t,s,r=((yield function(i,o){return I(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,r=t.generateCosSpecifiedData({servcmd:e,data:i}),n=r.head.seq+e;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:y.getPlatform(),cover_name:an(nn(99999)),snapshot_url:n},this._core))||{})["download_url"];return(console.log(M+" _getSnapshotInfoByUrl OK snapshotUrl:",r),y.isEmpty(r))?{}:(e=y.addAuthToUrl(r),{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 Nn{constructor(e){this.uploadProgress=0,this.type=hn,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:r,UUID:n}=e;return new Nn({url:e,downloadFlag:t,second:s,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:s,size:r,second:n}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:y.removeAuthToUrl(s),Download_Flag:t,Second:n,Size:r,UUID:e}}}}var Gn,Pn,wn,Un=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(hn,Nn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(t){var s,r,e,n;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==(n=this._core.store.get("login"))?void 0:n.userId),a=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.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 Nn(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,t),e.end(),a}catch(t){throw null!=(n=(e=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)&&n.call(e,t).end(),console.error(M+" createAudioMessage error:",t),t}}upload(s){return I(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: "+un(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,n,t){return I(this,void 0,void 0,function*(){var e=n["to"],e=(yield vn.uploadToCOS({uploadFileType:3,file:t,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["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 kn={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}},Fn={createImageMessage:kn,createAudioMessage:kn,createVideoMessage:kn,createFileMessage:kn},qn={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},xn={TIMImageElem:Mn,TIMFileElem:An,TIMVideoFileElem:Ln,TIMSoundElem:Un},Vn=new class{install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:n}}=(this._core=e)["constants"];Mn.init(e),An.init(e),Ln.init(e),Un.init(e),vn.init(e),y.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,n].includes(e[0].type)}),e.helper.registerValidateConfig({auth:qn,params:Fn})}sendMessage(r,n){return I(this,void 0,void 0,function*(){var e,t,s;try{return console.log("sendMessage message:",r),yield this._upload(r),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,n)}catch(e){throw console.error("sendMessage error:",e),e}})}_upload(r){return I(this,void 0,void 0,function*(){var t,s;if(!0!==r._relayFlag)try{let t=xn[r.type];if(t){let e=this._core.ssoLog.createSSOLogData({method:"upload"});e.setLogInfo({message:"type:"+r.type}),yield t.upload(r),e.end()}}catch(e){throw r.status=tn.FAIL,e instanceof Error&&(e.data={message:r}),this._core.message.messageDataHandler.storeConversationMessage(r),null!=(s=(t=this._core.ssoLog.getSSOLogData("upload")).setError)&&s.call(t,e).end(),e}})}},O=new class{init(e){this.core=e}},Bn=e=>{var{OuterConstant:t,utils:{isString:s}}=O["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},jn=e=>{var{OuterConstant:t,utils:{isString:s}}=O["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},Kn=e=>{var{OuterConstant:t,utils:{isString:s}}=O["core"];return s(e)&&e===t.CONV_SYSTEM},Hn=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 Wn(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 $n(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 Yn{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=Hn(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:r,isUnreadC2CMessage:n}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||n&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=Hn(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}}(G=Gn=Gn||{})[G.OFF=0]="OFF",G[G.ON=1]="ON",Pn=Pn||{},Pn[Pn.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID",(N=wn=wn||{})[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 T=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:e,notificationCenter:t,appStore:{conversationStore:s},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n},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(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),e.registerWorkflowStep(r.RECEIVE_C2C_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(r.RECEIVE_C2C_NEW_MESSAGE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(r.RECEIVE_GROUP_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.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:r=[],isUnreadC2CMessage:n}=e.result[t.UNREAD_MESSAGE_SYNC]||{},i=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:n}),i=!0)}),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,n=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:i}=this._core.OuterConstant,o=!1;for(let s=0;s<n.length;s++){let e=n[s],t=""+i+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:n=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:n}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:n}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=r,i.__sequence=n,this._groupAtTipsList.push(i)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,n=e.getCurrentUserID(),i=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==n){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),i=!0)}}),i&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:n}=this._core,i=(null==r?void 0:r.getLocalMessageList(t))||[];let o={};for(let e=(i.length||0)-1;0<=e;e--)if(!i[e].isDeleted){o=i[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===o.sequence&&r.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),r.updateLastMessage(o),e=!0),t.startsWith(n.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:n=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(n&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:n}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=n(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(this._name+` conversationID:${t} lastMessage updated`))}}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),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 n=0;n<t;n++){let t=new Yn(o[n]),{conversationID:s,type:r}=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),r===i.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===i.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[n].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:o[n].lastMessage,isInstantMessage:l}),!0===c&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:u}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:n}=e,e=this.getLocalConversation(e),i=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:o},common:{deepMerge:a}}=(!1===n&&i.push("lastMessage"),r&&i.push("isPinned"),this._core);r(n)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),o(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,i,[null,void 0,"",0,NaN])}_patchLastMessage(e){let n=this._core["OuterConstant"],{conversationID:t,lastMessage:i,isInstantMessage:o}=e,a=this.getLocalConversation(t);if(a&&i){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=i;o&&(e&&(a.lastMessage.payload=e),a.type===n.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],n=[],i=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?i:n).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(n.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(i);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:n,CONV_C2C:i}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===i){let e=t.replace(i,"");s.push(e)}else if(e===n){let e=t.replace(n,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:n},appStore:{userStore:i},user:s}=this._core,o=!1;null!=(t=s.userProfile)&&t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(t=>{var s=t["userID"],r=this.getLocalConversation(""+n+s);if(r){let e=(null==(s=i.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,n=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,n=!0)}),n&&this.emitConversationListUpdate()}_isConversationNeedShow(e){var t,s,r,e=this.getLocalConversation(e);return!(!this._core.utils.isUndefined(e)&&(t=this._core.OuterConstant,s=e.type===t.CONV_TOPIC,r=e.type===t.CONV_GROUP&&e.subType===t.GRP_ROOM,e=e.type===t.CONV_GROUP&&e.subType===t.GRP_LIVE,s||r||e))}updateUnreadCount(e,t=!0){let s,r,n=!1;var i,o=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return o&&(i=o.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${i} newUnreadCount:`+a),i!==a)&&(o.unreadCount=a,(n=!0)===t)&&this.emitConversationListUpdate(),n}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(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 t=this._core["OuterConstant"],e=this.getLocalConversationList(),s=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||""!==e.messageRemindType&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(s+=e.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(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:n=0,lastReadSequence:i=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let r=e-1;0<=r;r--){let e=o[r],t=n&&e.time>n,s=i&&e.sequence>i;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:n,CONVERSATION_UPDATED:i,LOGOUT:o,DESTROY:a,SYNC_CONVERSATION_LIST:l}}=this._core,{GROUP_AT_TIPS:u}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(l,this._handleConversationSynced,this),e.unSubscribeInnerEvent(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},zn=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return I(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 T.getLocalConversationList();if(t(o))return 0===o.length?[]:T.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:r,hasUnreadCount:n,hasGroupAtInfo:i}=o;return T.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,n)&&this._filterGroupAtInfo(e,i))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},Jn=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return I(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:r},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=Wn(t);T.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Qn=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return I(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:t=[]}=e||{};t.forEach(e=>{var{GroupId:e,MemberList:t}=e,t=(null==(t=t[0])?void 0:t.MsgFlag)||"",e=""+this._core.OuterConstant.CONV_GROUP+e;T.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Xn=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return I(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:n},appStore:{groupStore:i},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=T.getLocalConversation(u);if(Kn(u))o.data.conversation=a;else{let t=!1;var l=Bn(u)?s:r;if(e(a)&&(t=!0,a=new Yn({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 Jn.get([e]))}if(l===r){let e=u.replace(r,"");if(!i.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==n&&(yield Qn.get([e]))}}}return o})}_handleC2CConversation(o,a){return I(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:n}}=this._core,i=o["conversationID"],e=yield null==(e=e.userProfile)?void 0:e.getUserProfile({userIDList:[a]});if(0===(null==e?void 0:e.data.length))throw new t.ChatError({code:wn.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=n.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),n=T.hasLocalConversation(i);console.log(this._name+`._handleC2CConversation conversationID:${i} hasLocalConversation: `+n),n?r.updateConversation(i,o):T.appendToPinnedConversation(o)})}_handleGroupConversation(r,n){return I(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:n}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),T.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):T.appendToPinnedConversation(r)})}},Zn=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return T.getTotalUnreadMessageCount()}},ei=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{ALL_MESSAGE_READ:i}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(n,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),T.markMessageAsRead({conversationID:e,lastReadTime:t}),T.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),T.markMessageAsRead({conversationID:e,lastReadSequence:t}),T.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(l){return I(this,void 0,void 0,function*(){let e=this._core["OuterConstant"],t=l["conversationID"],s={code:0,data:{}},r=T.getLocalConversation(t);if(console.log(this._name+`.setMessageRead conversationID:${t} unreadCount:`+((null==r?void 0:r.unreadCount)||0)),r){var n=!(null!=(i=null==(n=this._core)?void 0:n.helper)&&i.isEmpty(r.groupAtInfoList));if(r.type===e.CONV_GROUP&&n&&this._deleteGroupAtTips(t),0!==r.unreadCount){var{ssoLog:i,helper:{ChatError:o}}=this._core,a=i.createSSOLogData({method:"setMessageRead"});a.setLogInfo({message:"conversationID:"+t});try{if(r.type===e.CONV_C2C){let e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(t,e),a.setLogInfo({moreMessage:"lastMessageTime:"+e}).end()}if(r.type===e.CONV_GROUP){let e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(t,e),a.setLogInfo({moreMessage:"lastMessageSequence:"+e}).end()}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new o({functionName:"setMessageRead",code:t,message:s});throw a.setError(r).end(),r}r.type===e.CONV_SYSTEM&&(r.unreadCount=0),T.emitConversationListUpdate()}}return s})}setAllMessageRead(){return I(this,arguments,void 0,function*(s={}){let{OuterConstant:{READ_ALL_MSG:e},ssoLog:t}=this._core,n=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 r=yield function(s){return I(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(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&T.emitConversationListUpdate(),n.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 n.setError(t).end(),t}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&T.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:n},appStore:t}=this._core,i=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of i)if(1<=t.unreadCount){if(1===o&&t.type===r){let e=this._getLocalMessageMaxTime(t);T.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===n){let t=s.replace(n,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);T.markMessageAsRead({conversationID:s,lastReadSequence:e})}}T.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:n,CONV_GROUP:i,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:0,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===n&&0===a.allC2CMessageReadStatus){if(a.allC2CMessageReadStatus=1,r===o)break}else if(e===i){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:n}=this._core["utils"],i=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;n(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&i.push(e+`-${t}-`+s))}),i}_deleteGroupAtTips(o){return I(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=T.getLocalConversation(o);if(e){var i=(null==e?void 0:e.groupAtInfoList)||[];if(0!==i.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,n=[...i];e({groupID:o.replace(s,"")})&&0===(n=i.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return I(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:n.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+i.length),this._clearGroupAtInfoList(o))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=T.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&T.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 I(this,void 0,void 0,function*(){try{yield function(e,t){return I(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),T.markMessageAsRead({conversationID:e,lastReadTime:t}),T.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:{GroupId:e,MsgReadedSeq:t}})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(this._name+"._setGroupMessageRead ok, lastReadSequence:"+t),T.markMessageAsRead({conversationID:e,lastReadSequence:t}),T.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:n,READ_ALL_GROUP_MSG:i}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![r,n].includes(o))&&(e!==s||![r,i].includes(o)))}},ti=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,o){var{isArray:t}=this._core["utils"];if(t(e)){let n=this._core["OuterConstant"],i=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=T.getLocalConversation(""+n.CONV_C2C+t):2===e&&(r=T.getLocalConversation(""+n.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+o),o&&!r.isPinned&&(r.isPinned=!0,i=!0),!o)&&r.isPinned&&(r.isPinned=!1,i=!0)}),i&&T.emitConversationListUpdate(!0)}}pinConversation(t){return I(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,ssoLog:e,helper:{ChatError:n}}=this._core,{conversationID:i,isPinned:o}=t,a={code:0,data:{conversationID:i}},l=T.getLocalConversation(i);if(l&&l.isPinned===o)return a;if(Kn(i))return l&&(l.isPinned=o),T.emitConversationListUpdate(!0),a;var u=e.createSSOLogData({method:"pinConversation"});u.setLogInfo({message:`conversationID:${i} isPinned:`+o});try{let e=null,t=(Bn(i)?e={Type:1,To_Account:i.replace(s.CONV_C2C,"")}:jn(i)&&(e={Type:2,GroupId:i.replace(s.CONV_GROUP,"")}),yield function(r,n){return I(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return n.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(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 Yn({conversationID:i,type:Bn(i)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});T.setLocalConversation(i,e)}T.emitConversationListUpdate(!0)}return a}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"pinConversation",code:t,message:s});throw u.setError(r).end(),console.error(this._name+".pinConversation fail:",r),r}})}},si=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],n=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&n.push(""+r.CONV_C2C+t),2===e&&n.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+n),this._deleteLocalConversationList(n)}}deleteConversation(t){return I(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:Pn.ONLY_CONVERSATIONID})):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(a){return I(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:n=0}=a,{ssoLog:e,helper:{ChatError:i}}=this._core,t=`conversationIDList:${s} clearHistoryMessage:`+r,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,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:wn.CONV_NOT_FOUND});return o.end(),console.log(this._name+"._deleteConversation ok."),{code:0,data:n===Pn.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new i({functionName:"deleteConversation",code:t,message:s});throw o.setError(r).end(),console.error(this._name+"._deleteConversation fail:",r),r}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!T.hasLocalConversation(e)&&((t=null==(t=T.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,i){return I(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,n={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:i?1:0};if(t.forEach(e=>{var t,s;T.hasLocalConversation(e)&&(t=(null==(t=T.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?n.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&n.conversationList.push({ToGroupid:s,Type:2}))}),0!==n.conversationList.length){var s=yield function(r,n){return I(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return n.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(n,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{T.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&T.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=T.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(T.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&T.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)}},ri=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return I(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),T.hasLocalConversation(e))return null!=(e=T.getLocalConversation(e))&&e.setDraftText(t),T.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:wn.CONV_NOT_FOUND})})}},ni=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return I(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,r){return I(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:{Peer_Account:e,Mute_Notifications:t}})})}({userIDList:a,receiveMessageOption:e},this._core),{ErrorList:s=[]}=t||{},r=[],n=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),i=[],o=this._core["OuterConstant"];return a.forEach(e=>{i.push(""+o.CONV_C2C+e),n.push({userID:e})}),T.patchMessageRemindType(i,l),{code:0,data:{successUserIDList:n,failureUserIDList:r}}})}},ii=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,n){return I(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,n){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:n},this._core),!t(r)){let e=""+s.CONV_GROUP+r;T.patchMessageRemindType([e],n)}return{code:0,data:{groupID:r,messageRemindType:n}}})}},oi=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 n=e["MuteNotificationsSync"];if(!t(n)){let{To_Account:e,MuteNotifications:t}=n,s=e.map(e=>""+i.CONV_C2C+e),r=Wn(t);console.log(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),T.patchMessageRemindType(s,r)}})}setMessageRemindType(o){return I(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=o,{helper:n,utils:{isUndefined:i}}=this._core;try{if(!i(e))return console.log(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield ii.set(e,r);if(i(t))throw new n.ChatError({functionName:s,message:"userIDList or groupID is required"});return console.log(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield ni.set(t,r)}catch(e){let t=new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},ai=new class{init(e){console.log("ConversationAction.init"),this._core=e,zn.init(e),Xn.init(e),Zn.init(e),ei.init(e),ti.init(e),si.init(e),ri.init(e),oi.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];si.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];ti.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];ti.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;ei.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;oi.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;ei.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},li=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return I(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=o,{startTime:r=0,endTime:n=0}=this._calcStartAndEndTime(o),i=yield function(i){return I(this,void 0,void 0,function*(){var e=O.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:n}=i;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:n}})})}({messageRemindType:this._getType(t),startTime:r,endTime:n,isRepeated:s?Gn.ON:Gn.OFF});return{code:0,data:{errorCode:i.ErrorCode,errorInfo:i.ErrorInfo}}}catch(e){$n("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:n=!0}=e,i=new Date,i=new Date(i.getFullYear(),i.getMonth(),i.getDate(),e,t,s),e=Math.round(i.getTime()/1e3);let o=n&&86400<=r?e+86400:e+r;return{startTime:e,endTime:o}}_getType(e){var t=this._core["OuterConstant"];return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}},ui=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 I(this,void 0,void 0,function*(){try{var e=yield function(){return I(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){$n("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:n,EndTime:i,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:n,endTime:i,isRepeated:o===Gn.ON}}},ci=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,ni.init(e),ii.init(e),Jn.init(e),Qn.init(e),li.init(e),ui.init(e)}};let di=e=>!Bn(e)&&!jn(e)&&!Kn(e),hi={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!di(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!di(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!di(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{var{utils:{isArray:t,isObject:s,isString:r}}=O["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&di(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(di(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=>!(!Bn(e)&&!jn(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}}},gi={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0},pi=new class{install(e){O.init(e),ai.init(e),ci.init(e),T.init(e),e.helper.registerValidateConfig({auth:gi,params:hi})}},_i=new class{init(e){this.core=e}},mi="AVChatRoom",vi="GRP_COUNTER",fi=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Si=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ii=["Role","JoinTime","MsgFlag","MsgSeq"],Ei=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Ci="notStart",Mi="resolved",yi="rejected",Oi=["Owner","Admin","Member"],Ti=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Ai={from:!0,groupID:!0,groupName:!0,to:!0},Ri={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Di=e=>e===_i.core.OuterConstant.GRP_PUBLIC,bi=e=>e===_i.core.OuterConstant.GRP_AVCHATROOM,Li=(r,e)=>{var t=_i.core.utils["isArray"];if(!t(r)||!t(e))return!1;let n=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,n=!0):(r.push({key:t,value:e}),n=!0)}),n},Ni=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:n,Value:i}=s[e];r.push({key:n,value:i})}return r},Gi=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:n,value:i}=s[e];r.push({Key:n,Value:i})}return r};function Pi(e,t){var s=_i.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:3122,replacement1:e})}function wi(e,t){var s=_i.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 Ui=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class ki{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}=_i.core["utils"];for(t in e)Ui.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:n},common:{deepMerge:i}}=_i.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),n(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&Li(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),i(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&i(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:n,excludedUnreadSequenceList:i}=e,o=_i.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:n,excludedUnreadSequenceList:i},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var A=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 ki(e))});var r=t();for(let[,e]of this._groupMap)e.selfInfo.userID=r,"Owner"===e.selfInfo.role&&(e.ownerID=r)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){let{GRP_ROOM:t,GRP_LIVE:s}=this._core["OuterConstant"];return[...this._groupMap.values()].filter(e=>{e=e.type;return e!==t&&e!==s})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){var e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(t){let{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:e}}=this._core,r=""+e+t;if(s.getConversation(r)){let e=this.getLocalGroup(t);s.updateConversation(r,{groupProfile:e})}}reset(){this.clearLocalGroup()}};function Fi(o,a){return I(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:n,responseFilter:i}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:n,ResponseFilter:i,SupportTopic:r,NeedAppDefineData:1}})})}function R(e){return{code:0,data:e||{}}}var qi=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Ci,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 I(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}),A.updateLocalGroup(e),A.getLocalGroupList()}return console.log(this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===yi||this._pagingStatus===Ci?this._syncGroupList().then(()=>{var e=A.getLocalGroupList();return R({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw console.error(this._name+".getGroupList fail:",e),e}):(e=A.getLocalGroupList(),console.log(this._name+".getGroupList return group count:"+e.length),R({groupList:e,isSyncCompleted:this._isSyncCompleted()}))})}_syncGroupList(){return I(this,void 0,void 0,function*(){this._pagingStatus===Ci&&A.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Mi,this._groupListTreeShaking(t),A.updateLocalGroup(t);var s=A.getLocalGroupList();return console.log(this._name+"._syncGroupList ok, count:"+s.length),A.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=yi,console.error(this._name+"._syncGroupList fail:",e),e}})}_pagingGetGroupList(e){return I(this,void 0,void 0,function*(){var{isCommunityRelay:n=!1,groupList:i}=e;let o,{limit:a,offset:l}=e;var u=[...fi];n&&(o=this._core.OuterConstant.GRP_COMMUNITY,u.push("AtInfoList"));try{let e=yield Fi({type:o,limit:a,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:u,SelfInfoFilter:[...Ii]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);i.push(...r);var c=l+a,d=!(c<s),h=`offset:${l} limit:${a} total:${s} isCompleted:${d} current:${i.length} isCommunityRelay:`+n;return console.log(this._name+"._pagingGetGroupList ok. "+h),n?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:n,limit:50,offset:l,groupList:i});if(n)return 11e3===e.code&&console.log(this._name+"._pagingGetGroupList ok. community unavailable"),i;throw e}})}_pagingGetJoinedCommunityList(e){return I(this,void 0,void 0,function*(){var{common:{getCurrentUserID:n},OuterConstant:i}=this._core,o=e["groupList"];let{limit:a,offset:l}=e;try{let e=yield Fi({limit:a,offset:l,type:i.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...fi],SelfInfoFilter:[...Ii]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);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 r=new Map([...A.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var n=[...r.keys()];for(let e=0,t=n.length;e<t;e++)A.deleteLocalGroup(n[e])}_isSyncCompleted(){return this._pagingStatus===Mi}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:n,ApplyJoinOption:i,CreateTime:o,FaceUrl:a,GroupId:l,Introduction:u,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:h,MemberNum:g,MaxMemberNum:p,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:S,Type:I,LastRecallTime:E,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],n=Ni(n),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);r.push({groupCustomField:n,joinOption:i,createTime:o,avatar:a,groupID:l,introduction:u,inviteOption:c,lastInfoTime:d,lastMsgTime:h,memberCount:g,maxMemberCount:p,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:S,type:I,selfInfo:C,_lastRevokedTime:E,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:n}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:n}}_convertAtInfoList(r,e){if(0===e.length)return[];let n=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:r,groupAtType:e,sequence:t,from:s})}),n}},xi=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(l){return I(this,void 0,void 0,function*(){var i;this._preCheckParams(l);let{ssoLog:e,helper:{ChatError:r}}=this._core,o=e.createSSOLogData({method:"createGroup"});try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(g,p){return I(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:n,avatar:i,maxMemberNum:o,joinOption:a,inviteOption:l,memberList:u,groupCustomField:c,isSupportTopic:d}=g;let h;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:n,FaceUrl:i,MaxMemberCount:o,ApplyJoinOption:a,InviteJoinOption:l,MemberList:h=u?u.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?Gi(t):void 0}}):h,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return p.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},l),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:n=[]}=s||{};o.setLogInfo({message:"groupID:"+r}).end(),console.log(`${this._name}.createGroup ok, type:${l.type} groupID:${r} overLimitUserIDList:`+n),e(l.memberList)||e(n)||(l.memberList=null==(i=l.memberList)?void 0:i.filter(e=>n.includes(e.userID))),A.updateLocalGroup([Object.assign(Object.assign({},l),{groupID:r})]);var a=A.getLocalGroup(r);return this._notNeedSendCustomMessage(l)||(this._sendCustomMessage(r,l.type),A.emitGroupListUpdate()),R({group:a})}catch(i){let{errorCode:e,errorInfo:t}=i,s=new r({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:r,isUndefined:n},common:{isCommunity:i}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:n}=_i.core.OuterConstant;return[e,t,s,r,n]})().includes(t))throw new this._core.helper.ChatError({code:2600});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:2602});n(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||n(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||n(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:2602});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!bi(e)}_canIUseJoinOption(e){return Di(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",n=0;t===s.GRP_COMMUNITY&&(r="Create Community",n=1);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:n,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},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:r}=t,n=(console.log(this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];n(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),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:r,groupAttributeList:n,operation:i}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];5!==i&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:i})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),console.log(this._name+`.refreshGroupAttributesCache. operation:${i} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;3!==s?4!==s?(1===s&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:n=[]}=e,i={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===n.length)for(let e of t.keys())i[e]=(null==(s=t.get(e))?void 0:s.value)||"";else n.forEach(e=>{t.has(e)&&(i[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return i}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:n}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+n.length),0===r.length&&0===n.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:n}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],n=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&n.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:n}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},Vi=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mi)})}dismissGroup(t){return I(this,void 0,void 0,function*(){console.log(this._name+".dismissGroup groupID:"+t);let{ssoLog:e,helper:{ChatError:n}}=this._core,i=e.createSSOLogData({method:"dismissGroup"});i.setLogInfo({message:"groupID:"+t});try{yield function(e,t){return I(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=A.getLocalGroup(t)["type"];return A.deleteLocalGroup(t),A.emitGroupListUpdate(),D.deleteGroupAttributesCache(t),R({groupID:t,type:e})}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"dismissGroup",code:t,message:s});throw i.setError(r).end(),console.error(this._name+".dismissGroup fail:",r),r}})}},Bi=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return I(this,void 0,void 0,function*(){let{groupID:n,groupCustomFieldFilter:e}=s,i={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...fi],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...Ei]}},{ssoLog:t,helper:{ChatError:o}}=this._core,a=t.createSSOLogData({method:"getGroupProfile"});a.setLogInfo({message:"groupID:"+n});try{let e=yield this.getGroupProfileAdvance(i),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!A.hasLocalGroup(n)&&bi(t[0].type)?new ki(t[0]):(A.updateLocalGroup(t),A.getLocalGroup(n))).isSupportTopic||A.updateConversationGroupProfile(n),a.end(),console.log(this._name+".getGroupProfile ok."),R({group:r})}catch(e){let{code:t,message:s}=e,r=new o({functionName:"getGroupProfile",code:t,message:s});throw a.setError(r).end(),console.error(this._name+".getGroupProfile fail:",r),e}})}getGroupProfileAdvance(a){return I(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),r=e.filter(e=>t({groupID:e})),n=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),i=[],o=[];return n.forEach(e=>{i.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:i,failureGroupList:o}})}_getGroupProfileAdvance(e){return I(this,void 0,void 0,function*(){let{isCommunityProfile:t=!1}=e,o=S(e,["isCommunityProfile"]);if(0===o.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(o,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),{isUndefined:r}=this._core["utils"],n=s.filter(e=>r(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:n,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:n,ApplyJoinOption:i,CreateTime:o,FaceUrl:a,GroupId:l,InfoSeq:u,Introduction:c,InviteJoinOption:d,LastInfoTime:h,LastMsgTime:g,MaxMemberNum:p,MemberNum:_,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:S,Owner_Account:I,ShutUpAllMember:E,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:O,ErrorInfo:T}=s[e],n=Ni(n),y=this._convertMembers(y);r.push({groupCustomField:n,joinOption:i,createTime:o,avatar:a,groupID:l,infoSequence:u,introduction:c,inviteOption:d,lastInfoTime:h,lastMsgTime:g,maxMemberCount:p,memberCount:_,muteAllMembers:m,name:v,nextMessageSeq:f,notification:S,ownerID:I,shutUpAllMember:E,muteUntil:C,type:M,members:y,errorCode:O,errorInfo:T})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:i,Member_Account:o,MsgFlag:a,MsgSeq:l,NameCard:u,Role:c}=s[e],n=Ni(n);r.push({memberCustomField:n,joinTime:i,userID:o,messageRemindType:a,sequence:l,nameCard:u,role:c})}return r}},ji=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){var{groupID:r,counterList:n=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<i&&i<t||(n.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:i,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:t,avChatRoomKey:e})}}setGroupCounters(t,n){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(n).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},Ki=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mi)})}joinGroup(o){return I(this,void 0,void 0,function*(){let t=o["groupID"],{ssoLog:s,ChatError:n,OuterConstant:r}=this._core,i=s.createSSOLogData({method:"joinGroup"});try{if(A.hasLocalGroup(t))try{return yield Bi.getGroupProfile({groupID:t}),i.setLogInfo({message:`groupID:${t} joinedStatus:`+r.JOIN_STATUS_ALREADY_IN_GROUP}).end(),R({status:r.JOIN_STATUS_ALREADY_IN_GROUP})}catch(s){console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),A.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,r=new n({functionName:"joinGroup",code:t,message:s});throw i.setError(r).end(),console.error(this._name+".joinGroup fail:",e),e}})}_applyJoinGroup(c){return I(this,void 0,void 0,function*(){var{OuterConstant:t,helper:e}=this._core,s=c["groupID"],r=Object.assign({},c),e=e.checkBusinessCapabilityBits("AV_HISTORY_MSG"),r=(e&&(r.historyMessageFlag=1),yield function(r,n){return I(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(r,this._core)),{Type:r,JoinedStatus:n,LongPollingKey:i,StartSeq:o,HugeGroupFlag:a,AVChatRoomKey:l,RspMsgList:u=[]}=r||{},e=`groupID:${s} joinedStatus:${n} longPollingKey:${i} startSeq:${o} avChatRoomFlag:${a} canGetAVChatRoomHistoryMsg:${e}, historyMessageCount:`+u.length;if(console.log(this._name+"._applyJoinGroup ok, "+e),n===t.JOIN_STATUS_WAIT_APPROVAL)return R({status:t.JOIN_STATUS_WAIT_APPROVAL,group:{groupID:s,type:r}});if(n!==t.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:2660});{let e=null;try{e=(yield Bi.getGroupProfile({groupID:s})).data.group}catch(t){e=new ki({groupID:s}),console.warn(this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${s}, errorCode:`,null==t?void 0:t.code)}return this._handleJoinResult({group:e,avChatRoomFlag:a,longPollingKey:i,startSequence:o,avChatRoomKey:l,historyMessageList:u})}})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(D.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),ji.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),R(e)):(A.updateLocalGroup([t]),A.emitGroupListUpdate(),R({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}},Hi=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mi)})}quitGroup(t){return I(this,void 0,void 0,function*(){if(!A.hasLocalGroup(t))throw new this._core.helper.ChatError({code:2623});let{ssoLog:e,helper:{ChatError:n}}=this._core,i=e.createSSOLogData({method:"quitGroup"});i.setLogInfo({message:"groupID:"+t});try{yield function(e,t){return I(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=A.getLocalGroup(t)["type"];return A.deleteLocalGroup(t),A.emitGroupListUpdate(),D.deleteGroupAttributesCache(t),R({groupID:t,type:e})}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"quitGroup",code:t,message:s});throw i.setError(r).end(),console.error(this._name+".quitGroup fail:",r),r}})}},Wi=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return I(this,void 0,void 0,function*(){console.log(this._name+".searchGroupByID groupID:"+v);try{var e=yield function(t,s){return I(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...Si]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:t=[]}=e||{},{AppDefinedData:s=[],ApplyJoinOption:r,CreateTime:n,FaceUrl:i,Introduction:o,InviteJoinOption:a,MaxMemberNum:l,MemberNum:u,Name:c,Owner_Account:d,Type:h,ErrorCode:g,ErrorInfo:p}=t[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:p});console.log(this._name+".searchGroupByID ok.");var _=Ni(s),m=new ki({groupID:v,name:c,avatar:i,introduction:o,joinOption:r,inviteOption:a,maxMemberCount:l,memberCount:u,type:h,ownerID:d,createTime:n,groupCustomField:_});return R({group:m})}catch(e){throw console.error(this._name+".searchGroupByID fail:",e),e}})}},$i=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(n){return I(this,void 0,void 0,function*(){let t=n["groupID"],{isUndefined:s}=this._core["utils"],r=A.getLocalGroup(t);if(r){let e=r["type"];this._canIUseJoinOption(e)||s(n.joinOption)||(console.warn(this._name+".updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom"),n.joinOption=void 0)}s(n.muteAllMembers)||(n.muteAllMembers=!0===n.muteAllMembers?"On":"Off");try{return yield function(u,c){return I(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:n,muteAllMembers:i,joinOption:o,inviteOption:a,groupCustomField:l}=u,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:n,ShutUpAllMember:i,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:l?Gi(l):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(n,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),r?(r.updateGroup(n),A.emitGroupListUpdate()):r=new ki(n),R({group:r})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}})}_canIUseJoinOption(e){return Di(e)||this._core.common.isCommunity({type:e})}},Yi=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(a){return I(this,void 0,void 0,function*(){let s="changeGroupOwner",{groupID:e,newOwnerID:t}=a,r=A.getLocalGroup(e),{helper:n,OuterConstant:i,common:{getCurrentUserID:o}}=this._core;if((null==r?void 0:r.type)===i.GRP_AVCHATROOM)throw new n.ChatError({functionName:s,code:2620});if(t===o())throw new n.ChatError({functionName:s,code:2621});console.log(`${this._name}.${s} groupID:${e} newOwnerID:`+t);try{return yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(a,this._core),console.log(this._name+`.${s} ok.`),r.ownerID=t,A.emitGroupListUpdate(),R({group:r})}catch(e){let t=new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},zi=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(mi)})}getGroupOnlineMemberCount(n){return I(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount",e=A.hasLocalGroup(n);if(console.log(`${this._name}.${s} groupID:${n} hasLocalGroup:`+e),!e)return R({memberCount:0});let r=Date.now();if(this._onlineMemberCountMap.has(n)){let e=this._onlineMemberCountMap.get(n),{lastReqTime:t=0,memberCount:s=0}=e||{};if(r-t<=6e4)return R({memberCount:s})}try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0}=e||{};return this._onlineMemberCountMap.set(n,{lastReqTime:Date.now(),memberCount:t}),console.log(`${this._name}.${s} ok. groupID:${n} 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}})}},Ji=new class{init(e,t){console.log("GroupAction.init"),qi.init(e),xi.init(e),Vi.init(e,t),Ki.init(e,t),Hi.init(e,t),Wi.init(e),Bi.init(e),$i.init(e),Yi.init(e),zi.init(e,t)}dismissGroup(e){return Vi.dismissGroup(e)}joinGroup(e){return Ki.joinGroup(e)}quitGroup(e){return Hi.quitGroup(e)}getGroupOnlineMemberCount(e){return zi.getGroupOnlineMemberCount(e)}},Qi=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return I(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 I(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=i||{},r=this._core["common"];let n;try{n=yield function(n,i){return I(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;n={}}var{NextStartTime:e=0,PendencyList:t=[]}=n||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},i),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=S(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:n,From_Account:i,GroupId:o,GroupName:a,PendencyType:l,To_Account:u}=e;return{handled:e,messageKey:t,applicant:i,applicantNick:n,groupID:o,groupName:a,authentication:r,applicationType:l,userID:u,note:s}}},Xi=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return I(this,void 0,void 0,function*(){let s="handleGroupApplication",t=e["application"],r=this._handleParams(e);try{2===(null==t?void 0:t.applicationType)?yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:n,invitee:i}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:n,Invited_Account:i}})})}(r,this._core):yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:n,messageKey:i}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:n,MsgKey:i}})})}(r,this._core),console.log(this._name+`.${s} ok.`);let e=A.getLocalGroup(r.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:r}=e;let n,i,o,a,l;if(s){let e=(s||{})["payload"];n=e.operatorID,i=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else n=(null==r?void 0:r.applicant)||"",i=(null==r?void 0:r.groupID)||"",o=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return 2===(null==r?void 0:r.applicationType)&&(l=r.userID),{handleAction:e,handleMessage:t,applicant:n,invitee:l,groupID:i,authentication:o,messageKey:a}}},Zi=new class{init(e){console.log("GroupApplication.init"),Qi.init(e),Xi.init(e)}};let eo=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}}=_i["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&&Li(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function to(a,l){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:n,memberCustomField:i}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:n,AppMemberDefinedData:o=i?Gi(i):o};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var so=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mi)})}getGroupMemberList(r){return I(this,void 0,void 0,function*(){let i="getGroupMemberList",{groupID:o,offset:a=0,count:e=100,role:t="",filter:s=""}=r;console.log(`${this._name}.${i} groupID:${o} offset:${a} count:${e} role:${t} filter:`+s);var l=A.getLocalGroup(o),u=100<e?100:e,c={groupID:o,offset:a,limit:u,memberRoleFilter:Oi.includes(t)?[t]:void 0,memberInfoFilter:Ti};try{let e=yield function(i,o){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:r,memberInfoFilter:n}=i;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:r,MemberInfoFilter:n}})})}(c,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{};console.log(`${this._name}.${i} ok, totalMemberCount:${s} next:`+r);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 n=a+u;g({groupID:o})&&(n=h(r)?0:r),t.length<u&&(n=0);var p=this._convertMemberInfo(t),p=yield this._patchAvatarAndNick(p),_=this._generateGroupMember(p);return R({memberList:_,offset:n})}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 r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:i,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u}=s[e],n=Ni(n);r.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:n})}return r}_patchAvatarAndNick(i){return I(this,void 0,void 0,function*(){let e,t=i.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],n=new Map(r.map(e=>[e.userID,e]));return i.forEach(e=>{var t,s;n.has(e.userID)&&({nick:t="",avatar:s=""}=n.get(e.userID),e.nick=t,e.avatar=s)}),i})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var n=new eo(s[e]);r.push(n)}return r}},ro=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(t){return I(this,void 0,void 0,function*(){let s="getGroupMemberProfile",{groupID:r,userIDList:n,memberCustomFieldFilter:i}=t,e=A.getLocalGroup(r),{helper:o,utils:{isArray:a}}=this._core;if(e&&bi(e.type))throw new o.ChatError({functionName:s,replacement1:s,code:2687});50<n.length&&(console.warn(`${this._name}.${s} userIDList length:${n.length} exceeds limit 50`),n.splice(50));try{let e=yield function(n,i){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:n,memberCustomFieldFilter:i,memberInfoFilter:[...Ti]},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 r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:i,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u}=s[e],n=Ni(n);r.push({userID:o,joinTime:i,onlineStatus:a,role:l,muteUntil:u,memberCustomField:n})}return r}_getMemberAvatarAndNick(i){return I(this,void 0,void 0,function*(){let e,t=i.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],n=new Map(r.map(e=>[e.userID,e]));return i.forEach(e=>{var t,s;n.has(e.userID)&&({nick:t="",avatar:s=""}=n.get(e.userID),e.nick=t,e.avatar=s)}),i})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var n=new eo(s[e]);r.push(n)}return r}},no=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(t){return I(this,void 0,void 0,function*(){let o="addGroupMember",{groupID:a,userIDList:e}=t,l=A.getLocalGroup(a),s=this._core["helper"];if(l&&bi(l.type))throw new s.ChatError({functionName:o,code:2661});var u=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:a,userIDList:u},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:i}=this._handleResult(t);return console.log(`${this._name}.${o} groupID:${a} ok, successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${n} overLimitUserIDList:`+i),R({failureUserIDList:s,successUserIDList:r,existedUserIDList:n,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=[],r=[],n=[],i=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;0===e?s.push(t):1===e?r.push(t):2===e?n.push(t):4===e&&i.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:i}}},io=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mi)})}deleteGroupMember(o){return I(this,void 0,void 0,function*(){let s="deleteGroupMember",{groupID:e,userIDList:t}=o,r=A.getLocalGroup(e),{helper:n,utils:{isUndefined:i}}=this._core;if(i(r))throw new n.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(r,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:t},this._core),console.log(`${this._name}.${s} ok, groupID:${e} userIDList length:`+t.length),R({group:r,userIDList:t})}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}})}},oo=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return I(this,void 0,void 0,function*(){let r="setGroupMemberMuteTime",t=this._core["helper"];this._preCheckSettingMuteParams(o);try{yield to(o,this._core);let{groupID:e,userID:t,muteTime:s}=o;console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} muteTime:`+s);var n=A.getLocalGroup(e),i=new eo({userID:t,muteTime:s});return R({group:n,member:i})}catch(e){n=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:`,n),n}})}_preCheckSettingMuteParams(e){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:2685})}},ao=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(o){return I(this,void 0,void 0,function*(){let r="setGroupMemberRole",t=this._core["helper"];this._preCheckSettingRoleParams(o);try{yield to(o,this._core);let{groupID:e,userID:t,role:s}=o;console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} role:`+s);var n=A.getLocalGroup(e),i=new eo({userID:t,role:s});return R({group:n,member:i})}catch(e){n=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:`,n),n}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:n,OuterConstant:i,common:{isCommunity:o}}=this._core,a=A.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==i.GRP_MBR_ROLE_OWNER)throw new n.ChatError({functionName:"setGroupMemberRole",code:2681});if(t===r.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberRole",code:2684});a=[...Oi];if(o({groupID:e})&&a.push(i.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new n.ChatError({functionName:"setGroupMemberRole",code:2683})}},lo=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(l){return I(this,void 0,void 0,function*(){let n="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:i}}=this._core;this._preCheckSettingNameCardParams(l);try{let{groupID:e,userID:t=i(),nameCard:s}=l,r={groupID:e,userID:t,nameCard:s};yield to(r,this._core),console.log(`${this._name}.${n} ok, groupID:${e} userID:${t} nameCard:`+s);var o=A.getLocalGroup(e),a=new eo({userID:t,nameCard:s});return R({group:o,member:a})}catch(e){let t=new s.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}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=A.getLocalGroup(e);if(bi(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:2687})}},uo=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(l){return I(this,void 0,void 0,function*(){let n="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:i}}=this._core;this._preCheckSettingCustomFiledParams(l);try{let{groupID:e,userID:t=i(),memberCustomField:s}=l,r={groupID:e,userID:t,memberCustomField:s};yield to(r,this._core),console.log(`${this._name}.${n} ok, groupID:${e} userID:${t} memberCustomField:`+JSON.stringify(s));var o=A.getLocalGroup(e),a=new eo({userID:t,memberCustomField:s});return R({group:o,member:a})}catch(e){let t=new s.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}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=A.getLocalGroup(e);if(bi(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:2687})}},co=new class{init(e,t){console.log("GroupMember.init"),so.init(e,t),ro.init(e),no.init(e),io.init(e,t),oo.init(e),ao.init(e),lo.init(e),uo.init(e)}getGroupMemberList(e){return so.getGroupMemberList(e)}deleteGroupMember(e){return io.deleteGroupMember(e)}},ho=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return I(this,void 0,void 0,function*(){var t="getGroupCounters";try{Pi(t,vi);var e,s,r,{groupID:n,keyList:i=[]}=l,{avChatRoomKey:o,lastUpdateTime:a}=ji.getLocalGroupCounters(n);return Date.now()-a>=this._getExpireTime()&&(e=yield function(n){return I(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=n,r=_i.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:n,keyList:i,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:r}=e,ji.updateLocalGroupCounters({groupID:n,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:ji.getLocalCounters(n,i)}}}catch(e){wi(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)}},go=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 I(this,void 0,void 0,function*(){return this._handleCounterOperation("Set",e)})}increaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Increase",e)})}decreaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Decrease",e)})}_handleCounterOperation(a,l){return I(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{Pi(t,vi);var{groupID:e,key:s,value:r=0}=l,n=ji.getLocalGroupCounters(e)["avChatRoomKey"],i="Set"===a?this._convertObjectToList(l.counters):[{Key:s,Value:r}],o=yield this._updateGroupCounters({groupID:e,counterList:i,avChatRoomKey:n,mode:a});return ji.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){wi(t,e)}})}_updateGroupCounters(i){return I(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=i,n=_i.core["common"];return n.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},po=new class{init(e){this._core=e,ho.init(e),go.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;0!==e&&2!==e||this._processAndNotifyCounterUpdate(r,t,s),1===e&&ji.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:n}=this._core;ji.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{n.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){ji.reset()}},_o=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return I(this,void 0,void 0,function*(){let r="initGroupAttributes",{groupID:n,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a}=D.getGroupAttributesCache(n),l=D.convertKeyValueMapToList(i);try{let e=yield function(n,i){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${r} ok. groupID:${n} serverMainSequence:`+t);var u=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:i[e],sequence:t}});return D.saveGroupAttributesCacheValuesCopy(n),D.refreshGroupAttributesCache({groupID:n,serverMainSequence:t,groupAttributeList:u,operation:1}),D.emitGroupAttributesUpdated(n),R({groupAttributes:i})}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}})}},mo=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return I(this,void 0,void 0,function*(){let r="setGroupAttributes",{groupID:n,groupAttributes:i}=e,{serverMainSequence:o,avChatRoomKey:a,values:l}=D.getGroupAttributesCache(n),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(n,i){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:a,groupAttributeList:u,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${r} ok. groupID:${n} serverMainSequence:`+t);var c=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:i[e],sequence:t}});return D.saveGroupAttributesCacheValuesCopy(n),D.refreshGroupAttributesCache({groupID:n,serverMainSequence:t,groupAttributeList:c,operation:2}),D.emitGroupAttributesUpdated(n),R({groupAttributes:i})}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}})}},vo=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(a){return I(this,void 0,void 0,function*(){let s="deleteGroupAttributes",{groupID:e,keyList:t=[]}=a;try{var{resultList:r,serverMainSequence:n,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:n,groupAttributeList:o,operation:i}),D.emitGroupAttributesUpdated(e),R({keyList:r})}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 I(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=D.getGroupAttributesCache(o),r=[],n=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},n.push({key:e,seq:t}),r.push(e))});var i=((yield function(n,i){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:n,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:i,groupAttributeList:n,operation:4}})}_clearGroupAttributes(r){return I(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=D.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:3}})}},fo=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(c){return I(this,void 0,void 0,function*(){let r="getGroupAttributes",n=c["groupID"],{avChatRoomKey:i,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=D.getGroupAttributesCache(n),{ssoLog:o,helper:{ChatError:a}}=this._core,l=o.createSSOLogData({method:"getGroupAttributes"});if(l.setLogInfo({message:`groupID:${n} localMainSequence:${t} serverMainSequence:${s} keyList:`+c.keyList}),3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:n,avChatRoomKey:i}),t=D.getGroupAttributesCacheValues(c),{serverGroupAttributeList:s=[]}=e||{};return l.setLogInfo({moreMessage:"from server, count:"+s.length}).end(),console.log(this._name+`.${r} from server. groupID:`+n),R({groupAttributes:t})}catch(e){let t=new a({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw l.setError(t).end(),console.error(this._name+`.${r} fail:`,t),t}var u=D.getGroupAttributesCacheValues(c);return l.setLogInfo({moreMessage:"from cache."}).end(),console.log(this._name+`.${r} from cache. groupID:`+n),R({groupAttributes:u})})}getGroupAttributesFromServer(n){return I(this,void 0,void 0,function*(){var e=this._core["utils"]["isUndefined"],{groupID:t,avChatRoomKey:s}=n,{AttrMainSeq:e=0,GroupAttrAry:s}=(yield function(r,n){return I(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:t,avChatRoomKey:s,groupType:e(s)?0:1},this._core))||{},r=(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:r,operation:5}),{serverGroupAttributeList:s}})}},So=new class{init(e){console.log("GroupAttribute.init"),_o.init(e),mo.init(e),vo.init(e),fo.init(e),D.init(e)}isGroupAttributesUpdated(e){return D.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:n,withChangedAttributeInfo:i}=r,o=D.getGroupAttributesCache(t)["localMainSequence"],a=n-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"];fo.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{D.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else D.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){D.reset()}};function Io(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:n,MsgPriority:i,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,TinyId:u,ToGroupId:c,GroupInfo:d,MsgBody:h}=e,g=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:n,From_Account:i,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:n,from:i,to:o}}();return{clientSequence:s,from:r,clientTime:n,priority:i,random:o,sequence:a,time:l,tinyID:u,to:c,groupProfile:g,elements:("tips"===t?Eo:Mo)(h)}}function Eo(r){let e={};return Object.keys(r).forEach(s=>{switch(s){case"MemberNum":e.memberCount=r[s];break;case"OpType":e.operationType=r[s];break;case"Operator_Account":e.operatorID=r[s];break;case"List_Account":e.userIDList=r[s];break;case"MsgMemberExtraInfo":e.memberInfoList=r[s].map(e=>Co(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=Co(r[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:r,GroupAttrInfo:n}=o[i];return{changedKeyList:e,groupAttributeList:n.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":e.msgMemberInfo=r[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}=r[s];return{expireTime:e,onlineMemberNum:t}}();break;case"GroupCounterInfo":e.groupCounterInfo=r[s].map(e=>{var{GroupCounterSeq:e,GroupCounter:t,Type:s}=e;return{type:s,groupCounterSeq:e,counterList:t}})}}),e}function Co(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function Mo(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 yo{constructor(e){this.type=_i.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=Eo(e);return new yo(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"groupProfile":this._initGroupProfile(t[e]);break;case"operatorInfo":this._initOperatorInfo(t[e]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(t[e]);break;case"newGroupProfile":this._initNewGroupProfile(t[e]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[e]=t[e]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];Ai[r]&&(this.content.groupProfile[r]=t[r])}}_initOperatorInfo(t){this.content.operatorInfo={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];this.content.operatorInfo[r]=t[r]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach(t=>{e.forEach(e=>{t.userID===e.userID&&Object.assign(t,e)})}):this.content.memberList=e}_initNewGroupProfile(t){this.content.newGroupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];"muteAllMembers"!==r?this.content.newGroupProfile[r]=t[r]:this.content.newGroupProfile.muteAllMembers=1===t.muteAllMembers}}}var Oo=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:n}=e;null!=e&&e.registerElementClass(n.MSG_GRP_TIP,yo),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this)}onNewGroupTips(e){let{messageList:t,conversationUpdateFieldList:s}=this._handleGroupTips(e),{notificationCenter:r,OuterEvent:n,appStore:i}=this._core;null!=s&&s.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e;i.conversationStore.updateConversation(e,{lastMessage:t,unreadCount:s})}),0<t.length&&(r.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:t}),this._handleGroupTipMessage(t))}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:n}=e,i=new Map,t=[],o=[];for(let t=0,e=n.length;t<e;t++){let e=Io(n[t],"tips");if(6===r){if(So.isGroupAttributesUpdated(e)){So.handleGroupAttributesUpdated(e);continue}if(po.isGroupCounterUpdated(e)){po.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(A.hasLocalGroup(a)){a=this._assembleMessage(e);if(6===r&&(a._onlineOnlyFlag=!0,o.push(a)),4===r){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 yo(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:n,memberInfoList:i,operatorInfo:o}=e,a={};if(t(i)?t(o)||(a=o):n!==r.JOINED&&n!==r.KICKED&&n!==r.ADMIN_SET&&n!==r.ADMIN_CANCELED||(a=Object.assign({},i[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:n,conversationType:i}=t;let o;if(e.has(n))o=e.get(n),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=i,o.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:n,unreadCount:e,type:i,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(n,o)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:n}=e.payload,i=r.groupID,o=A.getLocalGroup(i);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(i,s);break;case"groupName":o.name=s[e];break;default:o[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(n)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==n.userID||Object.keys(n).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:n[e]}),"role"===e&&this._updateSelfRole(o,n[e])}),A.emitGroupListUpdate(),A.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=A.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;400===t?r=s.GRP_MBR_ROLE_OWNER:300===t&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=A.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,A.emitGroupListUpdate(),A.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 To{constructor(e){this.type=_i.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=Mo(e);return new To(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"remarkInfo":this.content.handleMessage=t[e];break;case"groupProfile":this._initGroupProfile(t[e]);break;case"memberInfoList":break;default:this.content[e]=t[e]}})}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];Ri[r]&&(this.content.groupProfile[r]=t[r])}}}var Ao=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,To)}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:r,OuterEvent:n}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let n={};for(let e=0;e<t.length;e++){var i=Io(t[e],"system"),o=i["elements"]["operationType"];15!==o&&(o=this._assembleMessage(i),this._core.message.messageDataHandler.storeConversationMessage(o))&&(r.push(o),n=this._handleConversationOptions(o,s))}return n.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[n]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new To(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})),e=(s.setElement(t),s.isSystemMessage=!0,1===s.sequence&&1===s.random),t=2===s.sequence&&2===s.random;return(e||t)&&(s.sequence=r(),s.random=r(),s.generateMessageID()),s}_handleConversationOptions(e,t){var s=this._core["OuterConstant"],s={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&s.unreadCount++,s}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{var t=e.payload["operationType"];switch(t){case 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,r=A.hasLocalGroup(t);console.log(this._name+`._handleGroupJoinResult groupID:${t} type:${s} hasLocalGroup:`+r),r||bi(s)||(A.updateLocalGroup([Object.assign({},e)]),A.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];A.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];A.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],t=e["groupID"],s=A.hasLocalGroup(t);console.log(this._name+`._handleGroupInvitedResult groupID:${t} hasLocalGroup:`+s),s||(A.updateLocalGroup([Object.assign({},e)]),A.emitGroupListUpdate())}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=A.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(bi(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}A.deleteLocalGroup(s),A.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},Ro=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),Oo.init(e),Ao.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){Oo.onNewGroupTips(e)}_onNewGroupSystemNotification(e){Ao.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 b={required:!0,rules:["string"],allowEmpty:!1},Do={required:!0,rules:["number"],allowEmpty:!1},bo={required:!0,rules:["array"],allowEmpty:!1},Lo={required:!0,rules:["object"],allowEmpty:!1},No={createGroup:{name:b,type:b},dismissGroup:[Object.assign({key:"groupID"},b)],joinGroup:{groupID:b,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},b)],searchGroupByID:[Object.assign({key:"groupID"},b)],getGroupProfile:{groupID:b,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:b,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:b,newOwnerID:b},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},b)],handleGroupApplication:{handleAction:b},getGroupMemberList:{groupID:b},getGroupMemberProfile:{groupID:b,userIDList:bo,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:b,userIDList:bo},deleteGroupMember:{groupID:b,userIDList:bo},setGroupMemberMuteTime:{groupID:b,userID:b,muteTime:Object.assign(Object.assign({},Do),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:b,userID:b,role:b},setGroupMemberNameCard:{groupID:b,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:b},setGroupMemberCustomField:{groupID:b,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:bo},markGroupMemberList:{groupID:b,markType:Object.assign(Object.assign({},Do),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:bo},initGroupAttributes:{groupID:b,groupAttributes:Lo},setGroupAttributes:{groupID:b,groupAttributes:Lo},deleteGroupAttributes:{groupID:b,keyList:Object.assign(Object.assign({},bo),{allowEmpty:!0})},getGroupAttributes:{groupID:b,keyList:Object.assign(Object.assign({},bo),{allowEmpty:!0})},getGroupCounters:{groupID:b,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:b,counters:Lo},increaseGroupCounter:{groupID:b,key:b,value:Do},decreaseGroupCounter:{groupID:b,key:b,value:Do}},Go={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},Po=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=A,this.groupAction=Ji,this.groupAttribute=So,this.groupMember=co}install(e,t=[]){this._core=e,_i.init(e),A.init(e),Ji.init(e,this),co.init(e,this),Zi.init(e),po.init(e),So.init(e),Ro.init(e),e.helper.registerValidateConfig({auth:Go,params:No}),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;null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name)})}_reset(){A.reset(),So.reset(),po.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)}},wo=new class{init(e){this.core=e}},Uo={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},ko={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21};class Fo{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:n,onFail:i}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=n,this._onFail=i}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getPollingInterval())}isRunning(){return this._isRunning}_request(){return I(this,void 0,void 0,function*(){try{var e=yield function(n,i){return I(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getPollingInterval());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"),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class qo{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 xo=e=>e===Uo.GROUP_TIPS_HAS_NO_ROAMING||e===Uo.GROUP_TIPS_HAS_ROAMING,Vo=e=>e===Uo.GROUP_SYSTEM_MESSAGE;function Bo(g){var e,t,s,r,n,i,o,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:n,GId:i,MS:o,CCD:a,F_Account:l,IsSys:u,GInf:c,MsgBody:d}=g,h=S(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:n,ToGroupId:i,MsgSeq:o,CloudCustomData:a,From_Account:l,IsSystemMsg:u,GroupInfo:function(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:n}=e,e=S(e,["GN","GT","F_Hd","F_NN"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),n&&(t.From_AccountNick=n),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:r,RT:n,UDF:i,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:l}=e,e=S(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:n,UserDefinedField:i},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=S(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=l.map(e=>{var{Img:t,NN:s}=e,e=S(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((xo(u)||Vo(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===Uo.BROADCAST_MESSAGE||u===Uo.NORMAL_MESSAGE){var c=l;let e=wo["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 xo(u)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:n,OpType:i}=(c=l).MsgBody||{},"number"==typeof e||1!==i&&2!==i||(c.MsgBody.GroupJoinType=2===i?0:1),s||(c.MsgBody.MsgMemberExtraInfo=n.map(e=>({UserId:e}))),1!==i||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),Vo(u)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:n}=(o=l).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:n,ImageUrl:"",NickName:""},e),o.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*o.MsgTimeStamp},o.MsgBody),o.MsgBody=Object.keys(o.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:o.MsgBody[t]}),{})),a}var jo=new class{constructor(){this._name="MessageParser",this._sequenceList=new qo(200),this._messageIDList=new qo(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(n,e,i=!1){this._sortServerMessageList({groupID:n,serverMessageList:e,isHistoryMessage:i});var o=this._handleMessageList(n,e);if(0!==o.length){if(!i){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=wo["core"];return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(o[o.length-1]);e.updateConversation(""+t+n,{lastMessage:s})}this._checkMessageStacked(o);let e=o.filter(e=>!0===e.isModified),t=o.filter(e=>!1===e.isModified),{MESSAGE_RECEIVED:s,MESSAGE_MODIFIED:r}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:r,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let r=[];r=this._avChatRoomHandler.isPollingSimplifiedMessage()&&!s?(t.sort((e,t)=>e.MS-t.MS),t.map(e=>e.MS)):(t.sort((e,t)=>e.MsgSeq-t.MsgSeq),t.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${e} count:${r.length} sequenceList:`+r),r.length=0}_handleMessageList(s,r){var n,i,{messageDataHandler:o,messageHelper:a}=this._core["message"],l=this._avChatRoomHandler.isPollingSimplifiedMessage(),u=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(l&&(e=Bo(e)),Vo(e.Event)&&Object.values(ko).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),n=a.parseServerGroupMessage(e),i=this._createMessage(n),xo(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(n)?this._avChatRoomHandler.handleGroupAttributesUpdated(n):null===this._filterDuplicateMessage(i)||o.isMessageSentByCurrentInstance(i)||(1===n.isModified&&(i.isModified=!0),xo(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(i)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];xo(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),Vo(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(Uo).includes(t)?t===Uo.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===Uo.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===Uo.MESSAGE_REACTION?null:e:(console.warn(this._name+".onMessageReceived unknown event:"+t),null)}_createMessage(e){var{message:{messageFactory:t},OuterConstant:s}=this._core;let r=s.CONV_GROUP;e.event===Uo.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:i,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:o,Reason:a=""}}=e,l=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+n.CONV_GROUP+i,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:r};l.push(e)}),0!==l.length&&this._emitEvent({name:t,data:l})}_onLiveCustomData(e){var t=this._core["OuterEvent"]["ROOM_CUSTOM_DATA_RECEIVED"],{ToGroupId:e,MsgSeq:s,MsgTimeStamp:r,MsgBody:n}=e,n=(null==n?void 0:n.MsgContent)||"";this._emitEvent({name:t,data:n}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+n)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.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:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),i=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];n&&(e=Bo(e));var a=r.parseServerGroupMessage(e);Object.values(Uo).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(i.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<i.length&&this._emitEvent({name:e,data:i})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:n=60}=r,i=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:i,memberCount:r,expireTime:n}:(e.latestUpdateTime=i,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let Ko=e=>{var{store:t}=wo["core"];return(t.get("cloudConfig")||{})[e]},Ho=e=>{var{utils:{isUndefined:t}}=wo["core"];return!t(e)},Wo=()=>{var e=Ko("polling_interval");return Ho(e)?parseInt(e,10):300},$o=()=>{var e=Ko("polling_simplified_msg");return Ho(e)?parseInt(e,10):0};var Yo,zo=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,jo.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:r,GroupInfo:{GroupId:n,GroupType:i}}=s[e],r=Object.values(ko).includes(r.ReportType);i===t&&r&&this.reset(n)}}getPollingInterval(){return this._pollingInterval}isPollingSimplifiedMessage(){return 0!==$o()}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 e=0<this._joinedGroupMap.size?[...this._joinedGroupMap.values()].filter(e=>e.type===TYPES.GRP_LIVE):e}handleJoinGroupResult(l){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:n,group:i,historyMessageList:o}=l,a=i["groupID"];return yield this._preCheck(i),this._joinedGroupMap.set(a,i),this._parentPlugin.groupDataHandler.updateLocalGroup([i]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<o.length&&jo.onMessageReceived(a,o,!0),e(n)?{status:r.JOIN_STATUS_SUCCESS,group:i}:this.startMessageLongPolling(l)})}_preCheck(n){return I(this,void 0,void 0,function*(){var{common:e,OuterConstant:t,helper:s,apiMap:{quitGroup:r}}=this._core;if(e.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(e=Ko("polling_count_limit"),Ho(e)&&0<e?parseInt(e,10):20))throw new s.ChatError({code:2688,message:"the count of longPolling exceeds the max limit"})}else 0!==this._joinedAVChatRoomCount()&&n.type!==t.GRP_LIVE&&([e,s]=this._joinedGroupMap.entries().next().value,s.selfInfo.role===t.GRP_MBR_ROLE_OWNER?this._parentPlugin.groupDataHandler.deleteLocalGroup(e):yield r(e),this.reset(e))})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,n=r["groupID"];return this._pollingRequestInfoMap.set(n,{longPollingKey:e,startSequence:s}),this._pollingInterval=Wo(),this._startPolling(n),{status:t.JOIN_STATUS_SUCCESS,group:r}}_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 Fo({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:$o()}:{longPollingKey:t,startSequence:s,simplifiedMessage:$o()}}_handleSuccess(s,e){var r=e["ErrorCode"];if(0===r)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:`+r)}}_handleResponseData(e,t){var{Key:t,NextSeq:s,NextBroadcastSeq:r,RspMsgList:n=[],RspBroadcastMsgList:i=[]}=t;t&&s&&this._pollingRequestInfoMap.set(e,{longPollingKey:t,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<n.length?(0!==this._pollingNoMessageCount&&(this._pollingNoMessageCount=0,this._pollingInterval=Wo()),jo.onMessageReceived(e,n)):(this._pollingNoMessageCount+=1,this._pollingNoMessageCount===(t=Ko("polling_no_msg_count"),Ho(t)?parseInt(t,10):20)&&(this._pollingInterval=Wo()+(s=Ko("polling_interval_plus"),Ho(s)?parseInt(s,10):2e3))),0<i.length&&jo.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()]}_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);else{console.log(this._name+"._stopPolling all");for(let 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,jo.reset()}},Jo=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 I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(r),{group:{type:s}}=t["data"];return s===e.GRP_AVCHATROOM?zo.handleJoinGroupResult(t.data):t})}},Qo=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}quitGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&zo.reset(r),t})}},Xo=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}dismissGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&zo.reset(r),t})}},Zo=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(n){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=n["groupID"],e=e.getGroup(r);return(null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits("AV_MBR_LIST")?this._getGroupMemberList(n):this._parentPlugin.groupMember.getGroupMemberList(n)})}_getGroupMemberList(i){return I(this,void 0,void 0,function*(){let n="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(i,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${n} ok, groupID:${i.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:n=0,Marks:i=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:n,marks:i,isOnline:!0}})}},ea=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 I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},OuterConstant:t}=this._core,e=e.getGroup(s);return e?e.type===t.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(r){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=zo.getLocalOnlineMemberCount(r);if(e(s)||this._isExpired(r)){let{memberCount:e=0}=yield this._getOnlineMemberCountFromServer(r);return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${e} from server.`),{code:0,data:{memberCount:e}}}return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${s.memberCount} from local.`),{code:0,data:{memberCount:s.memberCount}}})}_isExpired(e){var e=zo.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(i){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return I(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||{},r=Date.now(),n={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return zo.updateLocalOnlineMemberCount(i,n),{memberCount:t}}catch(e){var s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},ta=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 I(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:n}=this._core,i=o["groupID"],t=t.getGroup(i);if(s(t))throw new r.ChatError({functionName:e,code:2603});if(t.type!==n.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(r.checkBusinessCapabilityBits("AV_BAN_MBR"))return this._deleteGroupMember(o);throw new r.ChatError({functionName:e,code:3122})})}_deleteGroupMember(o){return I(this,void 0,void 0,function*(){let s="_deleteGroupMember",{appStore:{groupStore:e},helper:r}=this._core,{groupID:t,duration:n=0,userIDList:i}=o;if(0===n)throw new r.ChatError({functionName:s,code:2686});try{return yield function(n,i){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(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 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}})}},sa=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return I(this,void 0,void 0,function*(){let n="markGroupMemberList",{groupID:i,markType:o,enableMark:a,userIDList:l=[]}=e,u=this._generateRequestData(e);try{let e=yield function(r,n){return I(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(u,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,l);return console.log(`${this._name}.${n} ok, groupID:${i} markType:${o} enableMark:${a} success:${s.length} fail:`+r.length),{code:0,data:{successUserIDList:s,failureUserIDList:r}}}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}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:n=[]}=e,i=!0===r?1:2,o=[...n];return 500<o.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:i,memberList:o.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){let s=[],r=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:r).push(t)}),{successUserIDList:s,failureUserIDList:r}}},ra=new class{init(e,t){console.log("AVChatRoomAction.init"),Jo.init(e,t),Qo.init(e,t),Xo.init(e,t),Zo.init(e,t),ea.init(e,t),ta.init(e,t),sa.init(e)}},na=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:r}=this._core,{groupID:e,longPollingKey:n,longPollingSequence:i=1}=e;if(s(n))return console.warn(this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});zo.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=zo.getJoinedLiveList(),!t.isUnlimitedAVChatRoom()&&0<s.length&&this.stopMessageLongPolling({groupID:s[0]}),t={groupID:e,type:r.GRP_LIVE};return console.log(this._name+`.startMessageLongPolling groupID:${e} longPollingKey:${n} longPollingSequence:`+i),zo.startMessageLongPolling({group:t,longPollingKey:n,startSequence:i})}stopMessageLongPolling(e){e=e.groupID;return zo.reset(e),console.log(this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}},i=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,wo.init(e),zo.init(e,t),ra.init(e,t),na.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){zo.onAVChatRoomSystemNotification(e)}_reset(){zo.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 ia=new class{init(e){this.core=e}},oa="message",aa="user",la={OR:"or",AND:"and"},ua={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},ca={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![la.OR,la.AND].includes(e)||"keywordListMatchType should be OR or AND"},da={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},ha={required:!1,rules:["string"],allowEmpty:!0},ga={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=ia.core["OuterConstant"];if(!Array.isArray(t))return"groupTypeList should be an array";var s=[e.GRP_PUBLIC,e.GRP_COMMUNITY,e.GRP_WORK,e.GRP_MEETING];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"groupTypeList should be supported group type"}},pa={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=ia.core["OuterConstant"],s=[e.MSG_TEXT,e.MSG_IMAGE,e.MSG_AUDIO,e.MSG_FILE,e.MSG_VIDEO,e.MSG_LOCATION,e.MSG_CUSTOM,e.MSG_MERGER];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"messageTypeList should be supported message type"}},_a={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=ia.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},ma=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),va={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=ia.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},fa={searchCloudMessages:{keywordList:ua,keywordListMatchType:ca,cursor:ha,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:pa,conversationID:_a,timePosition:ma("timePosition"),timePeriod:ma("timePeriod")},searchCloudUsers:{keywordList:ua,keywordListMatchType:ca,cursor:ha,count:da,miniBirthday:ma("miniBirthday"),maxBirthday:ma("maxBirthday"),gender:va},searchCloudGroupMembers:{keywordList:ua,keywordListMatchType:ca,cursor:ha,count:da,groupTypeList:ga,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ua,keywordListMatchType:ca,cursor:ha,count:da,groupTypeList:ga}},Sa={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0},Ia=new class{install(e){this._core=e,ia.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:Sa,params:fa})}searchCloudMessages(v){return I(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a,ssoLog:e}=this._core,t=e.createSSOLogData({method:"searchCloudMessages"}),{conversationID:s,timePeriod:r,timePosition:n}=v,i=S(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:r,timePosition:n});var u=yield function(c){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:n,endTime:i,startTime:o,cursor:a,account:l,groupID:u}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:n,EndTime:i,StartTime:o,Cursor:a,PeerAccount:l,GroupID:u};return ia.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:n,UserID:r}=e,i=n?""+o.CONV_GROUP+n:""+o.CONV_C2C+r;return this._isSearchingAllConversations(v)&&1<s?{conversationID:i,messageCount:s,messageList:[]}:{conversationID:i,messageCount:s,messageList:t.map(e=>{return a.isEmpty(n)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}));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:oa,functionName:"searchCloudMessages"})}})}searchCloudUsers(f){return I(this,void 0,void 0,function*(){var s;try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:t,count:r=20}=f,n=S(f,["keywordListMatchType","count"]),i=Object.assign({count:r,keywordListMatchType:t===la.AND?1:0},n),o=(this._setBirthdayRangeParams(i,f),yield function(a){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:n,cursor:i,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,UserBirthStart:r,UserBirthEnd:n,Gender:o};return ia.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:aa,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(h){return I(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:t=20,keywordListMatchType:s}=h,r=S(h,["count","keywordListMatchType"]),n=yield function(o){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:n,groupIDList:i}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,GroupType:r,GroupIdList:i};return ia.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===la.AND?1:0},r));if(!n)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:o,GroupMembers:a=[],Cursor:u,TotalCount:c}=n;if(0!==i)throw{errorCode:i,errorInfo:o};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:r,GroupMemberUserName:n,GroupMemberUserID:i,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:i,nick:n,nameCard:o,avatar:a};if(l.has(t)){let e=l.get(t);e.memberList.push(s),l.set(t,e)}else l.set(t,{groupInfo:e,memberList:[s]})}),{code:0,data:{searchResultList:[...l.values()],cursor:u,totalCount:c}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:aa,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(d){return I(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:t=20,keywordListMatchType:s}=d,r=S(d,["count","keywordListMatchType"]),n=yield function(i){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:n}=i,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,GroupType:r};return ia.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===la.AND?1:0},r));if(!n)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:o,Groups:a,Cursor:l,TotalCount:u}=n;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:r,GroupName:n,GroupOwnerTinyID:i,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:l,GroupAddOption:u,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:n,ownerTinyID:i,ownerID:o,ownerNick:a,type:l,joinOption:u,inviteOption:c}}))||[],cursor:l,totalCount:u}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:aa,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:r}){var{ssoLog:n,helper:i}=this._core;let o=e;60020===e?o="SearchUnable":s!==oa&&27003===e?o="SearchParamsError":s!==oa&&60018===e&&(o="SearchOverLimit");s=new i.ChatError({code:o,message:t});throw n.getSSOLogData(r).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 Ea(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Ca="qualityStat",Ma="im-ssolog-quality-stat",ya=(Yo=Yo||{},Yo[Yo.ONLINE=8]="ONLINE","networkRTT"),Oa="messageE2EDelay",Ta="sendMessageC2C",Aa="sendMessageGroup",Ra="sendMessageGroupAV",Da="sendMessageRichMedia",ba="cosUpload",La="messageReceivedGroup",Na="messageReceivedGroupAVPush",Ga="messageReceivedGroupAVPull",Pa={networkRTT:2,messageE2EDelay:3,sendMessageC2C:4,sendMessageGroup:5,sendMessageGroupAV:6,sendMessageRichMedia:7,messageReceivedGroup:8,messageReceivedGroupAVPush:9,messageReceivedGroupAVPull:10,cosUpload:11},wa=[Ta,Aa,Ra,Da,ba],Ua=[La,Na,Ga],ka=[ya,Oa,Ta,Aa,Ra,Da,ba,La,Na,Ga],Fa={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},qa="quality_stat";var xa=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(Fa))}init(e){this._core=e,Object.values(wa).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,n=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case n.TOTAL_COUNT:this._handleTotalCount(t);break;case n.SUCCESS_COUNT:this._handleSuccessCount(t);break;case n.FAILED_COUNT:this._handleFailedCount(t,s);break;case n.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,n,i,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:n}=o,r=Ea(s/t*100,2),i=Ea((n=s+n)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:n,percent_platform:i,average_value:o}):null}_handleTotalCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.totalCount++}_handleSuccessCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.successCount++}_handleFailedCount(s,e){var t=null!=(t=null==e?void 0:e.code)?t:null==e?void 0:e.errorCode;if(this._isUserSideError(t)){let e=this._getSendMessageSpecifiedKey(s),t=e&&this._messageStatsMap.get(e);t&&t.failedCountOfUserSide++}}_handleSendCost(e,t){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&(e.costSum+=Date.now()-t,e.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||120001<=e&&e<=13e4||10100<=e&&e<=10200}_getSendMessageSpecifiedKey(s){let{MSG_IMAGE:e,MSG_AUDIO:t,MSG_VIDEO:r,MSG_FILE:n,CONV_C2C:i,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,n].includes(s.type))return Da;if(s.conversationType===i)return Ta;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?Ra:Aa}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===ba?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)}},Va=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){var{OuterEvent:e,notificationCenter:t}=this._core=e;this._initStatsMap(),t.subscribeOuterEvent(e.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){var t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:r}}=this._core;s(t)||!this._currentCycleStats.has(t)?console.warn(Ca+".addMessageSequence invalid key:",t):({conversationID:s,sequence:e}=e,s=s.replace(r,""),0!==(r=this._lastCycleStats.get(t)).size&&r.has(s)&&e>(r=r.get(s)).minSeq&&e<r.maxSeq?this._insertToLastCycle(e,r):this._addToCurrentCycle(t,s,e))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,n=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(n+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:n,percent_business:Ea(n/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Ua).forEach(e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)})}_onMessageReceived(e){var{data:e=[]}=e;e.forEach(e=>{this.addMessageSequence(e)})}_transferCycleDataOptimized(e){var t=this._currentCycleStats.get(e);if(t){let r=new Map;t.forEach((e,t)=>{var s=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;r.set(t,{sortedSequences:s,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,r),this._currentCycleStats.set(e,new Map)}}_getReceivedMessageSpecifiedKey(s){let{CONV_GROUP:e,GRP_AVCHATROOM:r}=this._core["OuterConstant"];if(s.conversationType===e&&!0!==(null==s?void 0:s._onlineOnlyFlag)){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);return t?(s=t["type"],s===r?Ga:La):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,r=e.length-1;for(;s<=r;){var n=Math.floor((s+r)/2);if(e[n]===t)return n;e[n]<t?s=n+1:r=n-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},Ba=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],n=[s,r];t.forEach(e=>{!n.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Ea(this._totalDelay/e,1)}_calculatePercentage(e,t){return Ea(e/t*100,2)}},ja=new class{init(e){this.core=e}},L=new class{constructor(){this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:n,DESTROY:i},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;ja.init(e),xa.init(e),Va.init(e),Ba.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(n,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){console.log(Ca+".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:qa,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...ka.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&&xa.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:Pa[e],timestamp:Date.now(),network_type:Yo.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case Oa:return Ba.getStatResult();case Ta:case Aa:case Ra:case Da:case ba:return xa.getStatResult(e);case La:case Na:case Ga:return Va.getStatResult(e);default:return null}}_uploadQualityReports(t){return I(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=ja.core,s="imopenstat.tim_web_report_v2",e=e.generateSSOLogProtocolData({servcmd:s,data:r}),s=e.head.seq+s;t.sendPacket(e,{requestId:s})}(),this._reportIndex++,this._wholePeriod=!1}catch(e){console.warn("doReport failed. error:",e),this._pendingReports=this._pendingReports.concat(t),this._cacheFailedLogs()}})}_cacheFailedLogs(){var e=this._pendingReports,t=Ca+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(Ma)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(Ma,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(qa)}_dispose(){var{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:r}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(r,this._dispose,this),this._reset(),Ba.dispose(),Va.dispose()}};let Ka=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:n}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(n.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return I(this,void 0,void 0,function*(){let n=this._core["OuterConstant"],i=[],o=[];return yield Promise.all(null==e?void 0:e.map(r=>I(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+n.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:o})),i.push(e.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:i,groupTipList:o}})}_recoverHistoryForConversation(e){return I(this,arguments,void 0,function*({conversationID:S,localLastMessageSequence:I,serverLastMessageSequence:E,groupTipList:C}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:n,notificationCenter:i,message:o,appStore:a,common:{getMessagePreviewText:l}}=this._core,u=E-I,c=Math.min(20,u),d={},h=yield o.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:S,sequence:I+c,direction:n.Direction.FORWARD,count:c}),{nextReqMessageIDFromServer:g,hasNoMoreHistoryMessage:p,messageList:_,serverGroupTipList:m}=h,v=(e(m)&&C.push(...m),p&&g<0),f=[];if(e(_)&&(_.forEach(e=>{o.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===n.CONV_SYSTEM&&(e.isSystemMessage=!1),o.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:S,localLastMessageSequence:e,serverLastMessageSequence:E,groupTipList:C})}t(d.lastMessage)&&(d.lastMessage.messageForShow=l(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(S,d))}catch(I){console.debug("Recovery failed for conversation:",S,I)}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var n;0<(null==e?void 0:e.length)&&(n=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,n))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&1<=t&&t<300}},Ha,Wa;Ha=es.STANDARD,Wa=[m,function(e){Us.install(e),Bs.install(e),js.install(e)},Ks,t,Zs,L,Ka,e,Vn,pi,Po,i,Ia,gr];var $a,Ya,za,F,Ja,Qa,Xa,Za=Object.freeze({__proto__:null,ChatError:_,buildAndSendPacket:Os,get builtInPlugins(){return Wa},checkBusinessCapabilityBits:Ss,deepMerge:bs,getCurrentUserID:g,getErrorMessage:as,getMessagePreviewText:Ls,isC2CConv:e=>Y(e)&&e.slice(0,3)===Wt.CONV_C2C,isCommunity:Es,isGroupConv:e=>Y(e)&&e.slice(0,5)===Wt.CONV_GROUP,isTopic:Cs,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=k.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:Is,registerInterceptor:ms,registerValidateConfig:vs,requireAuth:ls,get sdkEdition(){return Ha},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:i}=C;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:n}=C,{groupID:i,sequence:o}=t,a=!1;return Es({groupID:i})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[n]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[n],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(n)&&(e=[i]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:_s,validateParameters:cs,workflowManager:h}),el=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:n}=s,i=this._conversationMap.get(e);i&&!He(t)&&(Object.keys(t).forEach(e=>{i[e]=t[e]}),r)&&k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED,{needSort:n})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED))}},tl=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]})}},sl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:n,updateUnreadCount:i=!0}=e,o=S(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(r=this._messagesByConversation.get(s))?void 0:r.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(n,{conversationID:s,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];Cs(s)?k.notificationCenter.emitInnerEvent(jt[e],t):k.notificationCenter.emitInnerEvent(e,t)}},rl=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)}},nl=Object.freeze({__proto__:null,conversationStore:el,groupStore:tl,messageStore:sl,userStore:rl});let il={on:k.notificationCenter.subscribeOuterEvent.bind(k.notificationCenter),off:k.notificationCenter.unSubscribeOuterEvent.bind(k.notificationCenter),destroy:function(){return I(this,void 0,void 0,function*(){var e,t;try{null!=(e=k.store.get("login"))&&e.isLogin&&(yield il.logout()),k.notificationCenter.emitInnerEvent(d.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{k.notificationCenter.emitOuterEvent(u.SDK_DESTROY,{SDKAppID:null==(t=k.store.get("instance"))?void 0:t.sdkAppId}),Is.clear(),fs.clear(),h.destroy(),k.destroy()}})},callExperimentalAPI:function(e,t){return ol[e]?ol[e](t):Promise.reject(new Error(`API ${e} is not found`))},use:fs.installExternalPlugin.bind(fs),registerPlugin:function(e){console.log("registerPlugin",e)},setLogLevel:function(e){console.log("setLogLevel",e),!k||"function"!=typeof k.setLogLevel||null!=k&&k.setLogLevel(e)}},ol={},al={};function ll(e){let{apiName:r,context:t,methodName:n=r,matcher:s}=e;al[r]||(al[r]=[]),al[r].push({context:t,methodName:n,matcher:s}),il[r]&&1!==al[r].length||(il[r]=(...t)=>{_s(n,t);var s=al[r];for(let e of s)if(!e.matcher||e.matcher(t))return e.context[e.methodName].bind(e.context)(...t)})}function ul(e,t,s){s=s||e;ol[e]=t[s].bind(t)}function cl(){return Object.assign(Object.assign({InnerEvent:d,InnerEventSubType:k.notificationCenter.InnerEventSubType,OuterEvent:u,OuterConstant:C,SignalingEvent:Ft,helper:Object.assign(Object.assign(Object.assign({},k.utils),k.common),{registerApi:ll,registerExperimentalAPI:ul,registerInterceptor:ms,registerValidateConfig:vs,checkBusinessCapabilityBits:Ss,registerWorkflowStep:h.registerWorkflowStep.bind(h),ChatError:_}),apiMap:il},k),{constants:Object.assign(Object.assign({},os),k.constants),common:Object.assign(Object.assign({},Za),k.common),utils:k.utils,appStore:nl})}ol.statTUIKeyFeatures=function(e){console.log("statTUIKeyFeatures",e)},(G=$a=$a||{})[G.USER_INITIATED=0]="USER_INITIATED",G[G.KICKED_OUT=1]="KICKED_OUT",(N=Ya=Ya||{})[N.multipleAccount=1]="multipleAccount",N[N.multipleDevice=2]="multipleDevice",N[N.restApi=3]="restApi",(m=za=za||{})[m.multipleDevice=3002]="multipleDevice",m[m.multipleAccount=3003]="multipleAccount",m[m.usersigExpired=70001]="usersigExpired",m[m.restApi=20002]="restApi";let dl={[Ya.multipleAccount]:"multipleAccount",[Ya.multipleDevice]:"multipleDevice",[Ya.restApi]:"REST_API_Kick",[za.multipleAccount]:"multipleAccount",[za.multipleDevice]:"multipleDevice",[za.restApi]:"REST_API_Kick",[za.usersigExpired]:"userSigExpired"},hl="login_online_presence_task",{ERROR:gl,DESTROY:pl,FORCE_OFFLINE:_l}=d,{KICKED_OUT_MULT_ACCOUNT:ml,KICKED_OUT_MULT_DEVICE:vl,KICKED_OUT_REST_API:fl,ACCOUNT_A2KEY_EXPIRED:Sl,MSG_A2KEY_EXPIRED:Il}=Zt;class El{init(){var e=k["notificationCenter"];e.subscribeInnerEvent(_l,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(gl,Il,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(gl,Sl,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(gl,ml,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(gl,vl,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(gl,fl,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(pl,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 I(this,void 0,void 0,function*(){var e=t["kickedOutReasonCode"];try{this._logKickedOutEvent(t),yield k.login.loginAction.logout($a.KICKED_OUT)}catch(e){console.debug(e)}finally{k.notificationCenter.emitOuterEvent(u.KICKED_OUT,{data:{type:dl[e]},name:u.KICKED_OUT}),[Ya.restApi,Sl,Il].includes(e)&&k.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,s=k.ssoLog.createSSOLogData({method:"kickedOut"}),e=`type:${dl[e]} newInstanceInfo: `+JSON.stringify(t);s.setLogInfo({message:e}).end(!0),console.warn("loginModule."+e)}_isKickedOut(e){return[Ya.multipleAccount,Ya.multipleDevice,Ya.restApi].includes(e)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(_l,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(gl,Sl,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(gl,Il,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(gl,ml,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(gl,vl,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(gl,fl,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(pl,this._dispose,this)}}function Cl(){return I(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:r,CustomStatus:n,PurchaseBits:i,A2Key:o,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:u,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:n,purchaseBits:i,a2Key:o,authKey:a,errorCode:l,errorInfo:u,actionStatus:c}}}catch(e){throw console.warn(e),e}})}class Ml{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){var{notificationCenter:e,store:t}=k;t.set("login",{isReady:!1}),ll({apiName:"login",context:this}),ll({apiName:"logout",context:this}),ll({apiName:"getLoginUser",context:this}),ll({apiName:"isReady",context:this}),e.subscribeInnerEvent(d.RECONNECTED,this._reLogin,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}login(s){return I(this,void 0,void 0,function*(){let e=this._getUiPlatform(),t=(k.store.get("instance")||{})["sdkEdition"],r=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:Zt.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!==Zt.REPEAT_LOGIN&&(this._latestLoginAt=0),new _({functionName:"login",code:t}));throw r.setError(s).end(!0),s}})}_getUiPlatform(){var{store:e,utils:{IN_BROWSER:t,isH5:s}}=k,e=(null==(e=e.get("instance"))?void 0:e.scene)||"";let r=e;return t&&(r=e+"_web",s)&&(r=e+"_h5"),rs[r]}_reLogin(){return I(this,void 0,void 0,function*(){var e,t,s,r,n,i;try{this._isLoginIn()&&(t=k.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Cl())&&({instanceID:r,customStatus:n}=s,k.store.set("login",{statusInstanceId:r}),h.executeWorkflow(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:n,statusType:Kt.USER_STATUS_ONLINE}),i=`socketId:${null==(e=k.channel.getSocketAdapter())?void 0:e.getId()} instanceId:`+r,t.setLogInfo({message:i}).end(!0))}catch(e){console.warn(e)}})}logout(){return I(this,arguments,void 0,function*(s=$a.USER_INITIATED){let e=k.ssoLog.createSSOLogData({method:"logout"});e.setLogInfo({moreMessage:"identifier:"+g()});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()?g():""}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(u.SDK_READY,{name:u.SDK_READY})},1)}_updateAndEmitSDKNotReady(){k.store.set("login",{isReady:!1}),k.notificationCenter.emitOuterEvent(u.SDK_NOT_READY,{name:u.SDK_NOT_READY})}_validateAfterLogin(e){var t,s="login";if(!e)throw new _({functionName:s,message:"login response is empty"});var{tinyID:e,a2Key:r}=e||{},n=k.ssoLog.getSSOLogData(s);if(!e){let e=new _({functionName:s,code:Zt.NO_TINYID});throw null!=(t=null==n?void 0:n.setError)&&t.call(n,e).end(),e}if(!r){let e=new _({functionName:s,code:Zt.NO_A2KEY});throw null!=(t=null==n?void 0:n.setError)&&t.call(n,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:as({code:"RepeatLogin",replacement1:null==(e=k.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return I(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(),Cl()})}_ensureAsyncComplete(){return I(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=k.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:n,purchaseBits:i}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),k.user.userStatus.setCustomStatus(n),h.executeWorkflow(o.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),k.common.taskScheduler.addTask({id:hl,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(s){return I(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(),h.reset(),k.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;k.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_logLoginSuccess(e){var t=k.ssoLog.getSSOLogData("login"),{helloInterval:e,instanceID:s,timeStamp:r,customStatus:n}=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:${r} offset:${o} customStatus:${n} href: ${l} appId: `+a;console.log("login ok. "+i),t.updateLogCreatedAtByTimeOffset(),t.setLogInfo({moreMessage:i}).end()}_sendOnlinePresenceRequest(){return I(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(hl),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 yl={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Ol={logout:!0};class Tl{constructor(){this.loginAction=new Ml,this.kickedOutHandler=new El,this.loginAction.init(),this.kickedOutHandler.init(),vs({auth:Ol,params:yl})}}(Ks=F=F||{}).CONV_C2C="C2C",Ks.CONV_GROUP="GROUP",Ks.CONV_TOPIC="TOPIC",Ks.CONV_SYSTEM="@TIM#SYSTEM",(t=Ja=Ja||{}).MSG_PRIORITY_HIGH="High",t.MSG_PRIORITY_NORMAL="Normal",t.MSG_PRIORITY_LOW="Low",t.MSG_PRIORITY_LOWEST="Lowest",(L=Qa=Qa||{}).MSG_TEXT="TIMTextElem",L.MSG_CUSTOM="TIMCustomElem",L.MSG_LOCATION="TIMLocationElem",L.MSG_FACE="TIMFaceElem",L.MSG_IMAGE="TIMImageElem",L.MSG_AUDIO="TIMSoundElem",L.MSG_FILE="TIMFileElem",L.MSG_VIDEO="TIMVideoFileElem",L.MSG_GRP_TIP="TIMGroupTipElem",L.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",L.MSG_MERGER="TIMRelayElem";let Al={1:Ja.MSG_PRIORITY_HIGH,2:Ja.MSG_PRIORITY_NORMAL,3:Ja.MSG_PRIORITY_LOW,4:Ja.MSG_PRIORITY_LOWEST},Rl=((e=Xa=Xa||{}).IN="in",e.OUT="out",{});function Dl(e){var t,s,r;return e?(void 0===Rl[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),Rl[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Rl[e])):Rl[e]+=1,Rl[e]):0}class bl{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=Ja.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=k.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:n,needReadReceipt:i,isSupportExtension:o,customModerationConfigurationId:a,to:l,from:u,nick:c="",avatar:d="",time:h,messageControlInfo:g,tinyID:p,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:S,checkResult:I=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:O=Ut.SUCCESS,revokeReason:T="",conversationSubType:A,clientSequence:R,protocol:D="JSON",revokerInfo:b={userID:"",nick:"",avatar:""},readReceiptInfo:L={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:N,groupProfile:G,atUserList:P,flow:w,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||p,this.needReadReceipt=!0===i||1===i,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=l,this.nick=c,this.avatar=d,this.protocol=D,this.random=void 0===N?(t=t||99999999,Math.round(Math.random()*t)):N,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=S||0,this.conversationType=f||F.CONV_C2C,this.hasRiskContent=1<I,this.version=v,this.isPlaceMessage=E,this.isRevoked=2===E||8===C,this.isSystemMessage=y,this.readReceiptInfo=L,this.revokeReason=T,this.revokerInfo=b,this._receiverList=M,this.conversationSubType=A,this.revoker=(null==b?void 0:b.revoker)||"",this.clientSequence=R||S||0,this.status=O,this.atUserList=P||[],this.flow=w,this.isRead=U,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(G)}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=Dl(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 Ll{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new Ll({data:e,description:s,extension:t})}constructor(e){this.type=Qa.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 Nl{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new Nl({text:e})}constructor(e){this.type=xt.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 Gl=new class{constructor(){this._elementClassMap={[Qa.MSG_CUSTOM]:Ll,[Qa.MSG_TEXT]:Nl}}init(){ll({apiName:"createCustomMessage",context:this}),ll({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=Xa.OUT}=e,r=(k.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:r})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:r})&&(e.flow=Xa.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new bl(t)}createCustomMessage(t){let e=g(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[Qa.MSG_CUSTOM];if(!s)return null;if(r){let e=new r(t.payload);s.setElement(e)}return s}createTextMessage(e){var t,s;return e?(t="string"==typeof e.payload?e.payload:(null==(t=null==e?void 0:e.payload)?void 0:t.text)||"",t=new Nl({text:t}),s=g(),(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:r,tinyID:n}=k.store.get("login")||{},i=rl.getUserProfile(r);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||n||"",e.from=r,e.status=Ut.UNSENT,e.flow=Xa.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Xa.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Xa.OUT}};let Pl={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}},wl={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Ul={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function kl(r,n){return Object.keys(n).forEach(e=>{var{range:t,defaultValue:s}=n[e];r[e]=t.includes(r[e])?r[e]:s}),r}function Fl(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:r,disableVoipPush:n,enableIOSBackgroundNotification:i}=e=kl(e,Ul),e=S(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),r=!0===r||!0===t?1:0;let o;return $(s)||(o=!1===s?1:0),$(n)||(o=!1===n?1:0),Object.assign(Object.assign({},e),{BadgeMode:r,IsVoipPush:o,ContentAvailable:i?1:0})}(e),AndroidInfo:function(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,{sound:s="",FCMChannelID:r=""}=e=kl(e,wl),e=S(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:-1===(s=(e=s).lastIndexOf("."))?e:e.slice(0,s),OPPOChannelID:t,GoogleChannelID:r})}(e)}:Pl}function ql(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:n,IsSyncMsg:i,MsgBody:o,MsgClientTime:a,MsgLifeTime:l,MsgRandom:u,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:S}=e,I,{From_Account:E,To_Account:C}=e;if(1===i){let e=C;C=E,E=e}if(S){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=S;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:E,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:i,clientTime:a,messageLifeTime:l,random:u,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:g,to:C,tinyID:p,checkResult:_,cloudCustomData:m,revokerInfo:I,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:n,elements:Bl(o)}}function xl(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:n,MsgTimeStamp:i,To_Account:o,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:n,time:i,to:o,elements:Bl(t),messageVersion:a,cloudCustomData:l}}function Vl(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:n,MsgClientTime:i,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,TinyId:d,CloudCustomData:h,MsgVersion:g,MsgCheckResult:p,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,S,I=Ja.MSG_PRIORITY_NORMAL;if(Object.keys(Al).includes(String(e.MsgPriority))&&(I=Al[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;S={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:r,clientTime:i,priority:I,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:S,atUserList:E,elements:Bl(n),to:function(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=k,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:n}={}}=e;return r!==s||t(n)?e:n}(e)}}function Bl(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 jl(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:n,MsgTimeStamp:i,GroupId:o,TopicId:a,MsgVersion:l,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:n,time:i,groupID:o,topicID:a,elements:Bl(t),messageVersion:l,cloudCustomData:u}}function Kl({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:n,flow:i,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&i===Xa.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:n,unreadCount:t?1:0,lastMessage:a})}function Hl(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})}var Wl=Object.freeze({__proto__:null,autoIncrementIndex:Dl,filterValidMessages:Hl,parseServerGroupMessage:Vl,parseServerPushC2CModifyMessage:xl,parseServerPushGroupModifyMessage:jl,parseServerPushMessage:ql,parseServerPushMessageElement:Bl,updateConversationFields:Kl});let $l=k.utils["isPlainObject"];function Yl(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,n=t["offlinePushInfo"],i=(e.conversationType===F.CONV_C2C&&!0===s&&(n?n.disablePush=!0:n={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(i=e.cloudCustomData);var o=[];if(r&&$l(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:o,offlinePushInfo:n}}function zl(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 Jl(t,s){return I(this,void 0,void 0,function*(){var e=yield Os((t.conversationType===F.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:n,messageControlInfo:i,offlinePushInfo:o}=Yl(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:n,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Fl(o),SendMsgControl:r?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:zl(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:n,messageControlInfo:i,offlinePushInfo:o}=Yl(e,t),r=!0===r?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:n,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?i:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:Fl(o),forbidCallbackControl:zl(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let Ql=k.utils["isPlainObject"],{MSG_AUDIO:Xl,MSG_FILE:Zl,MSG_IMAGE:eu,MSG_VIDEO:tu,MSG_MERGER:su}=C;class ru{init(){ll({apiName:"sendMessage",context:this,matcher:e=>![Xl,Zl,eu,tu,su].includes(e[0].type)})}sendMessage(c,t){return I(this,void 0,void 0,function*(){let r=k.ssoLog.createSSOLogData({method:"sendMessage"}),{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:i}=is;if(!(c instanceof bl)){let e=new _({code:Zt.MSG_INSTANCE_REQUIRED});throw r.setError(e).end(),e}let n=c.validateBeforeSend();if(!n.isValid){let{code:e,message:t=""}=n.error||{},s=new _({code:e,message:t});throw r.setError(s).end(),s}this._reportMessageSendQuality({name:e,message:c});let l=!1;var u=(k.message||{})["messageDataHandler"];try{let r=(t||{})["messageControlInfo"],n=null,i=(u.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===F.CONV_C2C?(l=!0===(null==t?void 0:t.onlineUserOnly),n=yield Jl(c,t)):c.conversationType===F.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),n=yield Jl(c,t)),n){let{messageDropReason:e,sequence:t,time:s}=n;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=Ut.SUCCESS,c.time=s,c.conversationType===F.CONV_GROUP&&(c.sequence=t),l?c._onlineOnlyFlag=!0:(u.storeConversationMessage(c),this._applySentMessageControlInfo(c,r),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=Ut.FAIL,u.removeRandomOfSentMessage(c.random);let{errorCode:t,errorMessage:s="",errorInfo:r=s}=e||{},n=(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:r,data:{message:c}}));throw this._logSendMessageError({message:c,error:n}),n}})}_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 r=`head.seq: type:${e.type} from:${e.from} to:`+e.to;if(k.utils.IN_BROWSER){if("connection"in navigator){let e=navigator.connection;r+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:`+e.rtt}if("memory"in window.performance){let e=window.performance.memory;r+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:`+e.jsHeapSizeLimit}}s.setLogInfo({message:r}).setError(t).end()}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,n=Cs(s)?d.TOPIC_NEW_MESSAGE:d.NEW_MESSAGE;k.notificationCenter.emitInnerEvent(n,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Ql(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 r,n=e["conversationID"],i=t.getLatestMsgSentByMe(n);i&&({nick:i,avatar:r}=i,s=i!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(n){return I(this,void 0,void 0,function*(){var{to:t,from:s}=n;let r=t,e=tl.getGroup(r);if(Es({groupID:r})&&null!=e&&e.isSupportTopic)throw new _({code:Zt.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Cs(t)&&([r]=t.split(Jt.TOPIC),e=tl.getGroup(r)),!e&&"function"==typeof(null==il?void 0:il.getGroupProfile)){let e=yield il.getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===C.GRP_AVCHATROOM){let e=as({code:Zt.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new _({code:Zt.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){k.notificationCenter.emitInnerEvent(d.QUALITY_STAT,{label:ns.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class nu{constructor(e){this.value=e,this.next=null}}class iu{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new nu(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 ou=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new iu(100),k.notificationCenter.subscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}get _messagesByConversation(){return sl.getMessages()}storeConversationMessage(e,t=!1){var s=e["conversationID"];return!!s&&(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),!this._shouldSkipStoreMessage(e,t))&&(t=this._getUniqueIdOfMessage(e),this._messagesByConversation.get(s).set(t,e),this._updateLatestMessageMap(e),!0)}_updateLatestMessageMap(e){var t=e["conversationID"];"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){var s=this._getUniqueIdOfMessage(e),r=this._messagesByConversation.get(e.conversationID);if(null!=r&&r.has(s)){let e=null==r?void 0:r.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var{conversationID:t=""}=e,e=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(t)&&null!=(t=this._messagesByConversation.get(t))&&t.delete(e)}modifyConversationMessage(a,t){var l;if(this._messagesByConversation.has(a)||this._sparseMessagesByConversation.has(a)){let e=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(a,e);if(o){let{messageVersion:s,elements:r,cloudCustomData:n,checkResult:e=0}=t,i=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:`+s),o.version<s){let e=this._getUniqueIdOfMessage(o),t=We(r);return null!=(l=this._messagesByConversation.get(a))&&l.has(e)?sl.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:n,hasRiskContent:i,operation:Vt.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=n,o.isModified=!0,o.hasRiskContent=i),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,s){var t;if(this._messagesByConversation.has(e))return null==(t=this._messagesByConversation.get(e))?void 0:t.get(s);if(this._sparseMessagesByConversation.has(e)){let t=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<t.length;e++)if(this._getUniqueIdOfMessage(t[e])===s)return t[e]}return null}findMessage(t){let s=null,e=Array.from(this._messagesByConversation.values());for(var r of e)if(s=Array.from(r.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var n of e)if(s=n.get(t)||null,s)break}return s}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:t,sequence:s,random:r,revoker:n}){let e=this._messagesByConversation.get(t),i=null;if(e){var o=Array.from(e.values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(i);return sl.updateMessage(t,[e],{isRevoked:!0,revoker:n,operation:Vt.revoke}),i}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(i=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return i.isRevoked=!0,i.revoker=n,i}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:r}){for(let e=0;e<t.length;e+=1){var n=t[e];if(n.sequence===s&&($(r)||n.random===r))return n}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],n=[],i=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);i.has(e)||(r.push(t),n.push([e,t]))}if(0<n.length){let e=new Map([...n,...i.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var n=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];n.has(e.ID)||n.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:n}=e;return e+`-${t}-${s}-${r}-`+n}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:i,latestNick:o,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),n=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===n&&(t!==o&&(e.nick=o),s!==i)&&(e.avatar=i)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),k.notificationCenter.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}};function au(e,t){var s,r,n,i,o,a,l,u=el.getConversation(e);null!=u&&u.lastMessage&&(u=u["lastMessage"],{lastTime:s,lastSequence:r,version:n}=u,{time:t,sequence:i,messageVersion:o,elements:a,cloudCustomData:l}=t,s===t)&&r===i&&n!==o&&(u.type=a[0].type,u.payload=a[0].content,u.messageForShow=Ls(u.type,u.payload),u.cloudCustomData=l,u.version=o,el.updateConversation(e,{lastMessage:u}))}class lu{init(){ll({apiName:"modifyMessage",context:this})}modifyMessage(c){return I(this,void 0,void 0,function*(){let r=k.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,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(r.setLogInfo({message:"to:"+n}),o===F.CONV_C2C?t=yield function(c){return I(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:n,time:i,type:o,cloudCustomData:a}=c,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:n,MsgTime:i,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},u=yield Os({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:Bl(e),messageVersion:t,cloudCustomData:s}}})}(c):o===F.CONV_GROUP&&(t=yield function(o){return I(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=o,n={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:r},i=yield Os({servcmd:"openim.modify_group_msg",data:n});if(i){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=i;return{elements:Bl(e),messageVersion:t,cloudCustomData:s}}})}(c)),t){r.end();let e=""+o+n;return n===g()&&o===F.CONV_C2C&&(e=""+o+u),s={conversationType:o,from:u,to:n,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 r.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:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent(u.MESSAGE_MODIFIED,{name:u.MESSAGE_MODIFIED,data:[r]}),k.notificationCenter.emitInnerEvent(d.MESSAGE_MODIFIED,{conversationID:t,message:r}),au(t,e)}_canModifyMessageElement(e){return[Qa.MSG_TEXT,Qa.MSG_CUSTOM,Qa.MSG_LOCATION,Qa.MSG_FACE].includes(e)}}class uu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];h.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,a.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),h.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,a.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),h.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,a.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){h.executeWorkflow(o.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(k.message||{})["messageDataHandler"],r=[],n=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):s.isInMessageList(e)||(s.storeConversationMessage(e)&&Kl({conversationUpdateFields:n,message:e}),s.isMessageSentByCurrentInstance(e)&&!t)||r.push(e)}),{conversationUpdateFieldList:[...n.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[a.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[a.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=ql(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Xa.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(r){var e;let n=(k.message||{})["messageDataHandler"],t=null==(e=k.store.get("login"))?void 0:e.userId,{from:s,nick:i,avatar:o,conversationID:a=""}=r;if(s!==t){let s=n.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;$(i)||$(o)?(r.nick=Y(e)?e:r.nick,r.avatar=Y(t)?t:r.avatar):i===e&&o===t||(n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:i,avatar:o}))}}else{let e=n.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=el.getConversation(e)||{};r.avatar===s&&r.nick===t||el.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),k.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),au(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=F.CONV_C2C,e=xl(e),{to:s,from:r}=e;let n=""+t+s;s===(null==(s=k.store.get("login"))?void 0:s.userId)&&(n=""+t+r),e=Object.assign({conversationType:t,conversationID:n},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 cu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];h.registerWorkflowStep(o.RECEIVE_GROUP_NEW_MESSAGE,a.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),h.registerWorkflowStep(o.RECEIVE_GROUP_NEW_MESSAGE,a.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)&&h.executeWorkflow(o.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=k.message["messageDataHandler"],r=[],n=new Map,i=null==t?void 0:t.GroupMsgArray;return null!=i&&i.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):s.isInMessageList(e)||s.storeConversationMessage(e)&&(r.push(e),Kl({conversationUpdateFields:n,message:e})))}),{conversationUpdateFieldList:[...n.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[a.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=Vl(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Xa.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(n){var e;let t=(k.message||{})["messageDataHandler"],s=null==(e=k.store.get("login"))?void 0:e.userId,{from:r,nick:i,avatar:o,conversationID:a="",_elements:l}=n;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||i===e.nick&&o===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:o,isSentByMe:!0})}else if(r===C.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=l,r={};if(He(t)?He(s)||(r=s):[Qt.JOINED,Qt.KICKED,Qt.ADMIN_SET,Qt.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!He(r)){let{nick:e="",avatar:t=""}=r;n.nick=e,n.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),au(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=F.CONV_GROUP,{topicID:s,groupID:r}=e=jl(e),s=s||r,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===zt.GRP_AVCHATROOM;return!(!tl.getGroup(e)&&t)}}var du=new class{constructor(){this.c2cMessageReceiver=new uu,this.groupMessageReceiver=new cu}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let hu={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."}}}},gu={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var pu=new class{getGroupRoamingMessagesByAnchor(s){return I(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(Wt.CONV_GROUP,""),c=[];let i=l;if(a===kt.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};i=l+e-1}var d=yield function(r){return I(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s}=r,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1};return s&&(e.ReqMsgSeq=s),yield Os({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:r}=d;o.setLogInfo({message:`groupID:${u} sequence:${l} reqSeq:${i} direction:${a}
5
+ complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+r}).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 n=2===s;return a===kt.BACKWARD&&(n=h[h.length-1].sequence>=l),{messageList:Hl(h),invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,serverGroupTipList:c}}}catch(e){t=new _({code:null==e?void 0:e.code});k.ssoLog.getSSOLogData("getGroupRoamingMessagesByAnchor").setError(t).end()}})}_parseMessage(e){var t=Wt.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=C.MSG_GRP_TIP),Vl(e)),t=Gl.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class _u{constructor(){this.messageHelper=Wl,this.messageFactory=Gl,this.messageSender=new ru,this.messageAction=new lu,this.messageReceiver=du,this.messageDataHandler=ou,this.messageHistory=pu,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),vs({auth:gu,params:hu})}}let mu="Tag_Profile_IM_",vu={NICK:mu+"Nick",GENDER:mu+"Gender",BIRTHDAY:mu+"BirthDay",LOCATION:mu+"Location",SELFSIGNATURE:mu+"SelfSignature",ALLOWTYPE:mu+"AllowType",LANGUAGE:mu+"Language",AVATAR:mu+"Image",MESSAGESETTINGS:mu+"MsgSettings",ADMINFORBIDTYPE:mu+"AdminForbidType",LEVEL:mu+"Level",ROLE:mu+"Role"},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:[]},Su=new Map([[vu.NICK,"nick"],[vu.GENDER,"gender"],[vu.BIRTHDAY,"birthday"],[vu.LOCATION,"location"],[vu.SELFSIGNATURE,"selfSignature"],[vu.ALLOWTYPE,"allowType"],[vu.LANGUAGE,"language"],[vu.AVATAR,"avatar"],[vu.MESSAGESETTINGS,"messageSettings"],[vu.ADMINFORBIDTYPE,"adminForbidType"],[vu.LEVEL,"level"],[vu.ROLE,"role"]]);var Iu=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf("Tag_Profile_Custom")?s.profileCustomField.push({key:e,value:t}):Su.has(e)&&(s[Su.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=>{s.push({tag:vu[e.toUpperCase()],value:t[e]})}),s}normalizeProfileFields(e){let r={};return e.forEach(e=>{var{tag:t,value:s}=e;if(Su.has(t)){let e=Su.get(t);r[e]=s}}),r}};let Eu=k.common["generateProtocolData"];function Cu(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:g(),UserItem:[]};r.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:r,UserProfileItem:n}=i,o=[];return n.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:n,ProfileItem:i}=e,i=Iu.parseProfileItem(i);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:n,profileItem:i})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:o}}})}function Mu(e){return rl.getFriendMap().has(e)}let yu=k.utils["isEmpty"];class Ou{init(){ll({apiName:"getMyProfile",context:this}),ll({apiName:"getUserProfile",context:this}),ll({apiName:"updateMyProfile",context:this}),this.createProfile=Iu.createProfile.bind(Iu);var e=k["notificationCenter"];h.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.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 I(this,void 0,void 0,function*(){let t=k.ssoLog.createSSOLogData({method:"getMyProfile"});try{var s=g(),r=yield Cu([s]);if(r){let e=this._handleProfileFormResponse(r)[0];return rl.getUserProfileMap().set(s,e),{code:0,data:e}}t.end()}catch(e){var{errorCode:r,errorInfo:s}=e,r=new _({functionName:"getMyProfile",code:r,message:s});throw t.setError(r).end(),e}})}getUserProfile(l){return I(this,void 0,void 0,function*(){var n=k.ssoLog.createSSOLogData({method:"getUserProfile"});try{let e=l["userIDList"],{userIdListToRequest:t,userIdListToCache:s}=(100<e.length&&(e=e.slice(0,100)),this._filterRequestAndCacheUsers(e)),r=[];s.forEach(e=>{e=rl.getUserProfile(e);r.push(e)});var i="userIDList.length:"+e.length;if(0===t.length)return n.setLogInfo({message:i}).end(),{code:0,data:r};var o=yield Cu(t);if(o){let e=this._handleProfileFormResponse(o);e.forEach(e=>{Mu(e.userID)&&rl.getUserProfileMap().set(e.userID,e)});var a=e.concat(r);return n.setLogInfo({message:i}).end(),{code:0,data:a}}}catch(e){o=e["errorCode"],i=new _({functionName:"getUserProfile",code:o});throw n.setError(i).end(),i}})}getMyProfileCacheThenServer(){return I(this,void 0,void 0,function*(){var e=g(),e=rl.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return I(this,void 0,void 0,function*(){let n=k.ssoLog.createSSOLogData({method:"updateMyProfile"}),t=g(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);let r=Iu.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};n.setLogInfo({message:JSON.stringify(r)}),yield function(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Eu({servcmd:e,data:r}),s=""+t.head.seq+e,n=yield k.channel.sendPacket(t,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=n;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var i=rl.getUserProfile(t),o=i?Object.assign(Object.assign({},i),s):Iu.createProfile(t,r);return function t(s,r,n){let i=n||[];var e,o;return!(!s||!r)&&(e=Object.keys(s).filter(e=>!i.includes(e)),o=Object.keys(r).filter(e=>!i.includes(e)),e.length===o.length)&&e.every(e=>!!r.hasOwnProperty(e)&&("object"==typeof s[e]&&null!==s[e]?t(s[e],r[e],n):s[e]===r[e]))}(i,o,["lastUpdatedTime","profileCustomField"])||k.notificationCenter.emitOuterEvent(u.PROFILE_UPDATED,{name:u.PROFILE_UPDATED,data:[o]}),o.lastUpdatedTime=Date.now(),rl.getUserProfileMap().set(t,o),n.end(),{code:0,data:o}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new _({functionName:"updateMyProfile",code:t,message:s});throw n.setError(r).end(),r}})}updateMyNickAndAvatar(n){return I(this,void 0,void 0,function*(){var e=g(),t=Date.now(),s=rl.getUserProfile(e),r={};(r=s?Object.assign(s,n):Iu.createProfile(e,n)).lastUpdatedTime=t,rl.getUserProfileMap().set(e,r)})}_onProfileDataModify(r){var e,t=function(){var{Profile_Account:e,PushType:t,ProfileList:s}=r.ProfileDataMod[0];return{userId:e,pushType:t,profileList:Iu.parseProfileList(s)}}();yu(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&(k.notificationCenter.emitInnerEvent(d.PROFILE_UPDATE,{name:d.PROFILE_UPDATE,data:[e]}),k.notificationCenter.emitOuterEvent(u.PROFILE_UPDATED,{name:u.PROFILE_UPDATED,data:[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,r=rl.getUserProfile(t);if(!r||!Mu(t))return{isProfileUpdated:!1,profile:null};let n=Iu.normalizeProfileFields(s),i=Object.keys(n).some(e=>r[e]!==n[e]);return i?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),n),{lastUpdatedTime:e}),rl.getUserProfileMap().set(t,e),el.updateConversation("C2C"+t,{userProfile:e}),{isProfileUpdated:i,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=rl.getUserProfileMap().has(e);(Mu(e)&&t?r:s).push(e)}),{userIdListToRequest:s,userIdListToCache:r}}_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=Iu.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_reset(){rl.getUserProfileMap().clear()}}var Tu,Au,Ru,N,G,Du=new Map,bu=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=bu.length;e<t;e++)Du.set(e,bu[e]);function Lu(e){if(!e)return"";var n=String(e).replace(/[=]+$/,"");let i="";if(n.length%4==1)return"";for(let e,t,s=0,r=0;t=n.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(i+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(i))}catch(e){return console.warn(e),""}}let Nu=k.utils["isEmpty"],Gu=k.common["generateProtocolData"];function Pu(n){return I(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=Gu({servcmd:s,data:{To_Account:n}}),s=r.head.seq+s,r=yield k.channel.sendPacket(r,{requestId:s});if(r)return{ErrorCode:s,ErrorInfo:r,ErrorList:e=[],UserStatusList:t=[]}=r,{errorCode:s,errorInfo:r,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:Lu(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:Nu(t)?e:t,code:s,message:r}})}})}class wu{constructor(){this._customStatus=""}init(){var e=k["notificationCenter"];ll({apiName:"getUserStatus",context:this}),ll({apiName:"setSelfStatus",context:this}),ll({apiName:"subscribeUserStatus",context:this}),ll({apiName:"unsubscribeUserStatus",context:this}),h.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,a.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 I(this,void 0,void 0,function*(){let n=k.ssoLog.createSSOLogData({method:"setSelfStatus"}),e=g(),t=s["customStatus"];try{return yield function(n){return I(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=Gu({servcmd:e,data:{CustomStatus:n}}),s=""+t.head.seq+e,r=yield k.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,n.setLogInfo({message:"customStatus: "+t}).end(),{code:0,data:{userID:e,statusType:1,customStatus:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new _({functionName:"setSelfStatus",code:t,message:s});throw n.setError(r).end(),r}})}getUserStatus(s){return I(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=Lu(e);this._customStatus=e}subscribeUserStatus(r){return I(this,void 0,void 0,function*(){try{console.log("User subscribeUserStatus options: ",r);var{userIDList:e=[]}=r,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_subscribe",s=Gu({servcmd:t,data:{To_Account:r}}),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(r){return I(this,void 0,void 0,function*(){try{console.log("User unsubscribeUserStatus options: ",r),this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=r,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=Gu({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:Lu(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=Lu(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:g(),statusType:1,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){k.notificationCenter.emitOuterEvent(u.USER_STATUS_UPDATED,{name:u.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){var{ErrorList:e=[]}=e;return e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:k.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!k.store.get("commercialConfig").get("USER_STATUS"))throw new _({functionName:e,code:Zt.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:g(),statusType:1,customStatus:this._customStatus});return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(n){return I(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:r,failureUserList:e}=(yield Pu(this._sliceUserIDList(n,s)))||{};return t.end(),{code:0,data:{successUserList:r,failureUserList:e}}}catch(e){s=e["errorCode"],r=new _({functionName:"getUserStatus",code:s});throw t.setError(r).end(),r}})}_isOnlyMeInArray(e){var t=g();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}},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 wu,this.userProfile.init(),this.userStatus.init(),vs({auth:ku,params:Uu})}}function qu(t){var s=[];if(Y(t)){var r=t.length;if(0!==r)for(let e=r-1;0<=e;e--)"1"===t[e]&&s.push(2**(r-e-1))}return s}(i=Tu=Tu||{}).NOT_START="notStart",i.PENDING="pending",i.RESOLVED="resolved",i.REJECTED="rejected",(G=Au=Au||{})[G.C2C=1]="C2C",G[G.GROUP=2]="GROUP",(N=Ru=Ru||{})[N.C2C=8]="C2C",N[N.GROUP=2]="GROUP";class xu{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Tu.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=k["notificationCenter"];h.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,a.CONVERSATION_RECOVER,this._syncConversationList,this),h.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.CONVERSATION_LIST_SYNC,this._syncConversationList,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this),console.log(this._name+".init")}isSyncCompleted(){return this._pagingStatus===Tu.RESOLVED}_syncConversationList(){return I(this,void 0,void 0,function*(){let e=k["ssoLog"],t=e.createSSOLogData({method:"syncConversationList"});try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=Tu.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:r}=e,s=new _({functionName:"syncConversationList",code:s,message:r});t.setError(s).end(),console.error(this._name+"._syncConversationList fail:",s)}})}_pagingGetConversationList(c){return I(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=Tu.PENDING,yield function(i){return I(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:n}=i;return Os({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:n,TopTimeStamp:r}})})}({fromAccount:g(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:n=[],TimeStamp:i,StartIndex:o,TopTimeStamp:a,TopStartIndex:l}=s||{};if(0<n.length){let e=this._getConversationOptions(n);t.push(...e);var u=k["notificationCenter"];u.emitInnerEvent(d.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=i,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=l,1!==r&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw 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===Au.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===Au.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===g()&&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="",r=null;return e.MsgBody&&(s=null==(t=e.MsgBody[0])?void 0:t.MsgType,r=this._parseContent(s,e.MsgBody[0])),{event:e.Event,elements:[{type:s,content:r,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 S(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=Tu.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.4.0"),{create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:n="",oversea:i=!1}=e;if("number"!=typeof e&&(o=Number(e),Number.isNaN(o)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(e=Number(e),Is.has(e))return Is.get(e);var o=""+(a()+a())+a()+a()+a()+a()+a()+a();function a(){return(65536*(1+Math.random())|0).toString(16).substring(1)}k.init({sdkAppId:e,instanceId:o,testEnv:t,devMode:s,unlimitedAVChatRoom:r,scene:n,sdkEdition:Ha,oversea:i}),h.init(),k.message=new _u,k.user=new Fu,k.login=new Tl,k.conversation=new Vu,fs.installBuiltInPlugin(Wa);t=il;return Is.set(e,t),t},TSignaling:Ft,EVENT:u,VERSION:nt,TYPES:C}});