@tencentcloud/lite-chat 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ class e{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,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 o=(...e)=>{s.apply(r,e),this.off(t,o)};this.on(t,o)}}let t={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},s=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var o;!function(e){e[e.CONV_DELETED=1]="CONV_DELETED",e[e.CONV_PINED=2]="CONV_PINED",e[e.CONV_UNPINED=3]="CONV_UNPINED",e[e.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",e[e.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",e[e.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",e[e.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED"}(o=o||{});var n,c,i=Object.freeze({__proto__:null,get ConvModifyPushType(){return o},ENUM_PLATFORM:t,IS_TOPIC_MESSAGE:2,NOT_NEED_CRC_SERVCMD:s});function r(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}!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="c2c_realtime_message",e.C2C_MESSAGE_MODIFIED="c2c_message_modified",e.C2C_REVOKED_MESSAGE="c2c_message_revoked",e.GROUP_REALTIME_MESSAGE="group_realtime_message",e.GROUP_MESSAGE_MODIFIED="group_message_modified",e.GROUP_MESSAGE_REVOKED="group_message_revoked",e.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",e.MESSAGE_REACTION_UPDATED="message_reaction_updated",e.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",e.GROUP_AT_TIPS="group_at_tips",e.USER_STATUS_UPDATE="user_status_update",e.FRIEND_LIST_MODIFIED="friend_list_modified",e.PROFILE_MODIFIED="profile_modified",e.CONV_MODIFIED="conversation_modified",e.GROUP_TIPS_NOTIFICATION="group_tips_notification",e.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",e.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",e.GROUP_SYSTEM_NOTIFICATION="group_system_notification",e.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",e.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",e.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",e.FOLLOW_LIST_UPDATED="follow_list_updated",e.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",e.ALL_MESSAGE_READ="all_message_read",e.CONVERSATION_MARK_UPDATED="conversation_mark_updated",e.CONVERSATION_GROUP_ADD="conversation_group_add",e.CONVERSATION_GROUP_DELETED="conversation_group_deleted",e.CONVERSATION_GROUP_UPDATED="conversation_group_updated",e.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",e.TOPIC_AT_TIPS="topic_at_tips",e.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",e.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",e.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",e.TOPIC_LATEST_MESSAGE="topic_latest_message"}(n=n||{});let a=[{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:r},{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:r},{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 o.CONV_MARK_UPDATED:s.push(n.CONVERSATION_MARK_UPDATED);break;case o.CONV_GROUP_ADDED:s.push(n.CONVERSATION_GROUP_ADD);break;case o.CONV_GROUP_DELETED:s.push(n.CONVERSATION_GROUP_DELETED);break;case o.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 u(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],o=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=a.find(e=>e.conditions.every(e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}));if(!e)return null;let s=[];"function"==typeof e.subTypeParser?s=e.subTypeParser(t):e.subType&&(s=e.subType),Array.isArray(s)?s.forEach(e=>{o.push({type:c.SERVER_PUSH_MESSAGE+":"+e,data:t})}):o.push({type:c.SERVER_PUSH_MESSAGE+":"+s,data:t})}),o}!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",e.ERROR="error"}(c=c||{});let l={[c.SERVER_PUSH_MESSAGE]:u,[c.SERVER_PUSH_MESSAGE_MULTIPLE]:u,[c.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},d=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=n}subscribeInnerEvent(s,r,o,n){var i,t;if(["string","number"].includes(typeof r)){let e=r,t=o;null!=(i=this._innerEventEmitter)&&i.on(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,o)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(l).includes(t)){let e=null==(t=l[t])?void 0:t.call(l,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,r,o,n){var i,t;if(["string","number"].includes(typeof r)){let e=r,t=o;null!=(i=this._innerEventEmitter)&&i.off(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,o)}}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 p(e,t){var s={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(s[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(s[o[r]]=e[o[r]]);return s}function h(e,i,a,l){return new(a=a||Promise)(function(s,t){function r(e){try{n(l.next(e))}catch(e){t(e)}}function o(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,o)}n((l=l.apply(e,i||[])).next())})}let _=e=>void 0===e,g=e=>"string"==typeof e,m=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[1].toLowerCase()},v=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===m(e),f=e=>null!==e&&"object"==typeof e,I=e=>v(e)||f(e),S=e=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},E=e=>{if("object"!=typeof e||null===e)return!1;e=Object.getPrototypeOf(e);if(null===e)return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return e===t};function C(e=99999999){return Math.round(Math.random()*e)}let M=(s,r,o,n)=>{if(!I(s)||!I(r))return 0;let i=0;var a,l=Object.keys(r);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!(_(r[a])||o&&o.includes(a)))if(I(s[a])&&I(r[a]))i+=M(s[a],r[a],o,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],i+=1)}return i};function y(s){let r,o,n=s,i="";for(let e=0,t=(n=s.length%8!=0?"0".repeat(8-s.length%8)+s:n)["length"];e<t;e+=8)r=parseInt(n.slice(e,e+4),2),o=parseInt(n.slice(e+4,e+8),2),i+=base16Map.get(r)+base16Map.get(o);return i}let T="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),A="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||T,O=A&&"function"==typeof wx.createGamePortal,D="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),R="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),L="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),b="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,G="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,w=A&&"object"==typeof wx.miniapp,P="undefined"!=typeof uni,U=A||D||R||L||N||G||b,k="undefined"==typeof window&&!U&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,F="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),$="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),q="undefined"!=typeof uni?!U:"undefined"!=typeof window&&!U&&!F,x=D?qq:R?tt:L?swan:N?my:A?wx:G?uni:b?jd:{},V=q&&window&&window.navigator&&window.navigator.userAgent||"",B=/(micromessenger|webbrowser)/i.test(V),j=function(){let e="WEB";return B?e="WEB":D?e="QQ_MP":R?e="TT_MP":L?e="BAIDU_MP":N?e="ALI_MP":A?e=w?"DONUT_NATIVE_APP":"WX_MP":G?e="UNI_NATIVE_APP":k?e="NS_NATIVE_APP":F&&(e="RN_NATIVE_APP"),t[e]}(),K=/iPad/i.test(V),W=/iPhone/i.test(V)&&!K,H=/iPod/i.test(V),Y=W||K||H,z=function(){var e=V.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),J=/Android/i.test(V),Q=function(){var e,t,s=V.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);return s?(e=s[1]&&parseFloat(s[1]),t=s[2]&&parseFloat(s[2]),e&&t?parseFloat(s[1]+"."+s[2]):e||null):null}(),X=/Firefox/i.test(V),Z=/Edge/i.test(V),ee=!Z&&/Chrome/i.test(V),te=/MSIE/.test(V)||-1<V.indexOf("Trident")&&-1<V.indexOf("rv:11.0"),se=function(){var e=/MSIE\s(\d+)\.\d/.exec(V);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(V)&&/rv:11.0/.test(V)?11:t}(),oe=/Safari/i.test(V)&&!ee&&!J&&!Z,ne=/Windows/i.test(V),ie=/MAC OS X/i.test(V),re=q&&"undefined"!=typeof Worker&&!te,ae=J||Y,ce=q&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ue=function(){var e;return"undefined"!=typeof window&&void 0!==window.navigator&&(e=window.navigator["standalone"],!(!Y||e||oe))}();function le(){let e="unknown";if(ie&&(e="mac"),ne&&(e="windows"),Y&&(e="ios"),J&&(e="android"),U)try{var t=wx.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}let de=2800,pe=2801,he=3e3,_e="application/x-www-form-urlencoded;charset=UTF-8";function ge(e){return h(this,arguments,void 0,function*({method:o,url:n,data:i,timeout:a=he}){return new Promise(U?(t,e)=>{x.request({url:n,data:i,method:o,timeout:a,header:{"content-type":_e},success:e=>t(e.data),fail:()=>e(new Error(`{"message":"Network error","code":${de}}`))})}:(t,e)=>{let s=new XMLHttpRequest,r=setTimeout(()=>{s.abort(),e(new Error(`{"message":"Request timeout","code":${pe}}`))},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":${de}}`))},s.open(o,n,!0),s.setRequestHeader("Content-type",_e),s.send(i||null)})})}function me(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(E(e)){for(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 ve(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(ve(t),ve(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(ve(e))}),t}if(Array.isArray(r))return r.map(e=>ve(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]=ve(r[e]))}),s}function fe(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var Ie=Object.freeze({__proto__:null,ANDROID_VERSION:Q,IE_VERSION:se,IN_ALIPAY_MINI_APP:N,IN_BAIDU_MINI_APP:L,IN_BROWSER:q,IN_DONUT_NATIVE_APP:w,IN_JD_MINI_APP:b,IN_MINI_APP:U,IN_NS_NATIVE_APP:k,IN_QQ_MINI_APP:D,IN_RN_APP:F,IN_TT_MINI_APP:R,IN_UNI_APP:P,IN_UNI_NATIVE_APP:G,IN_WX_MINI_APP:A,IN_WX_MINI_APP_DESK:T,IN_WX_MINI_GAME:O,IN_WX_MINI_PLUGIN:$,IOS_VERSION:z,IS_ANDROID:J,IS_CHROME:ee,IS_EDGE:Z,IS_FIREFOX:X,IS_IE:te,IS_IOS:Y,IS_IPAD:K,IS_IPHONE:W,IS_IPOD:H,IS_MAC:ie,IS_SAFARI:oe,IS_WECHAT:B,IS_WIN:ne,IS_WORKER_AVAILABLE:re,MINI_APP_NAMESPACE:x,USER_AGENT:V,base16EncodeBinaryString:y,deepCopyWithMethods:ve,deepMerge:M,generatePromise:fe,getPlatformType:le,getType:m,httpRequest:ge,isArray:v,isArrayOrObject:I,isEmpty:me,isFlutterWeb:ce,isH5:ae,isIOSWebView:ue,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:f,isPlainObject:E,isString:g,isUndefined:_,isValidRequestKey:S,platform:j,randomInt:C,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t}});class Se{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t;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:o}=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=o)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Ee{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:o}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=o}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}let Ce="CONNECT",Me="SEND",ye="DISCONNECT",Te="OPEN",Ae="MESSAGE",Oe="CLOSE",De="ERROR",Re="SEND_FAIL";class Le{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:Ce,url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:Me,data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:r,onClose:o,onError:n,onSendFail:i}=e;if(this._worker){let s={[Te]:t,[Ae]:r,[Oe]:o,[De]:n,[Re]:i};this._onSendFail=i,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:ye}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Ne,be=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return U?N?my.getStorageSync({key:e}).data:x.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){U?N?my.setStorageSync({key:e,data:JSON.stringify(t)}):x.setStorageSync(e,JSON.stringify(t)):this._canUseLocalStorage()&&localStorage.setItem(e,JSON.stringify(t))}clear(e){"string"==typeof e?this._store.set(e,{}):this._store.clear()}clearLocalStorage(e){this._canUseLocalStorage()&&("string"==typeof e?localStorage.setItem(e,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return"undefined"!=typeof window&&navigator&&navigator.cookieEnabled&&localStorage}};!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(Ne=Ne||{});class Ge{constructor(t){this._url="",this._readyState=Ne.DISCONNECTED,this._url=t,this._id=C(),this._emitter=new e,A?this._socket=new Ee:this._canUseWebWorker()?this._socket=new Le:this._socket=new Se,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Ne.CONNECTED,Ne.CONNECTING].includes(this._readyState)||(this._readyState=Ne.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Ne.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Ne.CONNECTED,Ne.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===Ne.CONNECTED}disconnect(){this._readyState=Ne.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Ne.CONNECTING&&(this._readyState=Ne.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Ne.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Ne.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Ne.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=be.get("cloudConfig")||{};return(_(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&re}}let we="CHINA",Pe="SINGAPORE",Ue="KOREA",ke="GERMANY",Fe="IND",$e="JPN",qe="USA",xe="INDONESIA",Ve={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"}}},Be={[Pe]:[[2e7,3e7],[172e7,173e7]],[Ue]:[[3e7,4e7],[173e7,174e7]],[ke]:[[4e7,5e7],[174e7,175e7]],[Fe]:[[5e7,6e7],[175e7,176e7]],[$e]:[[6e7,7e7],[176e7,177e7]],[qe]:[[7e7,8e7],[177e7,178e7]],[xe]:[[8e7,9e7],[178e7,179e7]]};function je(e){for(var t of Object.keys(Be))for(var[s,r]of Be[t])if(e>=s&&e<r)return t;return we}var Ke,We="1.3.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(Ke=Ke||{});let He=Ke.INITIAL;function Ye(){var e=Math.random();return 0===e?Ye():e}function ze(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:o}=be.get("instance"),n=Ye(),i=le(),a=function(){var e=le();let t=-1;return"ios"===e?t=z||-1:"android"===e&&(t=Q||-1),t}(),r=(s={sdkappid:r,instanceid:o,random:n,platform:j,host:i,version:a,sdkversion:We},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}var Je=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){var s=Date.now();this._timeOffsetWithServer=t+(s-e)-s}};let Qe=16;var Xe=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:o=Qe}=e,n=Math.max(o,Qe);return{id:e,nextExecuteTime:Date.now()+n,intervalMs:o,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 Ze(t){var s=[];for(let e=0;e<t.length;e+=1){var r,o=t.charCodeAt(e);55296<=o&&o<=56319?(r=t.charCodeAt(++e)-56320+(o-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):o<=127?s.push(o):o<=2047?s.push(192|o>>6,128|63&o):s.push(224|o>>12,128|o>>6&63,128|63&o)}return new Uint8Array(s)}function et(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&S(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=et(e[t]));return s}function st(e,t){if(s.includes(e))return 0;var r=Ze(JSON.stringify(t));let o=4294967295;var n=r["length"];for(let e=0;e<n;e++){o^=r[e];for(let e=0;e<8;e++)1&~o?o>>>=1:o=o>>>1^3988292384}return(4294967295^o)>>>0}function ot(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=be.get("login")||{},o=be.get("instance")||{},{servcmd:r,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:o.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,tjgID:"",seq:rt(),cs:0}),o=et(s);return r.cs=st(e,o),{head:r,body:o}}function nt(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=be.get("login")||{},o=be.get("instance")||{},{servcmd:r,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:o.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:rt(),cs:0}),o=et(s);return r.cs=st(e,o),{head:r,body:o}}let it=C();function rt(){return it=it<2415919103?it+1:C()}function at(){var e=be.get("login")||{},t=be.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:j,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var ct,pt,ut=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=be.get("login")||{},o=be.get("instance")||{},{servcmd:r,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:o.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:rt(),cs:0}),o=et(s);return r.cs=st(e,o),{head:r,body:o}},generateProtocolData:ot,generateSSOLogProtocolData:nt,generateSequence:rt,getCommonHead:at,taskScheduler:Xe,timeManager:Je});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(ct=ct||{});let lt={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 dt{constructor(e){this.level=ct.info,this._canSendLog=!0,this._logCreatedAt=Je.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+=Je.getTimeOffsetWithServer()}end(e=!1){var t;this._canSendLog&&(t=Je.getServerTimeMs(),0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:`+t),e?(this._canSendLog=!1,this.timestamp=Je.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout(()=>{this._canSendLog=!1,this.timestamp=Je.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())},0))}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=be.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=ct.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(lt).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{lt[e]&&(t[lt[e]]=this[e])}),t}}!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(pt=pt||{});var ht=pt;let _t=20,gt=6e4,mt=[4,5,6],vt=[],ft=[],It="report-logger";var St=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=_t,this._maxThreshold=100,this._waitingTime=gt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,d.subscribeInnerEvent(ht.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Xe.addTask({id:It,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=_t,evt_rpt_waiting:t=gt,evt_rpt_level:s=mt,evt_rpt_sdkappid_bl:r=vt,evt_rpt_tinyid_wl:o=ft}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=o}createSSOLogData(e){var t=new dt(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 h(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||me((t={Header:at(),Event:t}).Header.user_id)||(e=(t=nt({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void qt.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(A){var s=null==(t=null==(e=wx.getAccountInfoSync)?void 0:e.call(wx))?void 0:t.miniProgram;if(s){let{appId:e,envVersion:t}=s;be.set("instance",{appId:e,envVersion:t})}}else q&&be.set("instance",{href:window.location.href})}_filterLogs(e){var t=(be.get("login")||{})["tinyID"],s=(be.get("instance")||{})["sdkAppId"];return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}reset(){console.log("SSO_LOG_MODULE.reset"),Xe.removeTask(It),d.unSubscribeInnerEvent(ht.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=_t,this._maxThreshold=100,this._waitingTime=gt,this._logQueue=[]}};let Et=15e3,Ct="Channel",Mt="channel_schedule_task",yt="channel_reconnect_task",Tt="connected",At="connecting",Ot="disconnected",Dt=500,Rt="network_status_change",Lt="activity_status_change",Nt="send_fail",bt="reconnect_failed",Gt="socket_error",wt="socket_close";function Pt(e){return(Pt="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 Ut(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 kt,Vt,Ft={exports:{}},$t=(kt||(Ft.exports=function s(r,o,n){function i(t,e){if(!o[t]){if(!r[t]){if(!e&&Ut)return Ut(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=o[t]={exports:{}};r[t][0].call(e.exports,function(e){return i(r[t][1][e]||e)},e,e.exports,s,r,o,n)}return o[t].exports}for(var a=Ut,e=0;e<n.length;e++)i(n[e]);return i}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,o=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var o=r.shift();if(o){if("object"!=Pt(o))throw new TypeError(o+"must be non-object");for(var n in o)t=o,s=n,Object.prototype.hasOwnProperty.call(t,s)&&(e[n]=o[n])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,o){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),o);else for(var n=0;n<r;n++)e[o+n]=t[s+n]},flattenChunks:function(e){for(var t,s,r,o,n=t=0,i=e.length;n<i;n++)t+=e[n].length;for(o=new Uint8Array(t),n=s=0,i=e.length;n<i;n++)r=e[n],o.set(r,s),s+=r.length;return o}}),n={arraySet:function(e,t,s,r,o){for(var n=0;n<r;n++)e[o+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,o)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(r)},{}],2:[function(e,t,s){var l=e("./common"),o=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var u=new l.Buf8(256),r=0;r<256;r++)u[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&n||!e.subarray&&o))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,o,n=e.length,i=0,a=0;a<n;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),i+=s<128?1:s<2048?2:s<65536?3:4;for(t=new l.Buf8(i),a=o=0;o<i;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[o++]=s:(s<2048?t[o++]=192|s>>>6:(s<65536?t[o++]=224|s>>>12:(t[o++]=240|s>>>18,t[o++]=128|s>>>12&63),t[o++]=128|s>>>6&63),t[o++]=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,o,n=t||e.length,i=new Array(2*n),a=s=0;a<n;)if((r=e[a++])<128)i[s++]=r;else if(4<(o=u[r]))i[s++]=65533,a+=o-1;else{for(r&=2===o?31:3===o?15:7;1<o&&a<n;)r=r<<6|63&e[a++],o--;1<o?i[s++]=65533:r<65536?i[s++]=r:(r-=65536,i[s++]=55296|r>>10&1023,i[s++]=56320|1023&r)}return c(i,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":kt=1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var o=65535&e,n=e>>>16&65535,i=0;0!==s;){for(s-=i=2e3<s?2e3:s;n=n+(o=o+t[r++]|0)|0,--i;);o%=65521,n%=65521}return o|n<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var o=a,n=r+s;e^=-1;for(var i=r;i<n;i++)e=e>>>8^o[255&(e^t[i])];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,o,n,i,a,l=e.state,u=e.next_in,c=e.input,d=u+(e.avail_in-5),h=e.next_out,p=e.output,_=h-(t-e.avail_out),g=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,I=l.wnext,S=l.window,E=l.hold,C=l.bits,M=l.lencode,y=l.distcode,A=(1<<l.lenbits)-1,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&A];;){if(E>>>=r=s>>>24,C-=r,0==(r=s>>>16&255))p[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(o=65535&s,(r&=15)&&(C<r&&(E+=c[u++]<<C,C+=8),o+=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(n=65535&s,C<(r&=15)&&(E+=c[u++]<<C,(C+=8)<r)&&(E+=c[u++]<<C,C+=8),m<(n+=E&(1<<r)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(E>>>=r,C-=r,(r=h-_)<n){if(f<(r=n-r)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=S,(i=0)===I){if(i+=v-r,r<o){for(o-=r;p[h++]=S[i++],--r;);i=h-n,a=p}}else if(I<r){if(i+=v+I-r,(r-=I)<o){for(o-=r;p[h++]=S[i++],--r;);if(i=0,I<o){for(o-=r=I;p[h++]=S[i++],--r;);i=h-n,a=p}}}else if(i+=I-r,r<o){for(o-=r;p[h++]=S[i++],--r;);i=h-n,a=p}for(;2<o;)p[h++]=a[i++],p[h++]=a[i++],p[h++]=a[i++],o-=3;o&&(p[h++]=a[i++],1<o)&&(p[h++]=a[i++])}else{for(i=h-n;p[h++]=p[i++],p[h++]=p[i++],p[h++]=p[i++],2<(o-=3););o&&(p[h++]=p[i++],1<o)&&(p[h++]=p[i++])}break}}break}}while(u<d&&h<g);u-=o=C>>3,E&=(1<<(C-=o<<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<g?g-h+257:257-(h-g),l.hold=E,l.bits=C}},{}],8:[function(e,t,s){var N=e("../utils/common"),b=e("./adler32"),G=e("./crc32"),w=e("./inffast"),P=e("./inftrees"),U=0,k=-2,F=1,r=852,o=592;function x(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function i(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=F,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new N.Buf32(r),t.distcode=t.distdyn=new N.Buf32(o),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,i(e)):k}function l(e,t){var s,r;return!e||!e.state||(r=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t))?k:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=s,r.wbits=t,a(e))}function u(e,t){var s;return e?(s=new n,(e.state=s).window=null,(s=l(e,t))!==U&&(e.state=null),s):k}var q,V,B=!0;function j(e,t,s,r){var o,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(o=e.wsize-e.wnext)&&(o=r),N.arraySet(e.window,t,s-r,o,e.wnext),(r-=o)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=o,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=o))),0}s.inflateReset=a,s.inflateReset2=l,s.inflateResetKeep=i,s.inflateInit=function(e){return u(e,15)},s.inflateInit2=u,s.inflate=function(e,t){var s,r,o,n,i,a,l,u,c,d,h,p,_,g,m,v,f,I,S,E,C,M,y,A,T=0,D=new N.Buf8(4),O=[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),i=e.next_out,o=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,d=a,h=l,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(2&s.wrap&&35615===u)D[s.check=0]=255&u,D[1]=u>>>8&255,s.check=G(s.check,D,2,0),c=u=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&u)<<8)+(u>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&u))e.msg="unknown compression method",s.mode=30;else{if(c-=4,C=8+(15&(u>>>=4)),0===s.wbits)s.wbits=C;else if(C>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<C,e.adler=s.check=1,s.mode=512&u?10:12,c=u=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(s.flags=u,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=u>>8&1),512&s.flags&&(D[0]=255&u,D[1]=u>>>8&255,s.check=G(s.check,D,2,0)),c=u=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.head&&(s.head.time=u),512&s.flags&&(D[0]=255&u,D[1]=u>>>8&255,D[2]=u>>>16&255,D[3]=u>>>24&255,s.check=G(s.check,D,4,0)),c=u=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.head&&(s.head.xflags=255&u,s.head.os=u>>8),512&s.flags&&(D[0]=255&u,D[1]=u>>>8&255,s.check=G(s.check,D,2,0)),c=u=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.length=u,s.head&&(s.head.extra_len=u),512&s.flags&&(D[0]=255&u,D[1]=u>>>8&255,s.check=G(s.check,D,2,0)),c=u=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&((p=a<(p=s.length)?a:p)&&(s.head&&(C=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),N.arraySet(s.head.extra,r,n,p,C)),512&s.flags&&(s.check=G(s.check,r,p,n)),a-=p,n+=p,s.length-=p),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(p=0;C=r[n+p++],s.head&&C&&s.length<65536&&(s.head.name+=String.fromCharCode(C)),C&&p<a;);if(512&s.flags&&(s.check=G(s.check,r,p,n)),a-=p,n+=p,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(p=0;C=r[n+p++],s.head&&C&&s.length<65536&&(s.head.comment+=String.fromCharCode(C)),C&&p<a;);if(512&s.flags&&(s.check=G(s.check,r,p,n)),a-=p,n+=p,C)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=u=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}e.adler=s.check=x(u),c=u=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=i,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last)u>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:R=L=void 0;var R,L=s;if(B){for(q=new N.Buf32(512),V=new N.Buf32(32),R=0;R<144;)L.lens[R++]=8;for(;R<256;)L.lens[R++]=9;for(;R<280;)L.lens[R++]=7;for(;R<288;)L.lens[R++]=8;for(P(1,L.lens,0,288,q,0,L.work,{bits:9}),R=0;R<32;)L.lens[R++]=5;P(2,L.lens,0,32,V,0,L.work,{bits:5}),B=!1}if(L.lencode=q,L.lenbits=9,L.distcode=V,L.distbits=5,s.mode=20,6!==t)break;u>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}u>>>=2,c-=2}break;case 14:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if((65535&u)!=(u>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&u,c=u=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(p=s.length){if(0===(p=l<(p=a<p?a:p)?l:p))break e;N.arraySet(o,r,n,p,i),a-=p,n+=p,l-=p,i+=p,s.length-=p}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(s.nlen=257+(31&u),u>>>=5,c-=5,s.ndist=1+(31&u),u>>>=5,c-=5,s.ncode=4+(15&u),u>>>=4,c-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;c<3;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.lens[O[s.have++]]=7&u,u>>>=3,c-=3}for(;s.have<19;)s.lens[O[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=(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[n++]<<c,c+=8}if(f<16)u>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(A=m+2;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}C=s.lens[s.have-1],p=3+(3&u),u>>>=2,c-=2}else if(17===f){for(A=m+3;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}C=0,p=3+(7&(u>>>=m)),u>>>=3,c=c-m-3}else{for(A=m+7;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}C=0,p=11+(127&(u>>>=m)),u>>>=7,c=c-m-7}if(s.have+p>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;p--;)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=i,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,w(e,h),i=e.next_out,o=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(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[n++]<<c,c+=8}if(v&&!(240&v)){for(I=m,S=v,E=f;v=(T=s.lencode[E+((u&(1<<I+S)-1)>>I)])>>>16&255,f=65535&T,!(I+(m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,s.length=f,0===v){s.mode=26;break}if(32&v){s.back=-1,s.mode=12;break}if(64&v){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&v,s.mode=22;case 22:if(s.extra){for(A=s.extra;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.length+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(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[n++]<<c,c+=8}if(!(240&v)){for(I=m,S=v,E=f;v=(T=s.distcode[E+((u&(1<<I+S)-1)>>I)])>>>16&255,f=65535&T,!(I+(m=T>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,64&v){e.msg="invalid distance code",s.mode=30;break}s.offset=f,s.extra=15&v,s.mode=24;case 24:if(s.extra){for(A=s.extra;c<A;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.offset+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===l)break e;if(s.offset>(p=h-l)){if((p=s.offset-p)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}_=p>s.wnext?(p-=s.wnext,s.wsize-p):s.wnext-p,p>s.length&&(p=s.length),g=s.window}else g=o,_=i-s.offset,p=s.length;for(l-=p=l<p?l:p,s.length-=p;o[i++]=g[_++],--p;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;o[i++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[n++]<<c,c+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?G:b)(s.check,o,h,i-h)),h=l,(s.flags?u:x(u))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=u=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}c=u=0}s.mode=29;case 29:M=1;break e;case 30:M=-3;break e;case 31:return-4;default:return k}return e.next_out=i,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,(s.wsize||h!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&j(e,e.output,e.next_out,h-e.avail_out)?(s.mode=31,-4):(d-=e.avail_in,h-=e.avail_out,e.total_in+=d,e.total_out+=h,s.total+=h,s.wrap&&h&&(e.adler=s.check=(s.flags?G:b)(s.check,o,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&&b(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 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,r,o,n,i,a){for(var l,u,c,d,h,p,_,g,m,v=a.bits,f=0,I=0,S=0,E=0,C=0,M=0,y=0,A=0,T=0,D=0,O=null,R=0,L=new w.Buf16(16),N=new w.Buf16(16),b=null,G=0,f=0;f<=15;f++)L[f]=0;for(I=0;I<r;I++)L[t[s+I]]++;for(C=v,E=15;1<=E&&0===L[E];E--);if(E<C&&(C=E),0===E)o[n++]=20971520,o[n++]=20971520,a.bits=1;else{for(S=1;S<E&&0===L[S];S++);for(C<S&&(C=S),f=A=1;f<=15;f++)if((A=(A<<1)-L[f])<0)return-1;if(0<A&&(0===e||1!==E))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+L[f];for(I=0;I<r;I++)0!==t[s+I]&&(i[N[t[s+I]]++]=I);if(p=0===e?(O=b=i,19):1===e?(O=P,R-=257,b=U,G-=257,256):(O=k,b=F,-1),f=S,h=n,y=I=D=0,c=-1,d=(T=1<<(M=C))-1,1===e&&852<T||2===e&&592<T)return 1;for(;;){for(m=i[I]<p?(g=0,i[I]):i[I]>p?(g=b[G+i[I]],O[R+i[I]]):(g=96,0),l=1<<(_=f-y),S=u=1<<M;o[h+(D>>y)+(u-=l)]=_<<24|g<<16|m,0!==u;);for(l=1<<f-1;D&l;)l>>=1;if(0!==l?D=(D&l-1)+l:D=0,I++,0==--L[f]){if(f===E)break;f=t[s+i[I]]}if(C<f&&(D&d)!==c){for(h+=S,A=1<<(M=f-(y=0===y?C:y));M+y<E&&!((A-=L[M+y])<=0);)M++,A<<=1;if(T+=1<<M,1===e&&852<T||2===e&&592<T)return 1;o[c=D&d]=C<<24|M<<16|h-n}}0!==D&&(o[h+D]=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"),p=e("./utils/strings"),_=e("./zlib/constants"),r=e("./zlib/messages"),o=e("./zlib/zstream"),n=e("./zlib/gzheader"),g=Object.prototype.toString;function i(e){if(!(this instanceof i))return new i(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 o,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==_.Z_OK)throw new Error(r[e]);if(this.header=new n,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=p.string2buf(t.dictionary):"[object ArrayBuffer]"===g.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==_.Z_OK)throw new Error(r[e])}function a(e,t){t=new i(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}i.prototype.push=function(e,t){var s,r,o,n,i,a=this.strm,l=this.options.chunkSize,u=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?_.Z_FINISH:_.Z_NO_FLUSH,"string"==typeof e?a.input=p.binstring2buf(e):"[object ArrayBuffer]"===g.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||r!==_.Z_FINISH&&r!==_.Z_SYNC_FLUSH)||("string"===this.options.to?(o=p.utf8border(a.output,a.next_out),n=a.next_out-o,i=p.buf2string(a.output,o),a.next_out=n,a.avail_out=l-n,n&&h.arraySet(a.output,a.output,o,n,0),this.onData(i)):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(r=s===_.Z_STREAM_END?_.Z_FINISH:r)===_.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===_.Z_OK):r!==_.Z_SYNC_FLUSH||(this.onEnd(_.Z_OK),!(a.avail_out=0))},i.prototype.onData=function(e){this.chunks.push(e)},i.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=i,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")),Ft.exports),qt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=Dt,this._currentConnectState=Tt,this._beforeSendInterceptors=[]}init(){Xe.addTask({id:Mt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s}=be.get("instance"),r=je(t);return ze(s?Ve.TEST[r].DEFAULT:Ve.PRODUCTION[r].INITIAL.replace("*",""+t),{isBinary:e})}(this._isBinarySupported),d.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),d.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:o=Et,canResend:n=!0}=t||{};if(me(e))return console.warn(Ct+".sendPacket: packet is empty ",e),null;this._executeBeforeSendInterceptors(e);var i=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=fe();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:i,timeout:o,canResend:n})}t=this._isBinarySupported?Ze(i).buffer:i;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new Ge(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=Ct+`.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=Ct+".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(Ct+".dispose"),Xe.removeTask(Mt),Xe.removeTask(yt),d.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),d.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=Dt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(var t of this._beforeSendInterceptors){var{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){var e=this._currentConnectState===At&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return h(this,void 0,void 0,function*(){var e=`${Ct} 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}=be.get("instance"),t=je(t);if(s)return ze(Ve.TEST[t].DEFAULT,{isBinary:e});let r=Ve.PRODUCTION[t],o=q&&r.ANYCAST;return ze({[Ke.INITIAL]:()=>(He=Ke.DEFAULT,r.DEFAULT),[Ke.DEFAULT]:()=>(He=Ke.BACKUP,r.BACKUP),[Ke.BACKUP]:()=>(He=o?Ke.ANYCAST:Ke.DEFAULT,o?r.ANYCAST:r.DEFAULT),[Ke.ANYCAST]:()=>(He=Ke.DEFAULT,r.ANYCAST="",r.DEFAULT)}[He](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Ot,reason:bt}),console.warn(Ct+" 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=`${Ct} 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:Ot,reason:wt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=`${Ct} 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:Ot,reason:Gt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},t=`${Ct} 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:Ot,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=$t.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var o=new Uint8Array(e);let n="",i=0;for(var a=o["length"];i<a;){let t=o[i],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-i-s)for(let e=0;e<s;e+=1)t=o[i+e+1],r=r<<6|63&t;else r=65533,s=a-i;n+=String.fromCodePoint(r),i+=s+1}return n})(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:o,ErrorCode:r=r,ErrorInfo:o=o}=(null==e?void 0:e.body)||{},t=""+t+s,{resolve:s,reject:n}=this._pendingRequests.get(t);this._pendingRequests.delete(t),r&&0!==r?(d.emitInnerEvent("error",{errorCode:r,errorInfo:o}),n({errorCode:r,errorInfo:o})):s(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),d.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${Ct}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:o,reject:n,timeout:i}=e;if(r){this._pendingRequests.set(t,{resolve:o,reject:n,timestamp:Date.now(),uplinkData:s,timeout:i,canResend:r});let e=this._isBinarySupported?Ze(s).buffer:s;null!=(o=this._socketAdapter)&&o.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=Ct+` 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=Ct+" reconnect success";this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),d.emitInnerEvent(ht.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Tt})}_sendAck(e){e=ot({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return h(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 h(this,void 0,void 0,function*(){var e,t=ot({servcmd:"heartbeat.alive",data:{}});try{let e=""+t.head.seq+t.head.servcmd;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){var s=null==(e=be.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=Ct+` sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:Ot,reason:Nt})}})}_sendHeartbeatIfReady(){return h(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=G?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=Ct+" networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t),e);t&&"none"!==e?this._handleConnectStateChange({state:Tt,reason:Rt}):this._handleConnectStateChange({state:Ot,reason:Rt})}isPrivateNetWork(){var e=be.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:t,reason:s}=e;if(this._currentConnectState!==t){let e=`${Ct}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: `+s;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,d.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===Ot&&d.emitInnerEvent(ht.SOCKET_DISCONNECTED),t!==Ot&&t!==Tt||(this._resetReconnectDelay(),Xe.addTask({id:yt,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=`${Ct} activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),console.warn(e),3===t&&this._handleConnectStateChange({state:Ot,reason:Lt})}_resetReconnectDelay(){Xe.removeTask(yt);var e=null==(e=be.get("activityMonitor"))?void 0:e.isActive;this._intendedDelay=e?Dt:1e3}_scheduleReconnectWithBackoff(){var e=null==(e=be.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(Dt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=Ct+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;this._ssoLog({method:"scheduleReconnectWithBackoff",message:e}),console.log(e),this.reconnect(),Xe.updateTaskInterval(yt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;St.createSSOLogData({method:e}).setLogInfo({message:t}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){h(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 ge({method:"GET",url:e,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}})}(this._url),function(t){h(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 ge({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:pe,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=be.get("instance"))&&e.devMode||(e=le(),N)||A&&"windows"===e||G)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let xt={init:function(e){be.set("instance",e),qt.init()},destroy:function(){qt.dispose(),be.clear(),Xe.dispose()},notificationCenter:d,channel:qt,store:be,ssoLog:St,utils:Ie,common:ut,constants:i};!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated"}(Vt=Vt||{});var Bt,jt=Vt;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated",e.TOPIC_MESSAGE_DELETED="topic_message_deleted",e.TOPIC_MESSAGE_REVOKED="topic_message_revoked",e.TOPIC_MESSAGE_MODIFIED="topic_message_modified",e.TOPIC_NEW_MESSAGE="topic_new_message",e.QUALITY_STAT="quality_stat"}(Bt=Bt||{});var Kt,Jt,Wt=Bt,Ht=(!function(e){e.NEW_INVITATION_RECEIVED="newInvitationReceived",e.INVITEE_ACCEPTED="ts_invitee_accepted",e.INVITEE_REJECTED="ts_invitee_rejected",e.INVITATION_CANCELLED="ts_invitation_cancelled",e.INVITATION_TIMEOUT="ts_invitation_timeout",e.INVITATION_MODIFIED="ts_invitation_modified"}(Kt=Kt||{}),Kt);let Yt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),zt={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=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Jt=Jt||{}),{modify:Wt.MESSAGE_MODIFIED,delete:Wt.MESSAGE_DELETED,revoke:Wt.MESSAGE_REVOKED}),Xt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zt),{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:Jt}),Zt={[Qt.modify]:Wt.TOPIC_MESSAGE_MODIFIED,[Qt.delete]:Wt.TOPIC_MESSAGE_DELETED,[Qt.revoke]:Wt.TOPIC_MESSAGE_REVOKED},es={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"},ts=Object.assign({},es),ss={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},os=Object.assign(Object.assign(Object.assign(Object.assign({},ss),{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"}),ns=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"}),is={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},rs={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},as=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},is),{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:rs}),cs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Yt),Xt),ts),os),ns),as),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),us={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},ls={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},ds={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message"},ps={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"},hs={[ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:ps.USER_STATUS_UPDATE},{stepId:ps.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:ps.UNREAD_MESSAGE_SYNC},{stepId:ps.CONVERSATION_RECOVER},{stepId:ps.HISTORY_MESSAGE_RECOVER,dependency:ps.CONVERSATION_RECOVER},{stepId:ps.BLACKLIST_RECOVER},{stepId:ps.FRIEND_RECOVER},{stepId:ps.GROUP_REVOKED_NOTICE_RECOVER},{stepId:ps.TOPIC_REQUEST_INFO_RESET},{stepId:ps.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:ps.UNREAD_MESSAGE_SYNC},{stepId:ps.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:ps.UNREAD_MESSAGE_SYNC},{stepId:ps.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ps.UNREAD_MESSAGE_SYNC,ps.CONVERSATION_RECOVER]},{stepId:ps.EMIT_C2C_MESSAGE_EVENT,dependency:[ps.UNREAD_MESSAGE_SYNC,ps.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[ds.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:ps.COMMERCIAL_CONFIG_UPDATE},{stepId:ps.CLOUD_CONFIG_SYNC},{stepId:ps.USER_PROFILE_SYNC},{stepId:ps.UNREAD_MESSAGE_SYNC},{stepId:ps.FRIEND_AND_BLACKLIST_SYNC},{stepId:ps.GROUP_LIST_SYNC},{stepId:ps.CONVERSATION_LIST_SYNC},{stepId:ps.SIGNALING_MESSAGE_RECOVER,dependency:ps.UNREAD_MESSAGE_SYNC},{stepId:ps.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[ps.UNREAD_MESSAGE_SYNC]},{stepId:ps.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ps.UNREAD_MESSAGE_SYNC,ps.CONVERSATION_LIST_SYNC]},{stepId:ps.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[ps.GROUP_LIST_SYNC,ps.CONVERSATION_LIST_SYNC]},{stepId:ps.CONVERSATION_GROUP_LIST_SYNC},{stepId:ps.CONVERSATION_GROUP_UPDATE,dependency:[ps.CONVERSATION_LIST_SYNC,ps.CONVERSATION_GROUP_LIST_SYNC]},{stepId:ps.QUALITY_REPORT}],[ds.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:ps.HANDLE_C2C_NEW_MESSAGE},{stepId:ps.UNREAD_MESSAGE_SYNC},{stepId:ps.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:ps.HANDLE_C2C_NEW_MESSAGE},{stepId:ps.EMIT_C2C_MESSAGE_EVENT,dependency:[ps.HANDLE_C2C_NEW_MESSAGE,ps.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:ps.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ps.UNREAD_MESSAGE_SYNC]}],[ds.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:ps.HANDLE_GROUP_NEW_MESSAGE},{stepId:ps.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:ps.HANDLE_GROUP_NEW_MESSAGE},{stepId:ps.UPDATE_GROUP_NEXT_SEQUENCE,dependency:ps.HANDLE_GROUP_NEW_MESSAGE},{stepId:ps.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:ps.HANDLE_GROUP_NEW_MESSAGE},{stepId:ps.EMIT_GROUP_MESSAGE_EVENT,dependency:[ps.HANDLE_GROUP_NEW_MESSAGE,ps.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},_s={REACT:"atomicx_react",VUE3:"atomicx_vue3"},gs={[_s.REACT+"_web"]:40,[_s.REACT+"_h5"]:41,[_s.VUE3+"_web"]:42,[_s.VUE3+"_h5"]:43},ms={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},vs={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var fs=Object.freeze({__proto__:null,ERROR_CODE:us,InnerEvent:Wt,OuterConstant:cs,OuterEvent:jt,QUALITY_METRICS:ms,SDK_EDITION:ls,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:vs,SignalingEvent:Ht,UIKIT_PREFIX:_s,UI_PLATFORM:gs,WORKFLOW_DEFINITIONS:hs,WORKFLOW_NAME:ds,WORKFLOW_STEP:ps});function Is(t){var s;try{var r=be.getStorage("errorMessage");if(!t||!r)return"";var o=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:n=!1,code:i,replacement1:a="",replacement2:l=""}=t;if(!i)return"";var u=n?i+"_en":i+"_cn";let e=o[o[u]?u:i]||"";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 Ss extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:o=""}=e;let n=r;s&&!r&&(n=Is(e));r=s?`${t} failed. error: {"message": ${n}, "code": ${s}}`:`${t} failed. error: {"message": ${n}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=o}}function Es(e,t){if(e&&!0!==(null==(e=xt.store.get("login"))?void 0:e.isLoggedIn))throw new Ss({code:us.USER_NOT_LOGGED_IN,functionName:t})}let Cs=e=>"function"==typeof e;function Ms(t,s,r){let o=r||[];var e,n;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!o.includes(e)),n=Object.keys(s).filter(e=>!o.includes(e)),e.length===n.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?Ms(t[e],s[e],r):t[e]===s[e]))}function ys(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)Ts.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)Ts.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function Ts({required:e,rules:r,value:t,allowEmpty:o,name:n,key:i,customValidator:a}){if(void 0===t){if(e)throw new Ss({functionName:n,message:`[${n}] Missing required params: "${i}"`})}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=`[${i}] 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 Ss({functionName:n,message:e})}if(!1===o){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new Ss({functionName:n,message:i+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new Ss({functionName:n,message:i+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new Ss({functionName:n,message:`[${i}] custom validation failed: `+(e||"Invalid value")})}}}let As=[],Os={},Ds={};function Rs(e,t){var s;Es(Os[e],e),ys(Ds[e],t,e),s=e,As.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function Ls(e,t){As.push({interceptor:e,context:t})}function Ns(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(Ds,e),t&&"object"==typeof t&&Object.assign(Os,t)}var bs=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=v(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),o=-1<r?s.splice(r,1):[];s.forEach(e=>{t.has(e)||(e&&Cs(e.install)?(t.add(e),Cs(e.getInstalledSubPlugins)?e.install(Sh(),o):e.install(Sh()),Cs(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Cs(e)?(t.add(e),e(Sh()),Cs(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=xt.store.get("login"))?void 0:e.isLoggedIn)}};function Gs(e){return xt.store.get("commercialConfig").get(e)}let ws=new Map;var Ps=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 o=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?o-t:0;this._stepStartTimes.delete(s+"-"+e),console.error(`[Workflow ${s}] Step ${e} failed at ${new Date(o).toISOString()} (${t}ms)`,r)}else{let e=this._workflowStartTimes.get(s),t=e?o-e:0;this._workflowStartTimes.delete(s),console.error(`[Workflow ${s}] failed at ${new Date(o).toISOString()} (${t}ms)`,r)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){this._handlers.has(e)?hs[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(i,s){return h(this,void 0,void 0,function*(){if(this._validateWorkflow(i)){console.log(`[Workflow ${i}] Started execution at `+(new Date).toISOString());let e=hs[i],n={cancelled:!1};this._activeWorkflows.set(i,{cancelToken:n});try{let t=new Map,o=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:i,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:n});yield new Promise((t,s)=>{let r=()=>{n.cancelled?t():this._getExecutableSteps({pendingSteps:o.pendingSteps,completedSteps:o.completedSteps,stepMap:o.stepMap,workflowName:i}).filter(e=>!o.runningSteps.has(e)).forEach(e=>{o.completedSteps.has(e)||o.runningSteps.has(e)||this._executeWorkflowStep(e,o,{onComplete:()=>{0===o.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:o.pendingSteps,completedSteps:o.completedSteps,stepMap:o.stepMap,workflowName:i}).filter(e=>!o.runningSteps.has(e)).length&&0===o.runningSteps.size&&(console.log(`Workflow ${i} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),console.log(`[Workflow ${i}] Completed execution at `+(new Date).toISOString())}catch(e){console.error(`[Workflow ${i}] Failed execution at `+(new Date).toISOString(),e)}finally{this._activeWorkflows.delete(i)}}})}_executeWorkflowStep(a,l,u){return h(this,void 0,void 0,function*(){let{workflowName:n,runningSteps:e,stepMap:s,stepResults:r,data:o}=l;e.add(a),this._logWorkflowExecution(n,a,"start");try{let e=s.get(a),t=null;null!=e&&e.dependency&&(g(e.dependency)?t=r[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=r[e]})));var i=this._handlers.get(n).get(a);if(i){let e=yield Promise.resolve(i({data:o,result:t}));r[a]=e,this._logWorkflowExecution(n,a,"success")}l.completedSteps.add(a)}catch(e){let t=`[Workflow].${n}.`+a,{errorCode:s,errorInfo:r=t+" failed"}=e||{},o=new Ss({functionName:t,code:s,message:r});xt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${n}, stepId: `+a}).setError(o).end(),this._logWorkflowExecution(n,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(hs).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(hs).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return hs[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:o}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=r.get(e)||{};if(!t)return!0;if(g(t))return this._isStepRegistered({workflowName:o,stepId:t})?s.has(t):!e;if(v(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:o,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 Us=({type:e,groupID:t})=>e===cs.GRP_COMMUNITY||(""+t).startsWith(rs.COMMUNITY)&&!(""+t).includes(rs.TOPIC),ks=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(rs.COMMUNITY)&&(""+e).includes(rs.TOPIC)},Fs="openim",$s="million_group_open_http_svc";function qs(s){return h(this,void 0,void 0,function*(){var{servcmd:e,data:t}=xs(e=s.data)||Vs(e)?function(e){let{servcmd:t,data:s}=e;var r,o,n;return Vs(s)?({servcmd:e,data:r}=e,{GroupId:o=""}=r,[o]=(n=o).split(rs.TOPIC),{servcmd:Bs(e),data:Object.assign(Object.assign({},r),{GroupId:o,TopicId:n})}):{servcmd:t=xs(s)?Bs(t):t,data:s}}(s):s,t=xt.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return xt.channel.sendPacket(t,{requestId:e})})}function xs(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return Us({type:e,groupID:t})}function Vs(e){var{GroupId:e=""}=e;return ks(e)}function Bs(e){return e.includes(Fs)?e:(e=e.split(".")[1],$s+"."+e)}function js(){var e;return null==(e=xt.store.get("login"))?void 0:e.userId}let Ks=e=>v(e)||f(e),Ws=(s,r,o,n)=>{if(!Ks(s)||!Ks(r))return 0;let i=0;var a,l=Object.keys(r);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!(_(r[a])||o&&o.includes(a)))if(Ks(s[a])&&Ks(r[a]))i+=Ws(s[a],r[a],o,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],i+=1)}return i},Hs=(e,t)=>{if(_(t))return"";switch(e){case cs.MSG_TEXT:return t.text||"";case cs.MSG_IMAGE:return"[Image]";case cs.MSG_LOCATION:return"[Location]";case cs.MSG_AUDIO:return"[Voice]";case cs.MSG_VIDEO:return"[Video]";case cs.MSG_FILE:return"[File]";case cs.MSG_CUSTOM:return"[Custom Messages]";case cs.MSG_GRP_TIP:return"[Group Notification]";case cs.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case cs.MSG_FACE:return"[Animated Sticker]";case cs.MSG_MERGER:return"[Chat Record]";default:return""}},Ys=[{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}],zs="im_sdk_config_mgr.fetch_config",Js="im_sdk_config_mgr.push_configv2",Qs="cloud-config",Xs=2996;var Zs=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:o},channel:n}=this._core=e;e.subscribeInnerEvent(Js,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,o.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(Ys),n.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:o}=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:o+=1}),t<o)throw new this._core.helper.ChatError({code:Xs,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_fetchCloudConfig(){return h(this,void 0,void 0,function*(){try{var e=(this._core.store.get("instance")||{})["sdkAppId"],t=this._core.helper.generateProtocolData({servcmd:zs,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=""+t.head.seq+zs;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 h(this,void 0,void 0,function*(){try{var e;this._canFetch()&&(e=yield this._fetchCloudConfig(),this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:Qs,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}})}_fetchCloudConfigIfReady(){return h(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:o}=e;let n=null;if(0===t){if(this._version!==o)try{n=JSON.parse(s),this._version=o}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return n}_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(Qs),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Ys),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Js,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class eo{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 to={SEARCH_GRP_SNS:new eo(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new eo(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new eo(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new eo(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new eo(0,Math.pow(2,6)).toString(),USER_STATUS:new eo(0,Math.pow(2,7)).toString(),CONV_MARK:new eo(0,Math.pow(2,9)).toString(),CONV_GROUP:new eo(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new eo(0,Math.pow(2,11)).toString(),MSG_EXT:new eo(0,Math.pow(2,13)).toString(),GRP_COUNTER:new eo(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new eo(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new eo(Math.pow(2,7)).toString(),PLUGIN_CS:new eo(Math.pow(2,8)).toString(),PLUGIN_PUSH:new eo(Math.pow(2,9)).toString(),PLUGIN_BOT:new eo(Math.pow(2,10)).toString(),MSG_REACTION:new eo(Math.pow(2,16)).toString(),FOLLOW:new eo(Math.pow(2,20)).toString()},so="CommercialConfig",oo="commercial-config";var co,uo,no=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:o,InnerEvent:n}}=this._core=e;s.subscribeInnerEvent(n.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(n.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,o.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){return h(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let o,n=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(o=(t<32?new eo(0,2**t):new eo(2**(t-32),0)).toString(),!this._featureMap.get(o))){n=!1;break}return console.log(`${so}.isFeatureEnabled decimalNumber:${e} key:${o} ret:`+n),{code:0,data:{enabled:n}}})}_fetchAndParseCommercialConfig(){return h(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 h(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:oo,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 h(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,o;"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:o}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*o):void 0===t?(console.log(so+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(console.error(so+`._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 eo(0,2**t):new eo(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(to,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(to,r);e&&this._methodKeyMap.set(e,!1)}}else console.warn(so+".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(oo),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}},io=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)}},ro=new class{constructor(){this._core=null}install(e){return h(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 h(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={},o=new RegExp(/'/g);for(let t=0;t<s.length;t++){var n=s[t].indexOf(":"),i=s[t].slice(0,n);let e=s[t].slice(n+1);i.startsWith("//")||""!==e&&(e=e.replace(o,""),r[i]=e)}return r}}};function ao(o,l){return h(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=o,r="openim.getmsg",i=l.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+i.head.seq+r;try{let e=yield l.channel.sendPacket(i,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:o,revokedMessageList:n}=function(e,S){let r=[],o=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:o,MsgClientTime:n,MsgRandom:i,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,To_Account:d,TinyId:h,MsgCheckResult:p,CloudCustomData:_,IsPeerRead:g,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:g,clientTime:n,messageFlagBits:m,random:i,sequence:a,time:l,messageControlInfo:u,isSupportExtension:c,to:d,tinyID:h,checkResult:p,cloudCustomData:_,messageVersion:v,eventArray:f,elements:S.message.messageHelper.parseServerPushMessageElement(o)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))o.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=S.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:o}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:o,revokedMessageList:n,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}catch(e){console.warn(e)}})}!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(co=co||{}),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(uo=uo||{});var lo=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 h(this,void 0,void 0,function*(){let{isAfterReOnline:i=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=co.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?uo.NEW_MESSAGE_RECEIVED:uo.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:o,groupTipList:n}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",l=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:o,overflowUnreadCountList:r,conversationUpdateFieldList:u}),Array.isArray(n)&&c.push(...n),i){let e=this._handleNewMessageList(t)["messages"];h.push(...e)}}return i?{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 h(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return h(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:o,CONV_SYSTEM:n}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==n){let e=r.find(({conversationID:e})=>e===""+o+t);e?e.unreadCount=s:r.push({conversationID:""+o+t,unreadCount:s,type:o})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===n||r.find(({conversationID:e})=>e===""+o+t)||r.push({conversationID:""+o+t,type:o,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return h(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let o=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:i,conversationID:a=""}=r;if(s!==t){let s=o.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;n&&i?n===e&&i===t||o.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:i,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=o.getLatestMsgSentByMe(a);!e||n===e.nick&&i===e.avatar||o.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:i,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:o,_isExcludedFromLastMessage:n}=a,i=n?"":a;l.has(e)?(l.get(e).lastMessage=i,"in"!==r||o||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:o||"in"!==r?0:1,lastMessage:i})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:l}}_fetchUnreadDBMessage(l){return h(this,void 0,void 0,function*(){try{console.log("unread-message-synchronizer._fetchUnreadDBMessage options:",l);var e,t,s,r,o,n,i,a=yield ao(l,this._core);return a?({syncFlag:e,unreadMessageList:t,revokedMessageList:s,cookie:r,unreadCountList:o,overflowUnreadCountList:n,groupTipList:i}=a,this._parseAndSaveUnreadMessageList(t),{syncFlag:e,cookie:r,unreadMessageList:t,revokedMessageList:s,unreadCountList:o,overflowUnreadCountList:n,groupTipList:i}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===co.START_SYNC||t===co.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()}},po=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()}},ho=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()}},_o=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?ho:po).init(e)}};let go="none",mo="online";var vo=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return h(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:mo})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:go})}_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()}},fo=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return h(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()}},Io=new class{init(e){var t=e.helper["IN_WX_MINI_APP"];(t?fo:vo).init(e)}},So=new class{install(e){_o.init(e),Io.init(e)}};let Eo=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.*"]),Co="tui_room_svr.*";var Mo=new class{constructor(){this._transferredCommands=Eo}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 h(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=Co}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(n,i){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,{serviceCommand:s=Co,data:r}=n||{};let o={};try{o="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:o}),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=Eo}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};let yo=1,To=2,Ao=3,Oo=4,Do=5,Ro="TIMCustomElem",Lo="C2C",No="GROUP",bo="invite",Go="accept",wo="cancel",Po="reject",Uo="modifyInvitation",ko="signaling",Fo=8010,$o="signaling-timeout";function qo(e){return e.filter(e=>{var t,s;return e.type===Ro&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function xo(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function Vo(e,t){return e.toString(16).padStart(t,"0")}function Bo(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 jo=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){(this._core=e).notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){var t=ko+".isInvitationValid",{inviteID:e,groupID:s,inviter:r}=e,r=r===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var o=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(t+` inviteID:${e} inviteeList:${o} groupID:`+s),s){if(r)return 0<o.length;let e=this._core.common.getCurrentUserID();return o.includes(e)}return!0}updateSignaling(e){let s=ko+".updateSignaling",{inviteID:r,inviter:t,inviteeList:o,groupID:n}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+n),n&&this.hasSignaling(r)){let e=o[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()}},Ko=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:o}=e,s=s||(t?r[0]:o);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:o}=e,s=(null==(s=null==(s=jo.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,o)}}_createMessageControlInfo(e,t){t=t===Do&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){var t=ko+"._createInviteSignalingData",{userID:s,timeout:r=0,groupID:o="",inviteeList:n=[]}=e,i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:yo,inviter:i,inviteeList:o?n:[s],timeout:r});return console.log(t+" signalingData:",e),e}_createAcceptSignalingData(e){var t=ko+"._createAcceptSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:o}=jo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Ao,groupID:o,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createCancelSignalingData(e){var t=ko+"._createCancelSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviteeList:s,groupID:o}=jo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:To,groupID:o,inviter:r,inviteeList:s});return console.log(t+" signalingData:",e),e}_createRejectSignalingData(e){var t=ko+"._createRejectSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:o}=jo.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Oo,groupID:o,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createTimeoutSignalingData(e){var t=ko+"._createTimeoutSignalingData",{isInviter:s=!1,inviteID:r}=e,{inviteeList:r,inviter:o}=jo.getSignaling(r),n=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Do,inviter:o,inviteeList:s?r:[n]});return console.log(t+" signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?No:Lo,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[Vo(Bo(32),8),Vo(Bo(16),4),Vo(16384|Bo(12),4),Vo(32768|Bo(14),4),Vo(Bo(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Wo=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 h(this,void 0,void 0,function*(){var s;console.log(ko+".invite params:"+JSON.stringify(t));try{this._validateBeforeInvite(t);var{signaling:r,signalingData:o,signalingExtensionOptions:e}=Ko.createInviteSignaling(t),n=yield this._sendSignaling(r,e);if(0!==(null==n?void 0:n.code))return n;{let{inviteID:e,timeout:t}=o;return jo.saveSignaling(e,Object.assign(Object.assign({},o),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:$o+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},n),{inviteID:e})}}catch(e){throw console.error(ko+".invite error:"+e),e}})}accept(n){return h(this,void 0,void 0,function*(){console.log(ko+".accept params:"+JSON.stringify(n));try{var e=n["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,Ko.createAcceptSignaling(n)),o=yield this._sendSignaling(t,r);return 0===(null==o?void 0:o.code)?(jo.updateSignaling(s),Object.assign(Object.assign({},o),{inviteID:e})):o}catch(e){throw console.error(ko+".accept error:"+e),e}finally{this._isProcessingSignaling=!1}})}cancel(o){return h(this,void 0,void 0,function*(){console.log(ko+".cancel params:"+JSON.stringify(o));try{var e=o["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,Ko.createCancelSignaling(o)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(jo.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(ko+".cancel error:"+e),e}finally{this._isProcessingSignaling=!1}})}reject(o){return h(this,void 0,void 0,function*(){console.log(ko+".reject params:"+JSON.stringify(o));try{var e=o["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,Ko.createRejectSignaling(o)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(jo.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(ko+".reject error:"+e),e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return h(this,void 0,void 0,function*(){console.log(ko+".modifyInvitation params:"+JSON.stringify(e));var r,o,{inviteID:n,data:i}=e;let a="";try{this._validateBeforeModifyInvitation(n);let e=jo.getSignaling(n),t=e["signaling"],s=p(e,["signaling"]);a=t.payload.data,s.data=i,t.payload.data=JSON.stringify(s);var l=yield null==(o=null==(r=this._core)?void 0:r.message.messageAction)?void 0:o.modifyMessage(t);return jo.hasSignaling(n)&&jo.saveSignaling(n,Object.assign(Object.assign({},s),{signaling:t})),l}catch(e){if(a){let e=jo.getSignaling(n)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){if(0!==qo([e]).length)return e={businessID:(e=xo(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||yo,timeout:e.timeout||0},console.log(ko+" getSignalingInfo ",e),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&jo.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)&&jo.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=jo.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 h(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 h(this,void 0,void 0,function*(){var o;console.log(ko+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:n,inviteID:i}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=Ko.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!=(o=this._core)&&o.notificationCenter.emitOuterEvent(null==(o=this._core)?void 0:o.SignalingEvent.INVITATION_TIMEOUT,{name:null==(o=this._core)?void 0:o.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:i,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),n?jo.removeSignaling(i):jo.updateSignaling(l)}})}_validateInviteId(e,t){if(!jo.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:Fo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var t=bo,e=e["userID"],s=this._core.common.getCurrentUserID();if(e===s)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${s}, inviteeId:`+e})}_validateBeforeAccept(t){var s=Go;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=jo.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=wo,s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=jo.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s=Po;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=jo.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){var t=Uo;this._validateInviteId(t,e)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Ho=new class{constructor(){this._actionProcessor=new Map([[yo,this._onNewInvitationReceived.bind(this)],[Oo,this._onInviteeRejected.bind(this)],[Ao,this._onInviteeAccepted.bind(this)],[To,this._onInvitationCancelled.bind(this)],[Do,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=xo(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){jo.getSignalingListenStatus()&&0!==(e=qo(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){jo.getSignalingListenStatus()&&0<(e=qo(e.data)).length&&e.forEach(e=>{var t=xo(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){var r=ko+"._onNewInvitationReceived",{inviteID:o,inviteeList:n,groupID:i}=t,a=this._core.common.getCurrentUserID();if(console.log(r+` signalingData:${JSON.stringify(t)}}`),!i||n.includes(a)){let e=t["timeout"];var r=Date.now()/1e3-s.time,i=(0<e&&0<r&&e>r&&(e-=r),jo.getSignaling(o));i!==t&&(i||jo.saveSignaling(o,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(a=this._core)&&a.helper.taskScheduler.addOnceTask({id:$o+"-"+o,intervalMs:1e3*e,callback:Wo.handleInvitationExpiryTimer.bind(Wo,o)})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:n})}))}}_onInviteeRejected(e){var t=ko+"._onInviteeRejected",{inviteID:s,inviter:r,groupID:o,inviteeList:n}=e,i=jo.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${i} inviter:${r} groupID:`+o),i&&(jo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:n[0]})}))}_onInviteeAccepted(e){var t=ko+"._onInviteeAccepted",{inviteID:s,inviter:r,groupID:o,inviteeList:n}=e,i=jo.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${i} inviter:${r} groupID:`+o),i&&(jo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:n[0]})}))}_onInvitationCancelled(e){var t=ko+"._onInvitationCancelled",{inviteID:s,inviter:r,groupID:o}=e,n=jo.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${n} inviter:${r} groupID:`+o),n&&(jo.removeSignaling(s),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t=ko+"._onInvitationTimeout",{inviteID:s,inviteeList:r}=e,o=jo.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${o} data:`+e.data),o&&(jo.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s=ko+"._onInvitationModified",{inviteID:r,data:o}=e,n=jo.hasSignaling(r);console.log(s+` inviteID:${r} data:`+o),n&&(jo.saveSignaling(r,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:r,data:o}}))}_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)}},Yo=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:o}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(o.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)&&jo.getSignalingListenStatus()){e=qo([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();Ho.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=xo(e);s&&(t=s["actionType"],t===yo?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:o=0}=e,n=this._core.common.getCurrentUserID();r.includes(n)&&(r=Date.now()/1e3-t.time,0<o&&o<r&&0!==o||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 zo={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}}},Jo={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Zo,en,tn,Qo=new class{install(e){Wo.init(e),Ho.init(e),Ko.init(e),jo.init(e),Yo.init(e),e.helper.registerValidateConfig({auth:Jo,params:zo})}};let Xo=new class{init(e){this.core=e}},sn=(!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(Zo=Zo||{}),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(en=en||{}),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(tn=tn||{}),"MSG_REACTION"),on="MSG_EXT",nn=0,rn=1,an={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},cn="16k_zh",un="16k_en",ln="16k_yue",dn="16k_ja",pn="16k_zh-PY",hn={[an.ZH_CN]:cn,[an.EN_US]:un,[an.YUE_HK]:ln,[an.JA_JP]:dn,[an.ZH_PY]:pn},_n=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,gn={READ:0,UNREAD:1},mn=1,vn=2,fn=3,In=1,Sn=2,En=2116,Cn=2500,Mn="C2C",yn="GROUP",Tn=20,An=1,On=300;function Dn(n){return h(this,void 0,void 0,function*(){var e,s=Xo.core["appStore"],{messageList:t,conversationID:r}=n,s=s.conversationStore.getConversationMap();let o=null==(e=s.get(r))?void 0:e.peerReadTime;if(!o){let e=r.replace(Mn,""),t=yield function(t){return h(this,void 0,void 0,function*(){var e={To_Account:t};return Xo.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];o=null==e?void 0:e[0],s.has(r)&&(s.get(r).peerReadTime=o)}}t.forEach(e=>{e.time<=o&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)})})}function Rn(a){return h(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:o}}=Xo.core,n=r.conversationStore.getConversationMap();if(n.has(a)){let s=null==(e=n.get(a))?void 0:e.userProfile;if(s&&a.startsWith(o.CONV_C2C)){let{avatar:e,nick:t}=s;Xo.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!1})}}var i=((yield t.userProfile.getMyProfile())||{})["data"];if(i){let{avatar:e,nick:t}=i;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!0})}})}function Ln(e){let t,s=Xo.core["message"],{conversationID:r,messageID:o}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===o))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===o)}function Nn(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:o,nick:n,ID:i,clientSequence:a,clientTime:l,messageRandom:u,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:o,From_AccountNick:n,Id:i,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 bn(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:o,MsgClientTime:n,ClientSeq:i,To_Account:a,MsgTimeStamp:l,TinyId:u,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:n,time:l,tinyID:u,random:c,sequence:d,to:a,groupID:o,clientSequence:i,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return Xo.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var Gn=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:o}}=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,o,this._handleReactionSync,this)}addMessageReaction(_,g){return h(this,void 0,void 0,function*(){let{OuterConstant:e,ssoLog:t,helper:r}=this._core;this._validateMessageReactionBusinessCapability();var o=t.createSSOLogData({method:"addMessageReaction"}),{conversationID:s,ID:n,conversationType:i,from:a,to:l,clientSequence:u,random:c,time:d,sequence:p}=_;try{return this._recordMessageReactedByMe(n,g),i===e.CONV_C2C?yield function(i,a){return h(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:o,reactionID:n}=i,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+o,Reaction:n,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:a,to:l,clientSequence:u,random:c,time:d,reactionID:g},this._core):i===e.CONV_GROUP&&(yield function(r,o){return h(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=o.store.get("login"))?void 0:e.userId]};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:l,reactionID:g,sequence:p},this._core)),o.setLogInfo({message:`conversationID:${s} messageID:${n} reactionID:`+g}).end(),{code:0}}catch(e){this._removeMyReactionRecord(n,g);let t=(e||{})["errorCode"],s=new r.ChatError({functionName:"addMessageReaction",code:t});o.setError(s).end(),console.error("addMessageReaction error: ",e)}})}removeMessageReaction(d,p){return h(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:o,clientSequence:n,random:i,time:a,sequence:l}=d;return this._removeMyReactionRecord(t,p),s===u.CONV_C2C?yield function(i,a){return h(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:o,reactionID:n}=i,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+o,Reaction:n,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:r,to:o,clientSequence:n,random:i,time:a,reactionID:p},this._core):s===u.CONV_GROUP&&(yield function(r,o){return h(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=o.store.get("login"))?void 0:e.userId]};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},o)})}({to:o,reactionID:p,sequence:l},this._core)),c.setLogInfo({message:`conversationID:${e} messageID:${t} reactionID:`+p}).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 h(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=u,s=100<u.count?100:u.count,o=e["conversationID"],{ssoLog:n,helper:i,constants:a}=this._core;try{var l;if(l=o.startsWith(a.OuterConstant.CONV_C2C)?yield function(l){return h(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=l,{from:e,to:o,clientSequence:n,random:i,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:o,MsgKey:n+`_${i}_`+a};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(n){return h(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=n,{sequence:e,to:o}=e,s={Reaction:s,NextSeq:t,GroupId:o,Count:r,MsgSeq:e};return Xo.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 i.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});n.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}})}getMessageReactions(_){return h(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),_),r=t[0];let o=null,n=new Map,{from:i,to:a,conversationType:l}=r,u=this._generateMessageKeyList(t,n),{Results:c=[]}=(l===e.OuterConstant.CONV_C2C?o=yield function(o){return h(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=o,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:i,to:a,messageKeyList:u,maxUserCountPerReaction:s}):l===e.OuterConstant.CONV_GROUP&&(o=yield function(r){return h(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,e={GroupId:e,MsgSeqList:t,Count:s};return Xo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:u,maxUserCountPerReaction:s})),o||{}),d=this._extractUserIDsFromReactionResults(c),p=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:n}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:p}),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 h(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 h(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(sn))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){let t=e["MsgReactionNotifyList"],{notificationCenter:d,constants:p}=this._core;t.forEach(c=>h(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:o,MsgRandom:n}=Object.assign(Object.assign({},e),t),i=r+`-${o}-`+n,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),u=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:l}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(i+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:i,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(p.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:p.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:i,reactionList:u}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:o,OperateType:n}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:i=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+i,i=r+"-"+o;if(1===n?this._recordMessageReactedByMe(r,o):this._removeMyReactionRecord(r,o),null!=(e=this._reactionsMap.get(i))&&e.reactionID){let e=this._reactionsMap.get(i);e.reactedByMyself=1===n,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,o){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 o.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return o.set(t,e),t})),r}},wn=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:o}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),o.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),o.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return h(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 h(this,void 0,void 0,function*(){var{common:e,constants:t}=Xo.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:o,clientTime:n}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:o,MsgClientTime:n}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return h(this,void 0,void 0,function*(){var{common:e,constants:t}=Xo.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(o){return h(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=o[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(o);if(0<(null==s?void 0:s.length)){let e=yield function(s){return h(this,void 0,void 0,function*(){var{common:e,constants:t}=Xo.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:o,readReceiptList:t})}}return{code:0,data:{messageList:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(n){return h(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:i=gn.READ,cursor:s=""}=n,{conversationID:o,sequence:a,ID:l}=t,u=o.replace(e.OuterConstant.CONV_GROUP,""),c=100<=n.count?100:n.count;try{let n=yield function(n){return h(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:o}=n,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:o};return Xo.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:u,sequence:a,filter:i,cursor:s,count:c});if(n){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=n,o={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return i===gn.READ?o.readUserIDList=r.map(e=>e.Read_Account):i===gn.UNREAD&&(o.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let o=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:n,PeerReadTime:i,Peer_Account:a}=e;if(!s.isEmpty(n)){let r=""+t.OuterConstant.CONV_C2C+a;null!=n&&n.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=Ln({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=i,o.push({userID:a,messageID:e,isPeerRead:!0,timestamp:i}))}),this._emitReadReceiptEventIfNeed(o)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:n}}=e,i=""+s.OuterConstant.CONV_GROUP+n;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:o}=e,e=e+`-${t}-`+s,t=Ln({conversationID:i,messageID:e}),s={groupID:n,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof o&&(t.readReceiptInfo.unreadCount=o,s.unreadCount=o),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 Pn(i,a,l){return h(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=Xo.core["common"],{from:t,to:s,clientSequence:r,random:o,time:n}=i;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${o}_`+n,OperateType:l,ExtensionList:a}})})}function Un(r,o,n){return h(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=Xo.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:n,ExtensionList:o}})})}var kn=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:o}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,o,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(d,r){return h(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:o,conversationID:n,sequence:i,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 Pn(d,c,mn):s===e.CONV_GROUP&&(r=yield Un(d,c,mn)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return l.setLogInfo({message:`convID:${n} messageID:${o} sequence:${i}
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(i){return h(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:o}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),i),n=this._core.ssoLog.createSSOLogData({method:"getMessageExtensions"});n.setLogInfo({message:`convID:${e} messageID:${r} sequence:${t} time:`+o});try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(i,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),n.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 n.setError(r).end(),r}})}deleteMessageExtensions(p,_){return h(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t},ssoLog:s}=this._core,{conversationType:o,conversationID:r,sequence:n,ID:i,time:a}=p,l=fn,u=[];e(_)||(l=vn,null==_)||_.forEach(e=>{u.push({key:e,value:"",seq:0})});var c=s.createSSOLogData({method:"deleteMessageExtensions"}),d=(c.setLogInfo({message:`convID:${r} messageID:${i} sequence:${n} time:${a} operateType:`+l}),this._generateServerExtensions(p,u));try{let r;if(o===t.CONV_C2C?r=yield Pn(p,d,l):o===t.CONV_GROUP&&(r=yield Un(p,d,l)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(p,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"],o=t.ExtensionList||[],n=[],i=0,a=0,l=[];return o.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;n.push({code:e,key:t,value:s}),0===e?i++:a++,l.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<l.length&&this._updateLocalExtensions(e.ID,l),{resultList:n,successCount:i,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 h(this,void 0,void 0,function*(){let{constants:{OuterConstant:e},utils:{isEmpty:i}}=this._core;try{let n;var{conversationType:t,ID:a}=l;if(t===e.CONV_C2C?n=yield function(e,t){var s=Xo.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:o,random:n,time:i}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:o+`_${n}_`+i,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(n=yield function(e,t){var s=Xo.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(l,s)),n){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=n,r=(n.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let o=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;i(e)||o.push({key:t,value:e})})}return o}}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(on))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:o,MsgLastSeq:n,ExtensionC2cMsgInfo:i,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:i,MsgRandom:a}=i||a||{},o=o+`-${i}-`+a;this._extensionsLatestSequenceMap.set(o,n),r===mn?this._handleMessageExtensionsUpdated({messageID:o,updateMessageExtensionsInfo:e}):r===vn?this._handleMessageExtensionsDeleted({messageID:o,deleteMessageExtensionsInfo:t}):r===fn&&this._handleMessageExtensionsCleared({messageID:o,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:o=[]}=e,n=[];o.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:n}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:o=[]}=e,n=[];o.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:n}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:o,clearMessageExtensionsInfo:n=[]}=e,i=[];n.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(o)&&(this._messageExtensionsMap.get(o)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&i.push(t)}),this._clearLocationExtensions(o,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:o,keyList:i}})}};let Fn={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=Xo.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},$n={setMessageExtensions:[Fn,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Fn],deleteMessageExtensions:[Fn]},qn=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}=Xo.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}}}),$n),xn=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 Vn{constructor(e){this._core=e}deleteMessage(s){return h(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:t};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:e})})}revokeMessage(n){return h(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:o}=n;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:o,MsgTimeStamp:r}}})})}}class Bn{constructor(e){this._core=e}deleteMessage(s){return h(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 h(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 jn{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:o,revokeReason:n,revoker:i}=e;let a={};var l=this._core.message["messageDataHandler"];return(a=l.revokeMessage({conversationID:e,sequence:t,random:s,revoker:i}))||(a={conversationID:e,sequence:t},r&&o&&s&&(a.ID=r+`-${o}-`+s)),a=Object.assign(Object.assign({},a),{revoker:i,revokeReason:n,revokerInfo:{userID:i,nick:"",avatar:""}})}updateRevokerInfo(t){return h(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 h(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 Kn=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Bn(e),this._c2cMessageAction=new Vn(e),this._messageHelper=new jn(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 h(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:En});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:o,sequence:n,random:i,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!o){let e="C2C"===s?n+`_${i}_`+a:String(n);l.push(e)}u.push(e)}}),0===l.length)return this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}};30<l.length&&(l=l.slice(0,30),u=u.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:l}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:l}),this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(n){return h(this,void 0,void 0,function*(){var s;let r=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:e,isRevoked:t}=n;var o;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:${n.type} from:${n.from} to:`+n.to});try{if(o="C2C"===e?yield this._c2cMessageAction.revokeMessage(n):yield this._groupMessageAction.revokeMessage(n)){let e=o["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(n),{code:0,data:{message:n}}}}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 h(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(o){if(0!==o.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;o.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:o=""}=o[0];e(o)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,o):t.emitInnerEvent(r.MESSAGE_DELETED,o)}}_handleRevokeMessageSuccess(o){return h(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}=o;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([o])})}};class Wn{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new Wn({index:e,data:t})}constructor(e){this.type=Zo.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 Hn{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new Hn({description:e,longitude:t,latitude:s})}constructor(e){this.type=Zo.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 Yn=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(Zo.MSG_FACE,Wn),e.message.messageFactory.registerElementClass(Zo.MSG_LOCATION,Hn),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 Wn({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"],o=this._core.apiMap.createTextMessage(e),n=this._core["OuterConstant"];if(!o)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==n.MSG_AT_ALL?(t.push({GroupAtAllFlag:nn,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:rn}),s.push(n.MSG_AT_ALL))}),o._groupAtInfoList=t,o.atUserList=s}return o}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:o,payload:n,needReadReceipt:i,receiverList:a,cloudCustomData:l="",isSupportExtension:u=!1}=e;if(!Array.isArray(n._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(n.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:o,payload:n,needReadReceipt:i,isSupportExtension:u,cloudCustomData:l,receiverList:a});return t.setRelayFlag(!0),t.setElement(n._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new Hn({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 zn=class{init(e){this._messageHelper=new jn(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:n}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return h(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return h(this,void 0,void 0,function*(){let i=[],{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:o,Revoke_Reason:n,Reason:n=n}}=e,s=a()===r?"C2C"+s:"C2C"+r,r=this._messageHelper.generateRevokeMessage({conversationID:s,sequence:t,random:e,revoker:o,revokeReason:n});i.push(r)}),0<i.length&&(yield this._messageHelper.updateRevokerInfo(i),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:i}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return h(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 jn(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(r){return h(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e}}=r,u=[],{notificationCenter:t,OuterEvent:s}=this._core;e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:o,TopicId:n,RevokerInfo:{Revoker_Account:i=(null==l?void 0:l.Revoker_Account)||"",Reason:a=(null==l?void 0:l.Reason)||""}}=e,n=this._messageHelper.generateRevokeMessage({conversationID:n?"GROUP"+n:"GROUP"+s,sequence:t,random:e,tinyID:o,clientTime:r,revoker:i,revokeReason:a});u.push(n)}),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 Qn=new class{constructor(){this._c2cMessageReceiver=new zn,this._groupMessageReceiver=new Jn}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class Xn{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new jn(e)}getRoamingMessagesByAnchor(r){return h(this,void 0,void 0,function*(){try{var i=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:e,direction:a,sequence:l}=r,u=t.replace(yn,"");let n=l;if(a===tn.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};n=l+e-1}var s={GroupId:u,ReqMsgNumber:e,WithRecalledMsg:1,Version:1},c=(n&&(s.ReqMsgSeq=n),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:r}=c;i.setLogInfo({message:`groupID:${u} sequence:${l} reqSeq:${n} direction:${a}
3
+ complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+r}).end();var d=[];for(let e=0;e<t.length;e++){var h=t[e],p=this._parseMessage(h);d.push(p)}d.reverse();let o=s===en.NO_MORE_DATA;return a===tn.BACKWARD&&(o=d[d.length-1].sequence>=l),{messageList:this._messageHelper.filterValidMessages(d),invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o}}}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 h(this,void 0,void 0,function*(){let{message:{messageReceiver:d,messageDataHandler:p},notificationCenter:_,OuterEvent:g,constants:{OuterConstant:s}}=this._core,r=[];null!=e&&e.forEach(t=>h(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:tn.FORWARD,count:t}),{nextReqMessageIDFromServer:r,hasNoMoreHistoryMessage:o,messageList:n}=s,i=(c=o&&r<0,l=n[n.length-1].sequence,[]);if(Array.isArray(n)&&(n.forEach(e=>{d.groupMessageReceiver.updateMessageProfile(e),p.storeConversationMessage(e)&&i.push(e)}),0<i.length)&&_.emitOuterEvent(g.MESSAGE_RECEIVED,{name:g.MESSAGE_RECEIVED,data:i}),c)break}catch(e){console.debug(e);break}}else r.push(a.replace(s.CONV_GROUP,""))})),this._recoverGroupRevokeNotice(r)})}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&&t>=An&&t<On}_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"],s=yn,t=(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:s,flow:"in"}));return e.setElement(t.elements),e}_recoverGroupRevokeNotice(e){let r=this._filterValidGroupIDList(e);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 h(this,void 0,void 0,function*(){var e;try{var t=yield function(n){return h(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=Xo.core,o=e.groupStore.getGroupMap(),t={NotifyReqList:n.map(e=>{var t=o.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*Xo.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:i}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:o=""}}=e,n="GROUP"+i,n=this._messageHelper.generateRevokeMessage({conversationID:n,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:o});a.push(n)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return h(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 Zn{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new jn(e)}getRoamingMessagesByAnchor(g){return h(this,void 0,void 0,function*(){var o;try{var{conversationID:n,count:e,messageID:r,time:i,direction:a}=g;let t=i,s="";if(!i){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(n)){let e=this._historyMessageListFetchAnchors.get(n);t=e.lastMessageTime,s=e.messageKey}}var l=n.replace(Mn,""),u=yield function(n){return h(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:o}=n,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:o};return Xo.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:l,direction:a});if(u){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=u;this._historyMessageListFetchAnchors.set(n,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],p=this._parseMessage(d);c.push(p)}var _=this._messageHelper.filterValidMessages(c);return{messageList:_,nextReqMessageIDFromServer:null==(o=_[0])?void 0:o.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){var t=Mn,e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}}var ei=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new Xn(e),this._c2cMessageHistory=new Zn(e),this._messageHelper=new jn(e);var{InnerEvent:t,notificationCenter:s,constants:r}=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(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.WORKFLOW_STEP.HISTORY_MESSAGE_RECOVER,this._recoverHistoryMessage,this),s.subscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}getMessageList(e){return h(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e,r=Tn;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var o=this._core.ssoLog.createSSOLogData({method:"getMessageList"}),n=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:n,targetCount:r})){let e=null;if(t.startsWith(yn)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:r,direction:tn.FORWARD}):t.startsWith(Mn)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:r,direction:tn.FORWARD})),e){var{nextReqMessageIDFromServer:i,hasNoMoreHistoryMessage:a,messageList:l}=e,u=this._core.message.messageDataHandler.prependLocalMessageList({messageList:l,conversationID:t}),c=t,{appStore:d,message:h,OuterConstant:p}=Xo.core,d=d.conversationStore.getConversation(c),_=h.messageDataHandler.getLocalMessageList(c);if(d&&0!==_.length&&c!==p.CONV_SYSTEM){var g=[];for(let e=0;e<_.length;e++)"in"!==_[e].flow?"out"!==_[e].flow||_[e].isRead||_[e].setIsRead(!0):g.push(_[e]);let t=0;if(d.type===p.CONV_C2C){let e=g.slice(-d.unreadCount).filter(e=>e.isRevoked).length;t=g.length-d.unreadCount-e}else t=g.length-d.unreadCount;for(let e=0;e<t&&!g[e].isRead;e++)g[e].setIsRead(!0)}yield Rn(t),t.startsWith(Mn)&&(yield Dn({messageList:l,conversationID:t}));var m=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,u.length+n),v=m.filter(e=>e.isRevoked),f=(yield this._messageHelper.updateRevokerInfo(v),{nextReqMessageID:a?"":String(i),messageList:m,isCompleted:a}),I=m.map(e=>e.sequence);return o.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s}
4
+ availableLocalMessagesCount: ${n} sequenceList: ${JSON.stringify(I)} `}).end(),{code:0,data:f}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return o.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${n}}`}).end(),{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:r})}}catch(e){h=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(h).end(),console.debug(h)}})}getMessageListHopping(r){return h(this,void 0,void 0,function*(){var n,i;let{conversationID:e,sequence:a,time:t,direction:l=tn.FORWARD}=r,u=this._core.helper["isEmpty"];if(![tn.BACKWARD,tn.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=Tn}=r,c=(s=s>Tn?Tn:s,null);if(e.startsWith(yn)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:o}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),l===tn.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==tn.BACKWARD)return{code:0,data:c};{if(u(r)&&u(o))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(n=null==r?void 0:r[r.length-1])?void 0:n.sequence)||0,t=(null==(i=null==o?void 0:o[o.length-1])?void 0:i.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(Mn)&&(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===tn.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(_){return h(this,void 0,void 0,function*(){var t;let{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:o,CONV_GROUP:n},message:i,apiMap:a,ssoLog:l}=this._core,u=e.conversationStore.getConversation(_);if(!u)throw new s({code:Cn});var c=l.createSSOLogData({method:"clearHistoryMessage"}),d=(c.setLogInfo({message:"convID:"+_}),{fromAccount:r()}),p=u["type"];p===o?(d.type=In,d.toAccount=_.replace(o,"")):p===n&&(d.type=Sn,d.toGroupID=_.replace(n,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:_});let e=yield function(o){return h(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=o,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return Xo.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(d);return e&&(c.end(),i.messageDataHandler.deleteConversationMessageList(_),this._clearedConversations.add(_),this._fetchedCompleteConversations.delete(_),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(_),this._updateConversationLastMessage(_)),{code:0,data:{conversationID:_}}}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 o=-1;return null!=e&&e.startsWith(Mn)?o=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(yn)&&(o=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<=s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return h(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),o=r.length;let n=o,i={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=o;return s?(l=r.findIndex(e=>t.startsWith(Mn)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,n=l):a=e<o?o-e:0,i.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),i.messageList=r.slice(a,l),i.isCompleted=n<=e,t.startsWith(Mn)&&(yield Rn(t),yield Dn({messageList:i.messageList,conversationID:t})),i})}_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===yn&&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)}},ti=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(o){return h(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=o,r=yield function(n,i){return h(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=n,{store:r,common:o}=i,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 o.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})}})}},si=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return h(this,void 0,void 0,function*(){let{message:e,language:t=an.ZH_PY}=s,r=(e.payload||{})["url"];var o=null==(o=this._core.store.get("login"))?void 0:o.userID,o=(e.from===o&&"out"===e.flow&&(r=e.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(n=_n.exec(r))?void 0:n[1])||"mp3"),n=hn[t]||pn;try{let s=yield function(e){var{store:t,common:s}=Xo.core,{url:e,format:r,serverLanguageType:o}=e,o={BytesUrl:e,BytesEngServiceType:o,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:o})}({url:r,format:o,serverLanguageType:n});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{},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(!_n.test(e))throw new this._core.common.ChatError({code:2119})}};class oi{constructor(e){var{constants:t,common:s,utils:r}=Xo.core,{CONV_C2C:t,CONV_GROUP:o}=t.OuterConstant,{ID:e,tinyID:n,from:i,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:l,sequence:u,cloudCustomData:c="",nick:d="",avatar:h="",clientSequence:p,conversationType:_,groupID:g,_elements:m,time:v}=e,n=(this.ID=e||n+`-${s}-`+l,this.messageRandom=l,this.from=i,this.messageSender=i,this.time=v,this.messageSequence=u,this.clientSequence=p||u,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=h,this.nick=d,r.deepCopyWithMethods(m));n.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=n,e?_.startsWith(t)?this.receiverUserID=a:_.startsWith(o)&&(this.receiverGroupID=a):g?(this.receiverGroupID=g,this.messageReceiver=g):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 ni{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:o,JsonMsgKey:n}=e||{},e=e.map(e=>bn(e));return new ni({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:o,downloadKey:n})}constructor(e){this.type=Xo.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:o,pbDownloadKey:n="",downloadKey:i="",version:a=0,layersOverLimit:l=!1}=e,u=[];t.forEach(e=>{e&&(e=new oi(e),u.push(e))}),this.content={messageList:u,title:s,abstractList:r,compatibleText:o,version:a,downloadKey:i,pbDownloadKey:n,layersOverLimit:l}}validateBeforeSend(){var e=Xo.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:o,title:n,version:i,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:o,Title:n,Version:i,MsgList:Nn(a)}}}}var ii=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,ni),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 ni(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 h(this,void 0,void 0,function*(){var e,t,s;try{var n=function(t){let e="utf-8";Xo.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,o;if(o=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<o;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<o;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,o=null;if(11264<n){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return h(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:Nn(e)};return Xo.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];o=new ni(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(o)}catch(e){console.error(e)}}var{message:i}=(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 o&&i.setElement(a._elements),{code:0,data:{message:i}}}catch(e){throw console.error(e),e}})}downloadMergerMessage(n){return h(this,void 0,void 0,function*(){try{var e=n.payload,t=e["downloadKey"],s=p(e,["downloadKey","pbDownload","type","messageList"]),r=((yield function(e){return h(this,void 0,void 0,function*(){return Xo.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(t))||{})["MsgList"],o=null==r?void 0:r.map(e=>{e=bn(e);return new oi(e)});return"function"==typeof n.isOnlineMessage?n.setElement({type:n.type,content:Object.assign({messageList:o},s)}):(n.payload.messageList=o,n.payload.downloadKey="",n.payload.pbDownloadKey=""),n}catch(e){console.error(e)}})}},ri=new class{install(e){this._core=e,Xo.init(e),Kn.init(e),Yn.init(e),Qn.init(e),ei.init(e),Gn.init(e),ti.init(e),si.init(e),wn.init(e),ii.init(e),kn.init(e),e.helper.registerValidateConfig({auth:xn,params:qn}),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),Qn.dispose(),ei.dispose(),wn.dispose(),kn.dispose()}_reset(){ei.reset()}},ai=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(_,g){return h(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:o,qs:n,headers:i={},resources:a,dataType:l="text",uploadByIP:u,uploadIP:c}=_,d=o;if(n){let e=this._queryString(n);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(r.toUpperCase(),d,!0),h.responseType=l;var p=Object.assign({},i);if(u&&c&&(p.host=c),!t(p))for(let e in p)p.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&h.setRequestHeader(e,p[e]);return h.onload=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e);if(200===h.status)g(null,e);else{if(c&&!d.includes(c))return _.url=this._domainName2IP(d,c),_.uploadByIP=!0,this.request(_,g);g({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)};g(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,r="&",o="="){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)+o;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 ci=["unknown","image","video","audio","log"];var Ai,ui=new class{init(e){this._core=e}request(s,r){let e,{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:i}=null==(e=this._core)?void 0:e.utils,{resources:a="",headers:l={},url:u,downloadUrl:c=""}=s,d=u,h=null;var _=c?c.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(_){var _=decodeURIComponent(_[3]),_=_.includes("?")?_.split("?")[0]:_||"",_={key:s.fileKey||_,success_action_status:200,"Content-Type":""},g={};if(i){let[e,t]=u.split("?sign=");t&&(d=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:d,header:l,name:"file",filePath:a,formData:Object.assign(Object.assign({},_),g),timeout:s.timeout||3e5};if(n){let e=p(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?ci[s.fileType]:"image"})}return(h=o.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 o=+t.statusCode;200==o?s(null,{statusCode:o,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:o,message:JSON.stringify(t.data)},{statusCode:o,headers:r,data:void 0})}};function li(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function di(e){e=e||99999999;return Math.round(Math.random()*e)}function pi(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 hi(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function _i(e,t){return Math.round(Number(e)*10**t)/10**t}function gi(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function mi(e){return e<=1048576?_i(e/1024,1)+"KB/s":_i(e/1048576,1)+"MB/s"}let vi="TIMImageElem",fi="TIMSoundElem",Ii="TIMFileElem",Si="TIMVideoFileElem",Ei="RichMediaMessagePlugin",Ci=["rich.my-imcloud.com","imrich.qcloud.com"],Mi=1,yi=2,Ti=3,Oi=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Ai=Ai||{}),{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 Di=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(Oi).some(e=>e.test(t))}extractFileFromInput(e){return li(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 h(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=Ci;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=Ci}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(),o=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,o));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})}},Ri=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?ui:ai,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return h(this,void 0,void 0,function*(){var t=Ei+" uploadToCOS",e=l["file"];this.uploadFileType=l.uploadFileType,console.log(t+" options:",l);try{var s=Date.now(),r=yield this._createCosOptions(l),o=yield this._uploadFile(r),n=(this._handleUploadError(o,l),this._createUploadResult(e,o)),i=Date.now()-s,a=`size:${gi(e.size)} time:${i}ms speed:`+mi(1e3*e.size/i);return console.log(t+` ok. name:${e.name} `+a),{uploadOptions:r,response:n}}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 pi(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:pi(Date.now(),!1),uploadSpeed:mi(1e3*e.size/pi(Date.now(),!1))}}_createCosOptions(p){return h(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:s}=this._prepareUploadParams(p),r=this._isC2CConversation(p.message.conversationID)?1:2;try{var o=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:n,downloadUrl:i,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c}=o,d=!Di.isPrivateNetWork()&&o.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:i,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,uploadIP:d||"",onProgress:e=>this._handleUploadProgress(e,p)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){console.log(Ei+" prepareUploadParams:",e);var t=e["file"],{IN_MINI_APP:s,IN_RN_APP:r}=Di.getPlatformFlags(),s=s||r,r=s&&e.message.type!==Ii,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+di(999999)+e;return{fileName:hi(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 h(this,void 0,void 0,function*(){var t=Ei+" fetchCosSignatureUrl",s=Di.isSimpleCos(),r=this._prepareCosRequestData(e),o=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(o,n,i){return h(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=i,s=e.generateCosSpecifiedData({servcmd:o,data:n}),r=s.head.seq+o;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(o,r,this._core);this.fetchCosTryCount=0;var n=this._processResponse(e);return console.log(t+` ok. isSimpleCos:${s} data:`,n),n||{}}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=Di.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:o,str_upload_url:n,str_snapshot_url:i,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:o,uploadUrl:n,requestSnapshotUrl:i,fileKey:a}}let{upload_url:r,download_url:o,snapshot_url:n,thumb_url:i,large_url:a,file_key:u}=l;return{uploadUrl:r,downloadUrl:o,requestSnapshotUrl:n,thumbUrl:i,largeUrl:a,fileKey:u}}_prepareCosRequestData(e){return Di.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:Di.getPlatform(),uint32_sdkappid:Di.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(o){return h(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(o,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(o).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,o=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===o}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=Di.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let Li=2108,Ni=2251,bi=2252,Gi=["jpg","jpeg","gif","png","bmp","image","webp"],wi=20971520,Pi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Ui{constructor(e,t){this.instanceID=di(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=Di.addAuthToUrl(e.imageUrl||e.url||""),this.url=Di.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=Di.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function ki(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,o=parseInt(e)||0,s=parseInt(s)||0,n={url:void 0,width:0,height:0};if((o<=s?o:s)<=r)n.url=t,n.width=o,n.height=s;else{s<=o?(n.width=Math.ceil(o*r/s),n.height=r):(n.width=r,n.height=Math.ceil(s*r/o));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";n.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?p(n,["url"]):n}class Fi{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=vi;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:o}=t,n=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new Fi({imageFormat:s,imageInfoArray:n,uuid:o})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:o}=Di.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),o)?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 Ui(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=Pi[e.toUpperCase()]||Pi.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],ki({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:Di.removeAuthToUrl(e.imageUrl)}))}}var $i=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(vi,Fi),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(o){var n,i,a,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createImageMessage"}),t=(console.log(Ei+" createImageMessage options:",o),null==(n=this._core.store.get("login"))?void 0:n.userId),s=null==(a=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:a.createMessage(Object.assign(Object.assign({},o),{from:t})),r=this._processImage(o);o.payload.file=r;var l={imageFormat:Pi.UNKNOWN,uuid:Di.generateUUID(r),file:r,imageInfoArray:[]},u=new Fi(l);return s.setElement(u),this._messageOptionsMap.set(s.clientSequence,o),console.log(Ei+" createImageMessage OK imageMessage:",s),e.end(),s}catch(o){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)&&t.call(e,o).end(),console.error(Ei+" createImageMessage error:",o),o}}upload(r){return h(this,void 0,void 0,function*(){console.log(Ei+" 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,o,s){return h(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:Mi,file:s,to:e,message:o,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{uploadOptions:e,response:t}=yield Ri.uploadToCOS(e);return this._parseResponse(e,t)})}_generateImageInfo(e){console.log(Ei+" generateImageInfo");var{location:e,fileSize:t,width:s,height:r,smallImageUrl:o,smallImageWidth:n,smallImageHeight:i,largeImageUrl:a,largeImageWidth:l,largeImageHeight:u,imageInfoArray:c}=e,e=Di.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):o&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:o,smallImageWidth:n,smallImageHeight:i}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return ki({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,o;for(var n of e)1===n.type?(r=n,r.size=t):2===n.type?(o=n,o.size=t):(s=n,s.size=t);return[Object.assign({},s),Object.assign({},o),Object.assign({},r)]}_parseResponse(r,o){return h(this,void 0,void 0,function*(){console.log(Ei+" parseResponse");try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,o,"thumb"),yield this._getImageInfoByUrl(t,o,"large")),Di.isSimpleCos()&&!Di.isPrivateNetWork()&&(yield this._getImageInfoArray(s,o),null!=o)&&o.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,o))}return o}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,o,n){return h(this,void 0,void 0,function*(){try{var e=Di.addAuthToUrl(r),{width:t=0,height:s=0}=yield Di.probeImageWidthHeight(e);o.width=t,o.height=s,"thumb"===n?(o.smallImageUrl=r,o.smallImageWidth=t,o.smallImageHeight=s):(o.largeImageUrl=r,o.largeImageWidth=t,o.largeImageHeight=s)}catch(e){console.warn(`Failed to get ${n} image info:`,e)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:Ni});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(Ei+" _processImage error:",e),e}}_processMiniAppImageFile(e){li(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=Di.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,o){return h(this,void 0,void 0,function*(){var e=Ei+" getDownloadIP domainName: "+r;try{var t,s=yield function(i,a){return h(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:i},o=e.generateProtocolData({servcmd:s,data:r}),n=o.head.seq+s;return yield t.sendPacket(o,{requestId:n})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=o.location.split("/"))[0]=s.str_final_ip,o.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(s,r){return h(this,void 0,void 0,function*(){var t=Ei+"._getImageInfoArray";try{var e=yield function(i,a){return h(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:i},o=e.generateProtocolData({servcmd:s,data:r}),n=o.head.seq+s;return yield t.sendPacket(o,{requestId:n})}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)),Gi.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:bi})}_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:Li});if(r>=wi)throw new s.ChatError({message:"File size exceeds limit: "+gi(wi)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let qi=2108,xi=2401,Vi="2.5.0",Bi="1.18.0",ji=104857600;function Ki(e,t){let r=e.split("."),o=t.split("."),n=Math.max(r.length,o.length);for(;r.length<n;)r.push("0");for(;o.length<n;)o.push("0");for(let s=0;s<n;s++){let e=parseInt(r[s]),t=parseInt(o[s]);if(e>t)return 1;if(e<t)return-1}return 0}class Wi{constructor(e){this.type=Ii,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:Di.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:o}=e;return new Wi({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:o})}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:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:Di.removeAuthToUrl(s),FileName:r,FileSize:o,UUID:e}}}_getFileInfo(e){return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(Di.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=di(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 Hi=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(Ii,Wi),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(s){var r,o,n,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createFileMessage"}),t=(console.log(Ei+" createFileMessage options:",s),this._checkVersion(),this._processFile(s.payload.file));s.payload.file=t;var i=null==(r=this._core.store.get("login"))?void 0:r.userId,a=null==(n=null==(o=this._core)?void 0:o.message.messageFactory)?void 0:n.createMessage(Object.assign(Object.assign({},s),{from:i})),l={uuid:Di.generateUUID(t),file:t},u=new Wi(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,s),console.log(Ei+" 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(Ei+" createFileMessage error:",s),s}}upload(s){return h(this,void 0,void 0,function*(){console.log(Ei+" 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=Di.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:xi});if(e.size>ji)throw new t({message:"File size exceeds limit: "+gi(ji)});if(0===e.size)throw new t({code:qi})}_performFileUpload(r,o,t){return h(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:Mi,file:t,to:e,message:o,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield Ri.uploadToCOS(e))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:o,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||n){let e=Di.extractFileFromInput(t);if(e)return e;throw new i({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||o){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:o}=null==(e=this._core)?void 0:e.utils,n=(null==(n=this._core)?void 0:n.helper)["ChatError"];if(e){if(!(s||r||o))throw new n({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&Ki(e,Vi)<0)throw new n({message:`WXChooseMessageFile requires SDK version ${Vi} or higher`});if(r&&Ki(e,Bi)<0)throw new n({message:`QQChooseMessageFile requires SDK version ${Bi} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Yi=2108,zi=2352,Ji=["mp4","quicktime","mov"],Qi=104857600;class Xi{constructor(e){this.type=Si,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:Di.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:Di.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:Di.addAuthToUrl(e.thumbUrl),snapshotUrl:Di.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:o,VideoUUID:n,ThumbUUID:i,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:p,ThumbDownloadFlag:_,ThumbUrl:g,SnapshotUrl:m}=e;return new Xi({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:o,videoUUID:n,thumbUUID:i,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:p,thumbDownloadFlag:_,thumbUrl:g,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;Di.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),Di.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),Di.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:o,videoUUID:n,thumbUUID:i,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:p,thumbDownloadFlag:_,thumbUrl:g,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:Di.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:o,VideoUUID:n,ThumbUUID:i,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:p,ThumbDownloadFlag:_,ThumbUrl:Di.removeAuthToUrl(g),SnapshotUrl:Di.removeAuthToUrl(m)}}}}var Zi=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(Si,Xi),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(s){var r,o,n,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"}),t=(console.log(Ei+" createVideoMessage options:",s),this._processVideo(s));s.payload.file=t;var i=null==(r=this._core.store.get("login"))?void 0:r.userId,a=null==(n=null==(o=this._core)?void 0:o.message.messageFactory)?void 0:n.createMessage(Object.assign(Object.assign({},s),{from:i})),l={videoFormat:t.videoFile.type,videoSecond:_i(t.videoFile.second,0),videoSize:t.videoFile.size,remoteVideoUrl:"",videoUrl:t.videoFile.url,videoUUID:Di.generateUUID(t.videoFile),thumbUUID:Di.generateUUID(t.videoFile,"jpg"),thumbWidth:t.width||200,thumbHeight:t.height||200,thumbUrl:t.thumbUrl,thumbSize:t.thumbSize,thumbFormat:"jpg"},u=new Xi(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(Ei+" createVideoMessage error:",s),s}}upload(r){return h(this,void 0,void 0,function*(){console.log(Ei+" 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=Di.addAuthToUrl(t);return e.updateVideoUrl(t),Di.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>Qi)throw new t({message:"File size exceeds limit: "+gi(Qi)});if(0===e.videoFile.size)throw new t({code:Yi});if(-1===Ji.indexOf(e.videoFile.type))throw new t({code:zi})}_performVideoUpload(r,o,s){return h(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:yi,file:s,to:e,message:o,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{response:e,uploadOptions:t}=yield Ri.uploadToCOS(e);return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,o;try{var n=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:i,IN_BROWSER:a}=null==(o=this._core)?void 0:o.utils;let t=e.payload["file"],s={};if(i&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url),a){let e=Di.extractFileFromInput(t);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,s=this._processWebVideoFile(t)}return t.videoFile=s,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(Ei+" _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(li(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:o}=e,o=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:o}}_getSnapshotInfoByUrl(o){return h(this,void 0,void 0,function*(){try{console.log(Ei+" _getSnapshotInfoByUrl url:",o);var e,t,s,r=((yield function(n,i){return h(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=i,r=t.generateCosSpecifiedData({servcmd:e,data:n}),o=r.head.seq+e;return yield s.sendPacket(r,{requestId:o})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:Di.getPlatform(),cover_name:hi(di(99999)),snapshot_url:o},this._core))||{})["download_url"];return(console.log(Ei+" _getSnapshotInfoByUrl OK snapshotUrl:",r),Di.isEmpty(r))?{}:(e=Di.addAuthToUrl(r),{width:t=0,height:s=0}=yield Di.probeImageWidthHeight(e),{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s})}catch(e){throw console.error(Ei+" _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 er{constructor(e){this.uploadProgress=0,this.type=fi,this.content={downloadFlag:2,second:e.second,size:e.size,url:Di.addAuthToUrl(e.url),remoteAudioUrl:Di.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:o}=e;return new er({url:e,downloadFlag:t,second:s,size:r,uuid:o})}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:o}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:Di.removeAuthToUrl(s),Download_Flag:t,Second:o,Size:r,UUID:e}}}}let tr=2108,sr=2300,or=20971520;var nr=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(fi,er),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(t){var s,r,e,o;try{let e=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(Ei+" createAudioMessage options:",t);t.payload["file"];var n=this._processAudioFile(t.payload.file),i=(t.payload.file=n,null==(o=this._core.store.get("login"))?void 0:o.userId),a=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},t),{from:i})),l={second:Math.floor((n.duration||n.second)/1e3),size:n.fileSize||n.size||1,url:n.tempFilePath||n.uri||n.url,uuid:Di.generateUUID(n)},u=new er(l);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,t),e.end(),a}catch(t){throw null!=(o=(e=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)&&o.call(e,t).end(),console.error(Ei+" createAudioMessage error:",t),t}}upload(s){return h(this,void 0,void 0,function*(){console.log(Ei+" 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=Di.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:sr});if(e.size>or)throw new t({message:"File size exceeds limit: "+gi(or)});if(0===e.size)throw new t({code:tr})}_performAudioUpload(r,o,t){return h(this,void 0,void 0,function*(){var e=o["to"],e={uploadFileType:Ti,file:t,to:e,message:o,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(o.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield Ri.uploadToCOS(e))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:s}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):s?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let ir={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}},rr={createImageMessage:ir,createAudioMessage:ir,createVideoMessage:ir,createFileMessage:ir},ar={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},cr={[vi]:$i,[Ii]:Hi,[Si]:Zi,[fi]:nr};var Ir,Sr,Er,Cr,Mr,yr,ur=new class{install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:o}}=(this._core=e)["constants"];$i.init(e),Hi.init(e),Zi.init(e),nr.init(e),Ri.init(e),Di.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:ar,params:rr})}sendMessage(r,o){return h(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,o)}catch(e){throw console.error("sendMessage error:",e),e}})}_upload(r){return h(this,void 0,void 0,function*(){var t,s;if(!0!==r._relayFlag)try{let t=cr[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=Ai.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}})}};let lr=new class{init(e){this.core=e}},dr=e=>{var{OuterConstant:t,utils:{isString:s}}=lr["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},pr=e=>{var{OuterConstant:t,utils:{isString:s}}=lr["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},hr=e=>{var{OuterConstant:t,utils:{isString:s}}=lr["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:lr.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 gr(t){var{utils:{isString:e}}=lr["core"],s=[];if(e(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}function mr(e){var t=lr.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 vr(e){var t=lr.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}function fr(e,t){var s=lr.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}!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(Ir=Ir||{}),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(Sr=Sr||{}),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(Er=Er||{}),function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(Cr=Cr||{}),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(Mr=Mr||{}),function(e){e[e.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",e[e.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",e[e.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"}(yr=yr||{});let Tr=0,Ar=1;class Or{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}}=lr["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}}=lr["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:o}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||o&&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=lr["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}}=lr["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var Dr=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:o},InnerEvent:{MESSAGE_PUSH:n,NEW_MESSAGE:i,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(r.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),e.registerWorkflowStep(r.RECEIVE_C2C_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(r.RECEIVE_C2C_NEW_MESSAGE,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(r.RECEIVE_GROUP_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t)["InnerEventSubType"]["GROUP_AT_TIPS"];t.subscribeInnerEvent(i,this._handleNewMessage,this),t.subscribeInnerEvent(n,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:r=[],isUnreadC2CMessage:o}=e.result[t.UNREAD_MESSAGE_SYNC]||{},n=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:o}),n=!0)}),n&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,o=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:n}=this._core.OuterConstant,i=!1;for(let s=0;s<o.length;s++){let e=o[s],t=""+n+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),i=!0)}i&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:o=!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:o}),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:o}=e;let n={};t?n=this._convertGroupAtTipsKey(t):s?n=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(n=Object.assign({},e)),n.__random=r,n.__sequence=o,this._groupAtTipsList.push(n)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,o=e.getCurrentUserID(),n=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==o){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:o}=this._core,n=(null==r?void 0:r.getLocalMessageList(t))||[];let i={};for(let e=(n.length||0)-1;0<=e;e--)if(!n[e].isDeleted){i=n[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===i.sequence&&r.lastMessage.lastTime===i.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(i)&&(i=void 0),r.updateLastMessage(i),e=!0),t.startsWith(o.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:o=!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))&&(o&&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:o}}=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=o(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 n=this._core["OuterConstant"],{conversationUpdateFieldList:i,isFromGetConversations:a,isInstantMessage:l,isUnreadC2CMessage:u=!1,updateUnreadCount:c}=e,d=[],t=null==i?void 0:i.length;for(let o=0;o<t;o++){let t=new Or(i[o]),{conversationID:s,type:r}=t;if(!vr(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===n.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===n.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:i[o].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:i[o].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:o}=e,e=this.getLocalConversation(e),n=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:i},common:{deepMerge:a}}=(!1===o&&n.push("lastMessage"),r&&n.push("isPinned"),this._core);r(o)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),i(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,n,[null,void 0,"",0,NaN])}_patchLastMessage(e){let o=this._core["OuterConstant"],{conversationID:t,lastMessage:n,isInstantMessage:i}=e,a=this.getLocalConversation(t);if(a&&n){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=n;i&&(e&&(a.lastMessage.payload=e),a.type===o.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=[],o=[],n=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?n:o).push(e)});var i=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(o.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n);this._updateConversationMapFromList(i)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:o,CONV_C2C:n}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===n){let e=t.replace(n,"");s.push(e)}else if(e===o){let e=t.replace(o,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:o},appStore:{userStore:n},user:s}=this._core,i=!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(""+o+s);if(r){let e=(null==(s=n.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,i=!0}}),i&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,o=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,o=!0)}),o&&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,o=!1;var n,i=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return i&&(n=i.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${n} newUnreadCount:`+a),n!==a)&&(i.unreadCount=a,(o=!0)===t)&&this.emitConversationListUpdate(),o}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:o=0,lastReadSequence:n=0}=e,i=null==t?void 0:t.getLocalMessageList(s);if(0!==i.length){let e=i["length"];for(let r=e-1;0<=r;r--){let e=i[r],t=o&&e.time>o,s=n&&e.sequence>n;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:o,CONVERSATION_UPDATED:n,LOGOUT:i,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(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(o,this._handleMessageModified,this),e.unSubscribeInnerEvent(n,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(i,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},Rr=new class{constructor(){this._name="SyncConversationList",this._pagingStatus=Ir.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:r}=this._core=e;s.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.WORKFLOW_STEP.CONVERSATION_RECOVER,this._syncConversationListOnReOnline,this),s.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,r.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===Ir.RESOLVED}_syncConversationListOnReOnline(){return h(this,void 0,void 0,function*(){return this._syncConversationList()})}_syncConversationList(){return h(this,void 0,void 0,function*(){yield this._pagingGetConversationList(!0),this._pagingStatus=Ir.RESOLVED,Dr.emitConversationListUpdate()})}_pagingGetConversationList(l){return h(this,void 0,void 0,function*(){try{this._pagingStatus=Ir.PENDING;var e=this._core["common"],t=yield function(n,i){return h(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:o}=n;return i.common.buildAndSendPacket({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:o,TopTimeStamp:r}})})}({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:r=[],TimeStamp:o,StartIndex:n,TopTimeStamp:i,TopStartIndex:a}=t||{};if(0<r.length){let e=this._getConversationOptions(r);Dr.updateLocalConversationList({conversationUpdateFieldList:e,isFromGetConversations:!0,updateUnreadCount:!0}),Dr.emitConversationListUpdate()}this._pagingTimeStamp=o,this._pagingStartIndex=n,this._pagingPinnedTimeStamp=i,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===Sr.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===Sr.C2C&&!vr(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===Er.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:gr(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t,{userID:e,nick:s,peerAvatar:r}=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:r}])}_computeIsPeerRead(e){var t=this._core["common"],{lastC2CMsgFromAccount:e,time:s,c2cPeerReadTime:r}=e;return e===t.getCurrentUserID()&&s<=r}_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===Er.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:gr(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="",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=this._core.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return p(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:r=[]}=e.lastMsg||{};return s(e)?{type:r[0]?r[0].type:null,payload:r[0]?this._amendLayersOverLimitProp(r[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=Ir.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)}},Lr=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return h(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:Rr.isSyncCompleted()}}})}_getConversationList(i){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(i))return Dr.getLocalConversationList();if(t(i))return 0===i.length?[]:Dr.getLocalConversationList().filter(e=>i.includes(e.conversationID));if(s(i)){let{type:t,markType:s,groupName:r,hasUnreadCount:o,hasGroupAtInfo:n}=i;return Dr.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,n))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},Nr=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return h(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return h(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=mr(t);Dr.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},br=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return h(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return h(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;Dr.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Gr=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return h(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:o},appStore:{groupStore:n},utils:{isEmpty:e}}=this._core,i={code:0,data:{}},a=Dr.getLocalConversation(u);if(hr(u))i.data.conversation=a;else{let t=!1;var l=dr(u)?s:r;if(e(a)&&(t=!0,a=new Or({conversationID:u,type:l})),console.log(this._name+`.getConversationProfile conversationID:${u} isNewConversation:`+t),null==(i.data.conversation=a)||!a.getProfileCompleted()){if(l===s){let e=u.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield Nr.get([e]))}if(l===r){let e=u.replace(r,"");if(!n.getGroup(e))return i;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==o&&(yield br.get([e]))}}}return i})}_handleC2CConversation(i,a){return h(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:o}}=this._core,n=i["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:yr.USER_OR_GRP_NOT_FOUND});i.userProfile=null==e?void 0:e.data[0];e=null==(t=o.getFriend(a))?void 0:t.remark,s(e)||i.remark===e||(i.remark=e),i.setProfileCompleted(),o=Dr.hasLocalConversation(n);console.log(this._name+`._handleC2CConversation conversationID:${n} hasLocalConversation: `+o),o?r.updateConversation(n,i):Dr.appendToPinnedConversation(i)})}_handleGroupConversation(r,o){return h(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:o}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),Dr.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):Dr.appendToPinnedConversation(r)})}},wr=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return Dr.getTotalUnreadMessageCount()}},Pr=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{ALL_MESSAGE_READ:n}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(o,n,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),Dr.markMessageAsRead({conversationID:e,lastReadTime:t}),Dr.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),Dr.markMessageAsRead({conversationID:e,lastReadSequence:t}),Dr.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(n){return h(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=n["conversationID"],s={code:0,data:{}},r=Dr.getLocalConversation(t);if(console.log(this._name+`.setMessageRead conversationID:${t} unreadCount:`+((null==r?void 0:r.unreadCount)||0)),r){var o=!(null!=(o=null==(o=this._core)?void 0:o.helper)&&o.isEmpty(r.groupAtInfoList));if(r.type===e.CONV_GROUP&&o&&this._deleteGroupAtTips(t),0!==r.unreadCount){if(r.type===e.CONV_C2C){let e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(t,e)}if(r.type===e.CONV_GROUP){let e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(t,e)}r.type===e.CONV_SYSTEM&&(r.unreadCount=0),Dr.emitConversationListUpdate()}}return s})}setAllMessageRead(){return h(this,arguments,void 0,function*(s={}){let{OuterConstant:{READ_ALL_MSG:e},ssoLog:t}=this._core,o=t.createSSOLogData({method:"setAllMessageRead"}),n=(s.scope||(s.scope=e),s)["scope"],i=this._generateSetAllMessageReadRequestData(n);if(i.allC2CMessageReadStatus===Tr&&0===i.groupMessageReadInfoList.length)return{code:0};try{let r=yield function(s){return h(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return lr.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(i);if(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&Dr.emitConversationListUpdate(),o.setLogInfo({message:`scope:${n} 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 o.setError(t).end(),t}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&Dr.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:o},appStore:t}=this._core,n=t.conversationStore.getConversationMap(),i=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of n)if(1<=t.unreadCount){if(i===Ar&&t.type===r){let e=this._getLocalMessageMaxTime(t);Dr.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===o){let t=s.replace(o,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);Dr.markMessageAsRead({conversationID:s,lastReadSequence:e})}}Dr.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:o,CONV_GROUP:n,READ_ALL_C2C_MSG:i},appStore:e}=this._core,a={allC2CMessageReadStatus:Tr,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===o&&a.allC2CMessageReadStatus===Tr){if(a.allC2CMessageReadStatus=Ar,r===i)break}else if(e===n){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:o}=this._core["utils"],n=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;o(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&n.push(e+`-${t}-`+s))}),n}_deleteGroupAtTips(i){return h(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+i);let e=Dr.getLocalConversation(i);if(e){var n=(null==e?void 0:e.groupAtInfoList)||[];if(0!==n.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,o=[...n];e({groupID:i.replace(s,"")})&&0===(o=n.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(i,!1):(yield function(t,s){return h(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:o.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+n.length),this._clearGroupAtInfoList(i))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=Dr.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&Dr.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 h(this,void 0,void 0,function*(){try{yield function(e,t){return h(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),Dr.markMessageAsRead({conversationID:e,lastReadTime:t}),Dr.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return h(this,void 0,void 0,function*(){try{yield function(s,r){return h(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),Dr.markMessageAsRead({conversationID:e,lastReadSequence:t}),Dr.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:o,READ_ALL_GROUP_MSG:n}=this._core["OuterConstant"],{type:e,scope:i,unreadCount:a}=e;return!(a<=0||(e!==t||![r,o].includes(i))&&(e!==s||![r,n].includes(i)))}},Ur=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,i){var{isArray:t}=this._core["utils"];if(t(e)){let o=this._core["OuterConstant"],n=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=Dr.getLocalConversation(""+o.CONV_C2C+t):2===e&&(r=Dr.getLocalConversation(""+o.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+i),i&&!r.isPinned&&(r.isPinned=!0,n=!0),!i)&&r.isPinned&&(r.isPinned=!1,n=!0)}),n&&Dr.emitConversationListUpdate(!0)}}pinConversation(e){return h(this,void 0,void 0,function*(){var{OuterConstant:t,common:s}=this._core,{conversationID:r,isPinned:o}=e,n={code:0,data:{conversationID:r}},i=Dr.getLocalConversation(r);if(i&&i.isPinned===o)return n;if(hr(r))return i&&(i.isPinned=o),Dr.emitConversationListUpdate(!0),n;try{let e=null;dr(r)?e={Type:1,To_Account:r.replace(t.CONV_C2C,"")}:pr(r)&&(e={Type:2,GroupId:r.replace(t.CONV_GROUP,"")});var a=yield function(r,o){return h(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return o.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:s.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core);if(console.log(this._name+`.pinConversation ok, conversationID:${r} isPinned:${o}.`),a){if(i)i.isPinned!==o&&(i.isPinned=o);else{let e=new Or({conversationID:r,type:dr(r)?t.CONV_C2C:t.CONV_GROUP,isPinned:o});Dr.setLocalConversation(r,e)}Dr.emitConversationListUpdate(!0)}return n}catch(e){throw console.error(this._name+".pinConversation fail:",e),e}})}},kr=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"],o=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&o.push(""+r.CONV_C2C+t),2===e&&o.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+o),this._deleteLocalConversationList(o)}}deleteConversation(t){return h(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:Mr.ONLY_CONVERSATIONID})):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return h(this,void 0,void 0,function*(){var{conversationIDList:s,clearHistoryMessage:r=!0,flag:o=0}=e;console.log(this._name+`._deleteConversation conversationIDList:${s} clearHistoryMessage:`+r);try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:yr.CONV_NOT_FOUND});return console.log(this._name+"._deleteConversation ok."),{code:0,data:o===Mr.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!!Dr.hasLocalConversation(e)&&((t=null==(t=Dr.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,n){return h(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,o={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(t.forEach(e=>{var t,s;Dr.hasLocalConversation(e)&&(t=(null==(t=Dr.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?o.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&o.conversationList.push({ToGroupid:s,Type:2}))}),0!==o.conversationList.length){var s=yield function(r,o){return h(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return o.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(o,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=>{Dr.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&Dr.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=Dr.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(Dr.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&Dr.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)}},Fr=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return h(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),Dr.hasLocalConversation(e))return null!=(e=Dr.getLocalConversation(e))&&e.setDraftText(t),Dr.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:yr.CONV_NOT_FOUND})})}},$r=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return h(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}=lr.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[l],t=yield function(s,r){return h(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=[],o=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),n=[],i=this._core["OuterConstant"];return a.forEach(e=>{n.push(""+i.CONV_C2C+e),o.push({userID:e})}),Dr.patchMessageRemindType(n,l),{code:0,data:{successUserIDList:o,failureUserIDList:r}}})}},qr=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,o){return h(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:o},this._core),!t(r)){let e=""+s.CONV_GROUP+r;Dr.patchMessageRemindType([e],o)}return{code:0,data:{groupID:r,messageRemindType:o}}})}},xr=new class{constructor(){this._name="SetMessageRemindType"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){let{helper:{isEmpty:t},OuterConstant:n}=this._core;e.forEach(e=>{var o=e["MuteNotificationsSync"];if(!t(o)){let{To_Account:e,MuteNotifications:t}=o,s=e.map(e=>""+n.CONV_C2C+e),r=mr(t);console.log(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),Dr.patchMessageRemindType(s,r)}})}setMessageRemindType(i){return h(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=i,{helper:o,utils:{isUndefined:n}}=this._core;try{if(!n(e))return console.log(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield qr.set(e,r);if(n(t))throw new o.ChatError({functionName:s,message:"userIDList or groupID is required"});return console.log(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield $r.set(t,r)}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}})}},Vr=new class{init(e){console.log("ConversationAction.init"),this._core=e,Rr.init(e),Lr.init(e),Gr.init(e),wr.init(e),Pr.init(e),Ur.init(e),kr.init(e),Fr.init(e),xr.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:o,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:i}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,o,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,i,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}handleLoginSuccess(){Rr.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"];kr.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];Ur.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];Ur.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;Pr.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;xr.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;Pr.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:o,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:i}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,i,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Br=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(i){return h(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=i,{startTime:r=0,endTime:o=0}=this._calcStartAndEndTime(i),n=yield function(n){return h(this,void 0,void 0,function*(){var e=lr.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:o}=n;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:o}})})}({messageRemindType:this._getType(t),startTime:r,endTime:o,isRepeated:s?Cr.ON:Cr.OFF});return{code:0,data:{errorCode:n.ErrorCode,errorInfo:n.ErrorInfo}}}catch(e){fr("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:o=!0}=e,n=new Date,n=new Date(n.getFullYear(),n.getMonth(),n.getDate(),e,t,s),e=Math.round(n.getTime()/1e3);let i=o&&86400<=r?e+86400:e+r;return{startTime:e,endTime:i}}_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]}},jr=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 h(this,void 0,void 0,function*(){try{var e=yield function(){return h(this,void 0,void 0,function*(){var e=lr.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){fr("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:o,EndTime:n,IsRepeated:i}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:o,endTime:n,isRepeated:i===Cr.ON}}},Kr=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,$r.init(e),qr.init(e),Nr.init(e),br.init(e),Br.init(e),jr.init(e)}};let Wr=e=>!dr(e)&&!pr(e)&&!hr(e),Hr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Wr(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Wr(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Wr(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}}=lr["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&Wr(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(Wr(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=>!(!dr(e)&&!pr(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}}},Yr={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var zr=new class{install(e){lr.init(e),Vr.init(e),Kr.init(e),Dr.init(e),e.helper.registerValidateConfig({auth:Yr,params:Hr})}handleLoginSuccess(){Vr.handleLoginSuccess()}};let Jr=new class{init(e){this.core=e}},Qr="AVChatRoom",Xr="AV_HISTORY_MSG",Zr="GRP_COUNTER",ea="Set",ta="Increase",sa="Decrease",oa=0,na=1,ia=2,ra=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],aa=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],ca=["Role","JoinTime","MsgFlag","MsgSeq"],ua=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],la=0,da=1,pa="notStart",ha="resolved",_a="rejected",ga=10018,ma=11e3,va=2,fa=["Owner","Admin","Member"],Ia=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Sa=0,Ea=1,Ca=2,Ma=4,ya=1,Ta=2,Aa=3,Oa=4,Da=5,Ra=1,La=0,Na=4,ba=6,Ga=1,wa=2,Pa=3,Ua=4,ka=5,Fa=6,$a=400,qa=300,xa={from:!0,groupID:!0,groupName:!0,to:!0},Va={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Ba=2,ja=4,Ka=5,Wa=7,Ha=8,Ya=15,za=20,Ja=21,Qa=2600,Xa=2602,Za=2603,ec=2620,tc=2621,sc=2623,oc=2660,nc=2661,ic=2681,rc=2683,ac=2684,cc=2685,uc=2687,lc=3122,dc=10018,pc=e=>e===Jr.core.OuterConstant.GRP_PUBLIC,hc=e=>e===Jr.core.OuterConstant.GRP_AVCHATROOM,_c=(r,e)=>{var t=Jr.core.utils["isArray"];if(!t(r)||!t(e))return!1;let o=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,o=!0):(r.push({key:t,value:e}),o=!0)}),o},gc=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:o,Value:n}=s[e];r.push({key:o,value:n})}return r},mc=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:o,value:n}=s[e];r.push({Key:o,Value:n})}return r};function vc(e,t){var s=Jr.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:lc,replacement1:e})}function fc(e,t){var s=Jr.core["helper"],s=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(e+" fail:",s),s}let Ic=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Sc{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}=Jr.core["utils"];for(t in e)Ic.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:o},common:{deepMerge:n}}=Jr.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),o(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&_c(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),n(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&n(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:o,excludedUnreadSequenceList:n}=e,i=Jr.core["common"]["deepMerge"];i(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:o,excludedUnreadSequenceList:n},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var Ec=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 Sc(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 Cc(i,a){return h(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:o,responseFilter:n}=i;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:o,ResponseFilter:n,SupportTopic:r,NeedAppDefineData:1}})})}let Mc=function(e){return{code:0,data:e||{}}};var yc=new class{constructor(){this._name="GetGroupList",this._pagingStatus=pa,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 h(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}),Ec.updateLocalGroup(e),Ec.getLocalGroupList()}return console.log(this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===_a||this._pagingStatus===pa?this._syncGroupList().then(()=>{var e=Ec.getLocalGroupList();return Mc({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw console.error(this._name+".getGroupList fail:",e),e}):(e=Ec.getLocalGroupList(),console.log(this._name+".getGroupList return group count:"+e.length),Mc({groupList:e,isSyncCompleted:this._isSyncCompleted()}))})}_syncGroupList(){return h(this,void 0,void 0,function*(){this._pagingStatus===pa&&Ec.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=ha,this._groupListTreeShaking(t),Ec.updateLocalGroup(t);var s=Ec.getLocalGroupList();return console.log(this._name+"._syncGroupList ok, count:"+s.length),Ec.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=_a,console.error(this._name+"._syncGroupList fail:",e),e}})}_pagingGetGroupList(e){return h(this,void 0,void 0,function*(){var{isCommunityRelay:o=!1,groupList:n}=e;let i,{limit:a,offset:l}=e;var u=[...ra];o&&(i=this._core.OuterConstant.GRP_COMMUNITY,u.push("AtInfoList"));try{let e=yield Cc({type:i,limit:a,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:u,SelfInfoFilter:[...ca]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);n.push(...r);var c=l+a,d=!(c<s),h=`offset:${l} limit:${a} total:${s} isCompleted:${d} current:${n.length} isCommunityRelay:`+o;return console.log(this._name+"._pagingGetGroupList ok. "+h),o?d?n:(l=c,this._pagingGetGroupList({isCommunityRelay:!0,limit:a,offset:l,groupList:n})):d?(console.log(this._name+"._pagingGetGroupList start to get community list"),l=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:a,offset:l,groupList:n})):(l=c,this._pagingGetGroupList({limit:a,offset:l,groupList:n}))}catch(e){if(e.ErrorCode===ga)return console.warn(this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+a),this._pagingGetGroupList({isCommunityRelay:o,limit:50,offset:l,groupList:n});if(o)return e.code===ma&&console.log(this._name+"._pagingGetGroupList ok. community unavailable"),n;throw e}})}_pagingGetJoinedCommunityList(e){return h(this,void 0,void 0,function*(){var{common:{getCurrentUserID:o},OuterConstant:n}=this._core,i=e["groupList"];let{limit:a,offset:l}=e;try{let e=yield Cc({limit:a,offset:l,type:n.GRP_COMMUNITY,memberAccount:o(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ra],SelfInfoFilter:[...ca]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);i.push(...r);var u=l+a,c=!(u<s),d=`offset:${l} limit:${a} total:${s} isCompleted:${c} current:`+i.length;return console.log(this._name+"._pagingGetJoinedCommunityList ok. "+d),c?i:(l=u,this._pagingGetJoinedCommunityList({limit:a,offset:l,groupList:i}))}catch(e){if(e.code===dc)return console.warn(this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+a),this._pagingGetJoinedCommunityList({limit:50,offset:l,groupList:i});throw e}})}_groupListTreeShaking(s){var r=new Map([...Ec.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var o=[...r.keys()];for(let e=0,t=o.length;e<t;e++)Ec.deleteLocalGroup(o[e])}_isSyncCompleted(){return this._pagingStatus===ha}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:o,ApplyJoinOption:n,CreateTime:i,FaceUrl:a,GroupId:l,Introduction:u,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:h,MemberNum:p,MaxMemberNum:_,MuteAllMember:g,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:S,LastRecallTime:E,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],o=gc(o),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);r.push({groupCustomField:o,joinOption:n,createTime:i,avatar:a,groupID:l,introduction:u,inviteOption:c,lastInfoTime:d,lastMsgTime:h,memberCount:p,maxMemberCount:_,muteAllMembers:g,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:S,selfInfo:C,_lastRevokedTime:E,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:o}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:o}}_convertAtInfoList(r,e){if(0===e.length)return[];let o=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;o.push({groupID:r,groupAtType:e,sequence:t,from:s})}),o}},Tc=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(a){return h(this,void 0,void 0,function*(){var n;this._preCheckParams(a);try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(p,_){return h(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:o,avatar:n,maxMemberNum:i,joinOption:a,inviteOption:l,memberList:u,groupCustomField:c,isSupportTopic:d}=p;let h;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:o,FaceUrl:n,MaxMemberCount:i,ApplyJoinOption:a,InviteJoinOption:l,MemberList:h=u?u.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?mc(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:r,OverJoinedGroupLimit_Account:o=[]}=s||{};console.log(`${this._name}.createGroup ok, type:${a.type} groupID:${r} overLimitUserIDList:`+o),e(a.memberList)||e(o)||(a.memberList=null==(n=a.memberList)?void 0:n.filter(e=>o.includes(e.userID))),Ec.updateLocalGroup([Object.assign(Object.assign({},a),{groupID:r})]);var i=Ec.getLocalGroup(r);return this._notNeedSendCustomMessage(a)||(this._sendCustomMessage(r,a.type),Ec.emitGroupListUpdate()),Mc({group:i})}catch(e){throw console.error(this._name+".createGroup fail:",e),e}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:o},common:{isCommunity:n}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:o}=Jr.core.OuterConstant;return[e,t,s,r,o]})().includes(t))throw new this._core.helper.ChatError({code:Qa});if(!n({type:t})){if(r&&n({groupID:s}))throw new this._core.helper.ChatError({code:Xa});o(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||o(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||o(e.joinOption)||(e.joinOption=void 0),n({type:t})){if(r&&!n({groupID:s}))throw new this._core.helper.ChatError({code:Xa});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!hc(e)}_canIUseJoinOption(e){return pc(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",o=la;t===s.GRP_COMMUNITY&&(r="Create Community",o=da);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:o,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,{})}},Ac=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,o=(console.log(this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];o(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:o,operation:n}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];n!==Da&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:o,operation:n})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),console.log(this._name+`.refreshGroupAttributesCache. operation:${n} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;s!==Aa?s!==Oa?(s===ya&&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:o=[]}=e,n={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===o.length)for(let e of t.keys())n[e]=(null==(s=t.get(e))?void 0:s.value)||"";else o.forEach(e=>{t.has(e)&&(n[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:o}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+o.length),0===r.length&&0===o.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:o}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],o=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&o.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:o}}_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={}}},Oc=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Qr)})}dismissGroup(t){return h(this,void 0,void 0,function*(){console.log(this._name+".dismissGroup groupID:"+t);try{yield function(e,t){return h(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=Ec.getLocalGroup(t)["type"];return Ec.deleteLocalGroup(t),Ec.emitGroupListUpdate(),Ac.deleteGroupAttributesCache(t),Mc({groupID:t,type:e})}catch(e){throw console.error(this._name+".dismissGroup fail:",e),e}})}},Dc=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return h(this,void 0,void 0,function*(){let{groupID:o,groupCustomFieldFilter:e}=t,n={groupIDList:[o],responseFilter:{GroupBaseInfoFilter:[...ra],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...ua]}};try{let e=yield this.getGroupProfileAdvance(n),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!Ec.hasLocalGroup(o)&&hc(t[0].type)?new Sc(t[0]):(Ec.updateLocalGroup(t),Ec.getLocalGroup(o))).isSupportTopic||Ec.updateConversationGroupProfile(o),console.log(this._name+".getGroupProfile ok."),Mc({group:r})}catch(e){throw console.error(this._name+".getGroupProfile fail:",e),e}})}getGroupProfileAdvance(a){return h(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})),o=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),n=[],i=[];return o.forEach(e=>{n.push(...e.successGroupList),i.push(...e.failureGroupList)}),{successGroupList:n,failureGroupList:i}})}_getGroupProfileAdvance(e){return h(this,void 0,void 0,function*(){let{isCommunityProfile:t=!1}=e,i=p(e,["isCommunityProfile"]);if(0===i.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return h(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}})})}(i,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),{isUndefined:r}=this._core["utils"],o=s.filter(e=>r(e.errorCode)||0===e.errorCode),n=s.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return console.log(this._name+"._getGroupProfileAdvance ok, groupID:"+i.groupIDList.join(",")),{successGroupList:o,failureGroupList:n}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:o,ApplyJoinOption:n,CreateTime:i,FaceUrl:a,GroupId:l,InfoSeq:u,Introduction:c,InviteJoinOption:d,LastInfoTime:h,LastMsgTime:p,MaxMemberNum:_,MemberNum:g,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:I,Owner_Account:S,ShutUpAllMember:E,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:A,ErrorInfo:T}=s[e],o=gc(o),y=this._convertMembers(y);r.push({groupCustomField:o,joinOption:n,createTime:i,avatar:a,groupID:l,infoSequence:u,introduction:c,inviteOption:d,lastInfoTime:h,lastMsgTime:p,maxMemberCount:_,memberCount:g,muteAllMembers:m,name:v,nextMessageSeq:f,notification:I,ownerID:S,shutUpAllMember:E,muteUntil:C,type:M,members:y,errorCode:A,errorInfo:T})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,MsgFlag:a,MsgSeq:l,NameCard:u,Role:c}=s[e],o=gc(o);r.push({memberCustomField:o,joinTime:n,userID:i,messageRemindType:a,sequence:l,nameCard:u,role:c})}return r}},Rc=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:o=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<n&&n<t||(o.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:o}=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:o,counters:t,avChatRoomKey:e})}}setGroupCounters(t,o){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(o).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()}},Lc=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Qr)})}joinGroup(e){return h(this,void 0,void 0,function*(){var t=e["groupID"];try{if(Ec.hasLocalGroup(t))try{return yield Dc.getGroupProfile({groupID:t}),Mc({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS})}catch(e){console.warn(this._name+`.joinGroup ${t} was unjoined, start to join!`),Ec.deleteLocalGroup(t)}return yield this._applyJoinGroup(e)}catch(e){throw console.error(this._name+".joinGroup fail:",e),e}})}_applyJoinGroup(c){return h(this,void 0,void 0,function*(){var{OuterConstant:t,helper:e}=this._core,s=c["groupID"],r=Object.assign({},c),e=e.checkBusinessCapabilityBits(Xr),r=(e&&(r.historyMessageFlag=1),yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(r,this._core)),{Type:r,JoinedStatus:o,LongPollingKey:n,StartSeq:i,HugeGroupFlag:a,AVChatRoomKey:l,RspMsgList:u=[]}=r||{},e=`groupID:${s} joinedStatus:${o} longPollingKey:${n} startSeq:${i} avChatRoomFlag:${a} canGetAVChatRoomHistoryMsg:${e}, historyMessageCount:`+u.length;if(console.log(this._name+"._applyJoinGroup ok, "+e),o===t.JOIN_STATUS_WAIT_APPROVAL)return Mc({status:t.JOIN_STATUS_WAIT_APPROVAL,group:{groupID:s,type:r}});if(o!==t.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:oc});{let e=null;try{e=(yield Dc.getGroupProfile({groupID:s})).data.group}catch(t){e=new Sc({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:n,startSequence:i,avChatRoomKey:l,historyMessageList:u})}})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(Ac.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),Rc.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),Mc(e)):(Ec.updateLocalGroup([t]),Ec.emitGroupListUpdate(),Mc({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}},Nc=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Qr)})}quitGroup(t){return h(this,void 0,void 0,function*(){if(!Ec.hasLocalGroup(t))throw new this._core.helper.ChatError({code:sc});try{yield function(e,t){return h(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=Ec.getLocalGroup(t)["type"];return Ec.deleteLocalGroup(t),Ec.emitGroupListUpdate(),Ac.deleteGroupAttributesCache(t),Mc({groupID:t,type:e})}catch(e){throw console.error(this._name+".quitGroup fail:",e),e}})}},bc=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(f){return h(this,void 0,void 0,function*(){console.log(this._name+".searchGroupByID groupID:"+f);try{var e=yield function(t,s){return h(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...aa]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(f,this._core),{GroupInfo:t=[]}=e||{},{AppDefinedData:s=[],ApplyJoinOption:r,CreateTime:o,FaceUrl:n,Introduction:i,InviteJoinOption:a,MaxMemberNum:l,MemberNum:u,Name:c,Owner_Account:d,Type:p,ErrorCode:_,ErrorInfo:g}=t[0];if(0!==_)throw new this._core.helper.ChatError({code:_,message:g});console.log(this._name+".searchGroupByID ok.");var m=gc(s),v=new Sc({groupID:f,name:c,avatar:n,introduction:i,joinOption:r,inviteOption:a,maxMemberCount:l,memberCount:u,type:p,ownerID:d,createTime:o,groupCustomField:m});return Mc({group:v})}catch(e){throw console.error(this._name+".searchGroupByID fail:",e),e}})}},Gc=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(o){return h(this,void 0,void 0,function*(){let t=o["groupID"],{isUndefined:s}=this._core["utils"],r=Ec.getLocalGroup(t);if(r){let e=r["type"];this._canIUseJoinOption(e)||s(o.joinOption)||(console.warn(this._name+".updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom"),o.joinOption=void 0)}s(o.muteAllMembers)||(o.muteAllMembers=!0===o.muteAllMembers?"On":"Off");try{return yield function(u,c){return h(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:o,muteAllMembers:n,joinOption:i,inviteOption:a,groupCustomField:l}=u,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:o,ShutUpAllMember:n,ApplyJoinOption:i,InviteJoinOption:a,AppDefinedData:l?mc(l):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(o,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),r?(r.updateGroup(o),Ec.emitGroupListUpdate()):r=new Sc(o),Mc({group:r})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}})}_canIUseJoinOption(e){return pc(e)||this._core.common.isCommunity({type:e})}},wc=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(a){return h(this,void 0,void 0,function*(){let s="changeGroupOwner",{groupID:e,newOwnerID:t}=a,r=Ec.getLocalGroup(e),{helper:o,OuterConstant:n,common:{getCurrentUserID:i}}=this._core;if((null==r?void 0:r.type)===n.GRP_AVCHATROOM)throw new o.ChatError({functionName:s,code:ec});if(t===i())throw new o.ChatError({functionName:s,code:tc});console.log(`${this._name}.${s} groupID:${e} newOwnerID:`+t);try{return yield function(s,r){return h(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,Ec.emitGroupListUpdate(),Mc({group:r})}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}})}},Pc=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(Qr)})}getGroupOnlineMemberCount(o){return h(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount",e=Ec.hasLocalGroup(o);if(console.log(`${this._name}.${s} groupID:${o} hasLocalGroup:`+e),!e)return Mc({memberCount:0});let r=Date.now();if(this._onlineMemberCountMap.has(o)){let e=this._onlineMemberCountMap.get(o),{lastReqTime:t=0,memberCount:s=0}=e||{};if(r-t<=6e4)return Mc({memberCount:s})}try{let e=yield function(e,t){return h(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(o,this._core),{OnlineMemberNum:t=0}=e||{};return this._onlineMemberCountMap.set(o,{lastReqTime:Date.now(),memberCount:t}),console.log(`${this._name}.${s} ok. groupID:${o} memberCount:`+t),Mc({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}})}},Uc=new class{init(e,t){console.log("GroupAction.init"),yc.init(e),Tc.init(e),Oc.init(e,t),Lc.init(e,t),Nc.init(e,t),bc.init(e),Dc.init(e),Gc.init(e),wc.init(e),Pc.init(e,t)}dismissGroup(e){return Oc.dismissGroup(e)}joinGroup(e){return Lc.joinGroup(e)}quitGroup(e){return Nc.quitGroup(e)}getGroupOnlineMemberCount(e){return Pc.getGroupOnlineMemberCount(e)}},kc=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return h(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 Mc({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(n){return h(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=n||{},r=this._core["common"];let o;try{o=yield function(o,n){return h(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;o={}}var{NextStartTime:e=0,PendencyList:t=[]}=o||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},n),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=p(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:o,From_Account:n,GroupId:i,GroupName:a,PendencyType:l,To_Account:u}=e;return{handled:e,messageKey:t,applicant:n,applicantNick:o,groupID:i,groupName:a,authentication:r,applicationType:l,userID:u,note:s}}},Fc=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return h(this,void 0,void 0,function*(){let s="handleGroupApplication",t=e["application"],r=this._handleParams(e);try{(null==t?void 0:t.applicationType)===va?yield function(i,a){return h(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:o,invitee:n}=i;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:o,Invited_Account:n}})})}(r,this._core):yield function(i,a){return h(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:o,messageKey:n}=i;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:o,MsgKey:n}})})}(r,this._core),console.log(this._name+`.${s} ok.`);let e=Ec.getLocalGroup(r.groupID);return Mc({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 o,n,i,a,l;if(s){let e=(s||{})["payload"];o=e.operatorID,n=null==(s=e.groupProfile)?void 0:s.groupID,i=e.authentication,a=e.messageKey}else o=(null==r?void 0:r.applicant)||"",n=(null==r?void 0:r.groupID)||"",i=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return(null==r?void 0:r.applicationType)===va&&(l=r.userID),{handleAction:e,handleMessage:t,applicant:o,invitee:l,groupID:n,authentication:i,messageKey:a}}},$c=new class{init(e){console.log("GroupApplication.init"),kc.init(e),Fc.init(e)}};let qc=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}}=Jr["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&&_c(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function xc(a,l){return h(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:o,memberCustomField:n}=a;let i;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:o,AppMemberDefinedData:i=n?mc(n):i};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var Vc=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Qr)})}getGroupMemberList(r){return h(this,void 0,void 0,function*(){let n="getGroupMemberList",{groupID:i,offset:a=0,count:e=100,role:t="",filter:s=""}=r;console.log(`${this._name}.${n} groupID:${i} offset:${a} count:${e} role:${t} filter:`+s);var l=Ec.getLocalGroup(i),u=100<e?100:e,c={groupID:i,offset:a,limit:u,memberRoleFilter:fa.includes(t)?[t]:void 0,memberInfoFilter:Ia};try{let e=yield function(n,i){return h(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:r,memberInfoFilter:o}=n;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:r,MemberInfoFilter:o}})})}(c,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{};console.log(`${this._name}.${n} ok, totalMemberCount:${s} next:`+r);var{utils:{isArray:d,isEmpty:p},common:{isCommunity:_}}=this._core;if(l&&(l.memberCount=s),!d(t)||0===t.length)return Mc({memberList:[],offset:0});let o=a+u;_({groupID:i})&&(o=p(r)?0:r),t.length<u&&(o=0);var g=this._convertMemberInfo(t),g=yield this._patchAvatarAndNick(g),m=this._generateGroupMember(g);return Mc({memberList:m,offset:o})}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}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,OnlineStatus:a,Role:l,ShutUpUntil:u}=s[e],o=gc(o);r.push({userID:i,joinTime:n,onlineStatus:a,role:l,muteUntil:u,memberCustomField:o})}return r}_patchAvatarAndNick(n){return h(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],o=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;o.has(e.userID)&&({nick:t="",avatar:s=""}=o.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var o=new qc(s[e]);r.push(o)}return r}},Bc=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(t){return h(this,void 0,void 0,function*(){let s="getGroupMemberProfile",{groupID:r,userIDList:o,memberCustomFieldFilter:n}=t,e=Ec.getLocalGroup(r),{helper:i,utils:{isArray:a}}=this._core;if(e&&hc(e.type))throw new i.ChatError({functionName:s,replacement1:s,code:uc});50<o.length&&(console.warn(`${this._name}.${s} userIDList length:${o.length} exceeds limit 50`),o.splice(50));try{let e=yield function(o,n){return h(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:o,memberCustomFieldFilter:n,memberInfoFilter:[...Ia]},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),Mc({memberList:u})):Mc({memberList:[]})}catch(e){let t=new i.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,OnlineStatus:a,Role:l,ShutUpUntil:u}=s[e],o=gc(o);r.push({userID:i,joinTime:n,onlineStatus:a,role:l,muteUntil:u,memberCustomField:o})}return r}_getMemberAvatarAndNick(n){return h(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],o=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;o.has(e.userID)&&({nick:t="",avatar:s=""}=o.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var o=new qc(s[e]);r.push(o)}return r}},jc=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(t){return h(this,void 0,void 0,function*(){let i="addGroupMember",{groupID:a,userIDList:e}=t,l=Ec.getLocalGroup(a),s=this._core["helper"];if(l&&hc(l.type))throw new s.ChatError({functionName:i,code:nc});var u=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return h(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:o,overLimitUserIDList:n}=this._handleResult(t);return console.log(`${this._name}.${i} groupID:${a} ok, successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${o} overLimitUserIDList:`+n),Mc({failureUserIDList:s,successUserIDList:r,existedUserIDList:o,overLimitUserIDList:n,group:l})}catch(e){let t=new s.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}})}_handleResult(e){let s=[],r=[],o=[],n=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;e===Sa?s.push(t):e===Ea?r.push(t):e===Ca?o.push(t):e===Ma&&n.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:o,overLimitUserIDList:n}}},Kc=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Qr)})}deleteGroupMember(i){return h(this,void 0,void 0,function*(){let s="deleteGroupMember",{groupID:e,userIDList:t}=i,r=Ec.getLocalGroup(e),{helper:o,utils:{isUndefined:n}}=this._core;if(n(r))throw new o.ChatError({functionName:s,code:Za});20<t.length&&(console.warn(`${this._name}.${s} userIDList length:${t.length} exceeds limit 20`),t.splice(20));try{return yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return o.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),Mc({group:r,userIDList:t})}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}})}},Wc=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(i){return h(this,void 0,void 0,function*(){let r="setGroupMemberMuteTime",t=this._core["helper"];this._preCheckSettingMuteParams(i);try{yield xc(i,this._core);let{groupID:e,userID:t,muteTime:s}=i;console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} muteTime:`+s);var o=Ec.getLocalGroup(e),n=new qc({userID:t,muteTime:s});return Mc({group:o,member:n})}catch(e){o=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:`,o),o}})}_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:cc})}},Hc=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(i){return h(this,void 0,void 0,function*(){let r="setGroupMemberRole",t=this._core["helper"];this._preCheckSettingRoleParams(i);try{yield xc(i,this._core);let{groupID:e,userID:t,role:s}=i;console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} role:`+s);var o=Ec.getLocalGroup(e),n=new qc({userID:t,role:s});return Mc({group:o,member:n})}catch(e){o=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:`,o),o}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:o,OuterConstant:n,common:{isCommunity:i}}=this._core,a=Ec.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==n.GRP_MBR_ROLE_OWNER)throw new o.ChatError({functionName:"setGroupMemberRole",code:ic});if(t===r.get("login").userId)throw new o.ChatError({functionName:"setGroupMemberRole",code:ac});a=[...fa];if(i({groupID:e})&&a.push(n.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new o.ChatError({functionName:"setGroupMemberRole",code:rc})}},Yc=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(l){return h(this,void 0,void 0,function*(){let o="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(l);try{let{groupID:e,userID:t=n(),nameCard:s}=l,r={groupID:e,userID:t,nameCard:s};yield xc(r,this._core),console.log(`${this._name}.${o} ok, groupID:${e} userID:${t} nameCard:`+s);var i=Ec.getLocalGroup(e),a=new qc({userID:t,nameCard:s});return Mc({group:i,member:a})}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}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=Ec.getLocalGroup(e);if(hc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:uc})}},zc=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(l){return h(this,void 0,void 0,function*(){let o="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingCustomFiledParams(l);try{let{groupID:e,userID:t=n(),memberCustomField:s}=l,r={groupID:e,userID:t,memberCustomField:s};yield xc(r,this._core),console.log(`${this._name}.${o} ok, groupID:${e} userID:${t} memberCustomField:`+JSON.stringify(s));var i=Ec.getLocalGroup(e),a=new qc({userID:t,memberCustomField:s});return Mc({group:i,member:a})}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}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=Ec.getLocalGroup(e);if(hc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:uc})}},Jc=new class{init(e,t){console.log("GroupMember.init"),Vc.init(e,t),Bc.init(e),jc.init(e),Kc.init(e,t),Wc.init(e),Hc.init(e),Yc.init(e),zc.init(e)}getGroupMemberList(e){return Vc.getGroupMemberList(e)}deleteGroupMember(e){return Kc.deleteGroupMember(e)}},Qc=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return h(this,void 0,void 0,function*(){var t="getGroupCounters";try{vc(t,Zr);var e,s,r,{groupID:o,keyList:n=[]}=l,{avChatRoomKey:i,lastUpdateTime:a}=Rc.getLocalGroupCounters(o);return Date.now()-a>=this._getExpireTime()&&(e=yield function(o){return h(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=o,r=Jr.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:o,keyList:n,avChatRoomKey:i}),{GroupCounter:s=[],GroupCounterSeq:r}=e,Rc.updateLocalGroupCounters({groupID:o,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:Rc.getLocalCounters(o,n)}}}catch(e){fc(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)}},Xc=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 h(this,void 0,void 0,function*(){return this._handleCounterOperation(ea,e)})}increaseGroupCounter(e){return h(this,void 0,void 0,function*(){return this._handleCounterOperation(ta,e)})}decreaseGroupCounter(e){return h(this,void 0,void 0,function*(){return this._handleCounterOperation(sa,e)})}_handleCounterOperation(a,l){return h(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{vc(t,Zr);var{groupID:e,key:s,value:r=0}=l,o=Rc.getLocalGroupCounters(e)["avChatRoomKey"],n=a===ea?this._convertObjectToList(l.counters):[{Key:s,Value:r}],i=yield this._updateGroupCounters({groupID:e,counterList:n,avChatRoomKey:o,mode:a});return Rc.setGroupCounters(e,i),{code:0,data:{counters:i}}}catch(e){fc(t,e)}})}_updateGroupCounters(n){return h(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=n,o=Jr.core["common"];return o.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}))}},Zc=new class{init(e){this._core=e,Qc.init(e),Xc.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;e!==oa&&e!==ia||this._processAndNotifyCounterUpdate(r,t,s),e===na&&Rc.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:o}=this._core;Rc.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{o.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){Rc.reset()}},eu=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return h(this,void 0,void 0,function*(){let r="initGroupAttributes",{groupID:o,groupAttributes:n}=e,{serverMainSequence:i,avChatRoomKey:a}=Ac.getGroupAttributesCache(o),l=Ac.convertKeyValueMapToList(n);try{let e=yield function(o,n){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:a,groupAttributeList:l,mainSequence:i},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${r} ok. groupID:${o} serverMainSequence:`+t);var u=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return Ac.saveGroupAttributesCacheValuesCopy(o),Ac.refreshGroupAttributesCache({groupID:o,serverMainSequence:t,groupAttributeList:u,operation:ya}),Ac.emitGroupAttributesUpdated(o),Mc({groupAttributes: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}})}},tu=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return h(this,void 0,void 0,function*(){let r="setGroupAttributes",{groupID:o,groupAttributes:n}=e,{serverMainSequence:i,avChatRoomKey:a,values:l}=Ac.getGroupAttributesCache(o),u=Ac.convertKeyValueMapToList(n).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(o,n){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:a,groupAttributeList:u,mainSequence:i},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${r} ok. groupID:${o} serverMainSequence:`+t);var c=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return Ac.saveGroupAttributesCacheValuesCopy(o),Ac.refreshGroupAttributesCache({groupID:o,serverMainSequence:t,groupAttributeList:c,operation:Ta}),Ac.emitGroupAttributesUpdated(o),Mc({groupAttributes: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}})}},su=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(a){return h(this,void 0,void 0,function*(){let s="deleteGroupAttributes",{groupID:e,keyList:t=[]}=a;try{var{resultList:r,serverMainSequence:o,operation:n,groupAttributeList:i}=(0===t.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,t))||{};return console.log(`${this._name}.${s} ok. groupID:${e} operation: `+n),Ac.saveGroupAttributesCacheValuesCopy(e),Ac.refreshGroupAttributesCache({groupID:e,serverMainSequence:o,groupAttributeList:i,operation:n}),Ac.emitGroupAttributesUpdated(e),Mc({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(i,a){return h(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=Ac.getGroupAttributesCache(i),r=[],o=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},o.push({key:e,seq:t}),r.push(e))});var n=((yield function(o,n){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:t,groupAttributeList:o,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:n,groupAttributeList:o,operation:Oa}})}_clearGroupAttributes(r){return h(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=Ac.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return o.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:Aa}})}},ou=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(a){return h(this,void 0,void 0,function*(){let s="getGroupAttributes",t=a["groupID"],{avChatRoomKey:r,lastUpdateTime:e,localMainSequence:o,serverMainSequence:n}=Ac.getGroupAttributesCache(t);if(3e4<=Date.now()-e||o<n)try{yield this.getGroupAttributesFromServer({groupID:t,avChatRoomKey:r});let e=Ac.getGroupAttributesCacheValues(a);return console.log(this._name+`.${s} from server. groupID:`+t),Mc({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 i=Ac.getGroupAttributesCacheValues(a);return console.log(this._name+`.${s} from cache. groupID:`+t),Mc({groupAttributes:i})})}getGroupAttributesFromServer(r){return h(this,void 0,void 0,function*(){var e=this._core["utils"]["isUndefined"],{groupID:t,avChatRoomKey:s}=r,{AttrMainSeq:e=0,GroupAttrAry:s}=(yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return o.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)?La:Ra},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}}));Ac.refreshGroupAttributesCache({groupID:t,serverMainSequence:e,groupAttributeList:s,operation:Da})})}},nu=new class{init(e){console.log("GroupAttribute.init"),eu.init(e),tu.init(e),su.init(e),ou.init(e),Ac.init(e)}isGroupAttributesUpdated(e){return Ac.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:o,withChangedAttributeInfo:n}=r,i=Ac.getGroupAttributesCache(t)["localMainSequence"],a=o-i;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${n} diffSequence:`+a),0!=a)if(Ac.saveGroupAttributesCacheValuesCopy(t),1!==n||1!=a){if(Ac.hasGroupAttributesCache(t)){let e=Ac.getGroupAttributesCache(t)["avChatRoomKey"];ou.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{Ac.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else Ac.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){Ac.reset()}};function iu(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:o,MsgPriority:n,MsgRandom:i,MsgSeq:a,MsgTimeStamp:l,TinyId:u,ToGroupId:c,GroupInfo:d,MsgBody:h}=e,p=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:o,From_Account:n,To_Account:i}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:o,from:n,to:i}}();return{clientSequence:s,from:r,clientTime:o,priority:n,random:i,sequence:a,time:l,tinyID:u,to:c,groupProfile:p,elements:("tips"===t?ru:cu)(h)}}function ru(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=>au(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=au(r[s]);break;case"MsgGroupNewInfo":e.newGroupProfile=function(i){let e={};return Object.keys(i).forEach(n=>{switch(n){case"GroupIntroduction":e.introduction=i[n];break;case"GroupName":e.groupName=i[n];break;case"GroupFaceUrl":e.avatar=i[n];break;case"GroupNotification":e.notification=i[n];break;case"ApplyJoinOption":e.joinOption=i[n];break;case"InviteJoinOption":e.inviteOption=i[n];break;case"ShutupAll":e.muteAllMembers=i[n];break;case"Owner_Account":e.ownerID=i[n];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:o}=i[n];return{changedKeyList:e,groupAttributeList:o.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 au(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function cu(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 uu{constructor(e){this.type=Jr.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=ru(e);return new uu(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];xa[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 lu=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,uu)}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:r}=e,o=new Map,t=[],n=[];for(let t=0,e=r.length;t<e;t++){let e=iu(r[t],"tips");if(s===ba){if(nu.isGroupAttributesUpdated(e)){nu.handleGroupAttributesUpdated(e);continue}if(Zc.isGroupCounterUpdated(e)){Zc.handleGroupCounterUpdated(e);continue}}var i=e["groupProfile"]["groupID"];if(Ec.hasLocalGroup(i)){i=this._assembleMessage(e);if(s===ba&&(i._onlineOnlyFlag=!0,n.push(i)),s===Na){if(!this._core.message.messageDataHandler.storeConversationMessage(i))continue;n.push(i)}this._handleConversationOptions(o,i)}}return t.push(...o.values()),{conversationUpdateFieldList:t,messageList:n}}_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 uu(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:r,memberInfoList:o,operatorInfo:n}=e,i={};if(t(o)?t(n)||(i=n):r!==Ga&&r!==Pa&&r!==Ua&&r!==ka||(i=Object.assign({},o[0])),!t(i)){let{nick:e="",avatar:t=""}=i;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{conversationID:s,conversationType:r}=t;let o;if(e.has(s))o=e.get(s),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=r,o.lastMessage=t._isExcludedFromLastMessage?"":t;else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:s,unreadCount:e,type:r,lastMessage:t._isExcludedFromLastMessage?"":t}}e.set(s,o)}_handleGroupTipMessage(e){e.forEach(e=>{var t=e.payload["operationType"];switch(t){case Ga:this._handleNewMemberJoined(e);break;case wa:this._handleMemberQuitted(e);break;case Pa:this._handleMemberKicked(e);break;case Fa: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:o}=e.payload,n=r.groupID,i=Ec.getLocalGroup(n);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(n,s);break;case"groupName":i.name=s[e];break;default:i[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(o)||(null==(t=null==i?void 0:i.selfInfo)?void 0:t.userID)!==o.userID||Object.keys(o).forEach(e=>{"nameCard"===e&&i.updateSelfInfo({nameCard:o[e]}),"role"===e&&this._updateSelfRole(i,o[e])}),Ec.emitGroupListUpdate(),Ec.updateConversationGroupProfile(n)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=Ec.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;t===$a?r=s.GRP_MBR_ROLE_OWNER:t===qa&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=Ec.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,Ec.emitGroupListUpdate(),Ec.updateConversationGroupProfile(t))}};class du{constructor(e){this.type=Jr.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=cu(e);return new du(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];Va[r]&&(this.content.groupProfile[r]=t[r])}}}var pu=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,du)}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:o}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let o={};for(let e=0;e<t.length;e++){var n=iu(t[e],"system"),i=n["elements"]["operationType"];i!==Ya&&(i=this._assembleMessage(n),this._core.message.messageDataHandler.storeConversationMessage(i))&&(r.push(i),o=this._handleConversationOptions(i,s))}return o.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[o]:[],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 du(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 Ba:this._handleGroupJoinResult(e);break;case ja:this._handleMemberKicked(e);break;case Ka:this._handleGroupDismissed(e);break;case Wa:this._handleGroupInvitedResult(e);break;case Ha:this._handleGroupQuitResult(e);break;case za:this._handleMessageRemindTypeSynced(e);break;case Ja:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=Ec.hasLocalGroup(t);console.log(this._name+`._handleGroupJoinResult groupID:${t} type:${s} hasLocalGroup:`+r),r||hc(s)||(Ec.updateLocalGroup([Object.assign({},e)]),Ec.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];Ec.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];Ec.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],t=e["groupID"],s=Ec.hasLocalGroup(t);console.log(this._name+`._handleGroupInvitedResult groupID:${t} hasLocalGroup:`+s),s||(Ec.updateLocalGroup([Object.assign({},e)]),Ec.emitGroupListUpdate())}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=Ec.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(hc(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}Ec.deleteLocalGroup(s),Ec.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},hu=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),lu.init(e),pu.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){lu.onNewGroupTips(e)}_onNewGroupSystemNotification(e){pu.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 _u={required:!0,rules:["string"],allowEmpty:!1},gu={required:!0,rules:["number"],allowEmpty:!1},mu={required:!0,rules:["array"],allowEmpty:!1},vu={required:!0,rules:["object"],allowEmpty:!1},fu={createGroup:{name:_u,type:_u},dismissGroup:[Object.assign({key:"groupID"},_u)],joinGroup:{groupID:_u,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},_u)],searchGroupByID:[Object.assign({key:"groupID"},_u)],getGroupProfile:{groupID:_u,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:_u,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:_u,newOwnerID:_u},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},_u)],handleGroupApplication:{handleAction:_u},getGroupMemberList:{groupID:_u},getGroupMemberProfile:{groupID:_u,userIDList:mu,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:_u,userIDList:mu},deleteGroupMember:{groupID:_u,userIDList:mu},setGroupMemberMuteTime:{groupID:_u,userID:_u,muteTime:Object.assign(Object.assign({},gu),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:_u,userID:_u,role:_u},setGroupMemberNameCard:{groupID:_u,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:_u},setGroupMemberCustomField:{groupID:_u,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:mu},markGroupMemberList:{groupID:_u,markType:Object.assign(Object.assign({},gu),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:mu},initGroupAttributes:{groupID:_u,groupAttributes:vu},setGroupAttributes:{groupID:_u,groupAttributes:vu},deleteGroupAttributes:{groupID:_u,keyList:Object.assign(Object.assign({},mu),{allowEmpty:!0})},getGroupAttributes:{groupID:_u,keyList:Object.assign(Object.assign({},mu),{allowEmpty:!0})},getGroupCounters:{groupID:_u,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:_u,counters:vu},increaseGroupCounter:{groupID:_u,key:_u,value:gu},decreaseGroupCounter:{groupID:_u,key:_u,value:gu}},Iu={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var Su=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Ec,this.groupAction=Uc,this.groupAttribute=nu,this.groupMember=Jc}install(e,t=[]){this._core=e,Jr.init(e),Ec.init(e),Uc.init(e,this),Jc.init(e,this),$c.init(e),Zc.init(e),nu.init(e),hu.init(e),e.helper.registerValidateConfig({auth:Iu,params:fu}),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(){Ec.reset(),nu.reset(),Zc.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Eu=new class{init(e){this.core=e}},Cu="AV_MBR_LIST",Mu="AV_BAN_MBR",yu={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Tu={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},Au=60,Ou=2603,Du=2686,Ru=2688,Lu=3122;class Nu{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:o,onFail:n}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=o,this._onFail=n}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getPollingInterval())}isRunning(){return this._isRunning}_request(){return h(this,void 0,void 0,function*(){try{var e=yield function(o,n){return h(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.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 bu{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 Gu=e=>e===yu.GROUP_TIPS_HAS_NO_ROAMING||e===yu.GROUP_TIPS_HAS_ROAMING,wu=e=>e===yu.GROUP_SYSTEM_MESSAGE;function Pu(_){var e,t,s,r,o,n,i,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:o,GId:n,MS:i,CCD:a,F_Account:l,IsSys:u,GInf:c,MsgBody:d}=_,h=p(_,["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:o,ToGroupId:n,MsgSeq:i,CloudCustomData:a,From_Account:l,IsSystemMsg:u,GroupInfo:Uu(c),MsgBody:ku(d)},h)}(),l=a,u=l["Event"];if((Gu(u)||wu(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===yu.BROADCAST_MESSAGE||u===yu.NORMAL_MESSAGE){var c=l;let e=Eu["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 Gu(u)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:o,OpType:n}=(c=l).MsgBody||{},"number"==typeof e||1!==n&&2!==n||(c.MsgBody.GroupJoinType=2===n?0:1),s||(c.MsgBody.MsgMemberExtraInfo=o.map(e=>({UserId:e}))),1!==n||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),wu(u)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:o}=(i=l).MsgBody||{},i.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:o,ImageUrl:"",NickName:""},e),i.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*i.MsgTimeStamp},i.MsgBody),i.MsgBody=Object.keys(i.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:i.MsgBody[t]}),{})),a}function Uu(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:o}=e,e=p(e,["GN","GT","F_Hd","F_NN"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),o&&(t.From_AccountNick=o),t}function ku(e){let t=e;var s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:o,UDF:n,OpInf:i,OnlineInf:a,MsgMemberExtraInfo:l}=e,e=p(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:o,UserDefinedField:n},e);return i&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=i,s=p(i,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=l.map(e=>{var{Img:t,NN:s}=e,e=p(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},e)})),a&&(t.OnlineMemberInfo=function(){var{ET:e,Num:t}=a;return{ExpireTime:e,OnlineMemberNum:t}}()),t});return Array.isArray(e)?s:s[0]}var Fu=new class{constructor(){this._name="MessageParser",this._sequenceList=new bu(200),this._messageIDList=new bu(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(o,e,n=!1){this._sortServerMessageList({groupID:o,serverMessageList:e,isHistoryMessage:n});var i=this._handleMessageList(o,e);if(0!==i.length){if(!n){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=Eu["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}})(i[i.length-1]);e.updateConversation(""+t+o,{lastMessage:s})}this._checkMessageStacked(i);let e=i.filter(e=>!0===e.isModified),t=i.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 o,n,{messageDataHandler:i,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=Pu(e)),wu(e.Event)&&Object.values(Tu).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),o=a.parseServerGroupMessage(e),n=this._createMessage(o),Gu(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(o)?this._avChatRoomHandler.handleGroupAttributesUpdated(o):null===this._filterDuplicateMessage(n)||i.isMessageSentByCurrentInstance(n)||(1===o.isModified&&(n.isModified=!0),Gu(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(n)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];Gu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),wu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(yu).includes(t)?t===yu.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===yu.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===yu.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===yu.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:o,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:i,Reason:a=""}}=e,l=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+o.CONV_GROUP+n,ID:e+`-${t}-`+s,revoker:i,revokeReason:a,revokerInfo:{userID:i,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:o}=e,o=(null==o?void 0:o.MsgContent)||"";this._emitEvent({name:t,data:o}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+o)}_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,o=this._avChatRoomHandler.isPollingSimplifiedMessage(),n=[],i=s.length;for(let t=0;t<i;t++){let e=s[t];o&&(e=Pu(e));var a=r.parseServerGroupMessage(e);Object.values(yu).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(n.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<n.length&&this._emitEvent({name:e,data:n})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:o=Au}=r,n=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:n,memberCount:r,expireTime:o}:(e.latestUpdateTime=n,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let $u=e=>{var{store:t}=Eu["core"];return(t.get("cloudConfig")||{})[e]},qu=e=>{var{utils:{isUndefined:t}}=Eu["core"];return!t(e)},xu=()=>{var e=$u("polling_interval");return qu(e)?parseInt(e,10):300},Vu=()=>{var e=$u("polling_simplified_msg");return qu(e)?parseInt(e,10):0};var Bu=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,Fu.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:o,GroupType:n}}=s[e],r=Object.values(Tu).includes(r.ReportType);n===t&&r&&this.reset(o)}}getPollingInterval(){return this._pollingInterval}isPollingSimplifiedMessage(){return 0!==Vu()}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 h(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:o,group:n,historyMessageList:i}=l,a=n["groupID"];return yield this._preCheck(n),this._joinedGroupMap.set(a,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<i.length&&Fu.onMessageReceived(a,i,!0),e(o)?{status:r.JOIN_STATUS_SUCCESS,group:n}:this.startMessageLongPolling(l)})}_preCheck(o){return h(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=$u("polling_count_limit"),qu(e)&&0<e?parseInt(e,10):20))throw new s.ChatError({code:Ru,message:"the count of longPolling exceeds the max limit"})}else 0!==this._joinedAVChatRoomCount()&&o.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,o=r["groupID"];return this._pollingRequestInfoMap.set(o,{longPollingKey:e,startSequence:s}),this._pollingInterval=xu(),this._startPolling(o),{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 Nu({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:Vu()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Vu()}}_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:o=[],RspBroadcastMsgList:n=[]}=t;t&&s&&this._pollingRequestInfoMap.set(e,{longPollingKey:t,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<o.length?(0!==this._pollingNoMessageCount&&(this._pollingNoMessageCount=0,this._pollingInterval=xu()),Fu.onMessageReceived(e,o)):(this._pollingNoMessageCount+=1,this._pollingNoMessageCount===(t=$u("polling_no_msg_count"),qu(t)?parseInt(t,10):20)&&(this._pollingInterval=xu()+(s=$u("polling_interval_plus"),qu(s)?parseInt(s,10):2e3))),0<n.length&&Fu.onBroadcastMessageReceived(n)}_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,Fu.reset()}},ju=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 h(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?Bu.handleJoinGroupResult(t.data):t})}},Ku=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 h(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&&Bu.reset(r),t})}},Wu=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 h(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&&Bu.reset(r),t})}},Hu=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(o){return h(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=o["groupID"],e=e.getGroup(r);return(null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits(Cu)?this._getGroupMemberList(o):this._parentPlugin.groupMember.getGroupMemberList(o)})}_getGroupMemberList(n){return h(this,void 0,void 0,function*(){let o="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return h(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(n,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${o} ok, groupID:${n.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:o,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${o} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:o=0,Marks:n=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:o,marks:n,isOnline:!0}})}},Yu=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 h(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 h(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=Bu.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=Bu.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(n){return h(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return h(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0,ExpireTime:s=Au}=e||{},r=Date.now(),o={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return Bu.updateLocalOnlineMemberCount(n,o),{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}})}},zu=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(i){return h(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:o}=this._core,n=i["groupID"],t=t.getGroup(n);if(s(t))throw new r.ChatError({functionName:e,code:Ou});if(t.type!==o.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(i);if(r.checkBusinessCapabilityBits(Mu))return this._deleteGroupMember(i);throw new r.ChatError({functionName:e,code:Lu})})}_deleteGroupMember(i){return h(this,void 0,void 0,function*(){let s="_deleteGroupMember",{appStore:{groupStore:e},helper:r}=this._core,{groupID:t,duration:o=0,userIDList:n}=i;if(0===o)throw new r.ChatError({functionName:s,code:Du});try{return yield function(o,n){return h(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=o;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(i,this._core),console.log(this._name+`.${s} ok, groupID:`+t),{code:0,data:{group:e.getGroup(t),userIDList: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}})}},Ju=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return h(this,void 0,void 0,function*(){let o="markGroupMemberList",{groupID:n,markType:i,enableMark:a,userIDList:l=[]}=e,u=this._generateRequestData(e);try{let e=yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return o.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}.${o} ok, groupID:${n} markType:${i} 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:o,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${o} fail:`,t),t}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:o=[]}=e,n=!0===r?1:2,i=[...o];return 500<i.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:n,memberList:i.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}}},Qu=new class{init(e,t){console.log("AVChatRoomAction.init"),ju.init(e,t),Ku.init(e,t),Wu.init(e,t),Hu.init(e,t),Yu.init(e,t),zu.init(e,t),Ju.init(e)}},Xu=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:o,longPollingSequence:n=1}=e;if(s(o))return console.warn(this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});Bu.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=Bu.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:${o} longPollingSequence:`+n),Bu.startMessageLongPolling({group:t,longPollingKey:o,startSequence:n})}stopMessageLongPolling(e){e=e.groupID;return Bu.reset(e),console.log(this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}},Zu=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,Eu.init(e),Bu.init(e,t),Qu.init(e,t),Xu.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){Bu.onAVChatRoomSystemNotification(e)}_reset(){Bu.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 el="friend",tl=100,sl=2700,ol=2710,nl=2711,il=2716,rl=2742,al=30539,cl="Tag_SNS_IM_",ul={GROUP:cl+"Group",REMARK:cl+"Remark",ADDSOURCE:cl+"AddSource",ADDWORDING:cl+"Wording",ADDTIME:cl+"AddTime"},ll="Update_Type_Add",dl="Update_Type_Delete",pl="add",hl="remove",_l="rename",gl=e=>void 0===e;function ml(e,t){return h(this,void 0,void 0,function*(){return fl(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}),"ResultItem",e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function vl(e,t){return h(this,void 0,void 0,function*(){return fl(yield t.common.buildAndSendPacket({servcmd:"sns.friend_check",data:e}),"InfoItem",e=>({userID:e.To_Account,relation:e.Relation,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function fl(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){var{[t]:e=[],ActionStatus:t,ErrorCode:r,ErrorInfo:o,ErrorDisplay:n}=e;return{resultList:e.map(s),actionStatus:t,errorCode:r,errorInfo:o,errorDisplay:n}}let Il={[ul.REMARK]:(e,t)=>{e.remark=t},[ul.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[ul.ADDSOURCE]:(e,t)=>{e.source=t},[ul.ADDWORDING]:(e,t)=>{e.wording=t},[ul.ADDTIME]:(e,t)=>{e.addTime=t}},Sl=class{constructor(e){this.userID="",this.source="",this.wording="",this.remark="",this.addTime=0,this.groupList=[],this.friendCustomField=[];var{userID:e,tagValueList:t=[],core:s}=e,s=null==(s=s.user.userProfile)?void 0:s.createProfile(e,t);this.userID=e,this.profile=s,t.forEach(e=>{var{tag:e,value:t}=e,e=(-1<e.indexOf("Tag_Profile_Custom")&&this.friendCustomField.push({key:e,value:t}),Il[e]);null!=e&&e(this,t)})}update(e){let r=[];this.friendCustomField.forEach(e=>{r.push(e.key)}),e.forEach(e=>{let{tag:t,value:s}=e;-1<t.indexOf("Tag_Profile_Custom")&&(-1<r.indexOf(t)?this.friendCustomField.forEach(e=>{e.key===t&&(e.value=s)}):this.friendCustomField.push({key:t,value:s}));e=Il[t];null!=e&&e(this,s)})}};var El=new class{constructor(){this._startIndex=0,this._standardSequence=0,this._customSequence=0}init(e){var{helper:e,constants:t}=this._core=e;e.registerApi({apiName:"getFriendList",context:this,methodName:"getFriendListFromCache"}),e.registerApi({apiName:"getFriendProfile",context:this}),e.registerApi({apiName:"addFriend",context:this}),e.registerApi({apiName:"deleteFriend",context:this}),e.registerApi({apiName:"updateFriend",context:this}),e.registerApi({apiName:"checkFriend",context:this}),e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.FRIEND_RECOVER,this.syncFriendListFromServer,this)}getFriendListFromCache(){return h(this,void 0,void 0,function*(){var e=this._core.appStore["userStore"],e=[...e.getFriendMap().values()];return console.log(el+" getFriendListFromCache, data ",e),{code:0,data:e}})}syncFriendListFromServer(){return h(this,void 0,void 0,function*(){var e;try{console.log(el+" syncFriendListFromServer");var{friendList:t,nextStartIndex:s,standardSequence:r,customSequence:o,completeFlag:n}=yield function(c,d){return h(this,void 0,void 0,function*(){var{UserDataItem:e=[],StandardSequence:t,CustomSequence:s,FriendNum:r,CompleteFlag:o,NextStartIndex:n,ActionStatus:i,ErrorCode:a,ErrorInfo:l,ErrorDisplay:u}=e=yield d.common.buildAndSendPacket({servcmd:"sns.friend_get",data:c});return{friendList:e.map(e=>{return{userID:e.To_Account,tagValueList:null==(e=e.ValueItem)?void 0:e.map(e=>({tag:e.Tag,value:e.Value}))}}),standardSequence:t,customSequence:s,friendNumber:r,completeFlag:o,nextStartIndex:n,actionStatus:i,errorCode:a,errorInfo:l,errorDisplay:u}})}({From_Account:null==(e=this._core.store.get("login"))?void 0:e.userId,StartIndex:this._startIndex,StandardSequence:this._standardSequence,CustomSequence:this._customSequence},this._core);this._startIndex=s,this._standardSequence=r,this._customSequence=o,this._processFriendList(t),0===n?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),console.log(el+" syncFriendListFromServer ok")}catch(e){throw console.error(el+" syncFriendListFromServer error:",e),e}})}getFriendProfile(l){return h(this,void 0,void 0,function*(){var t;try{console.log(el+" getFriendProfile params:",l);let e=l["userIDList"];e.length>tl&&(e=e.slice(0,tl));var s,r,o,{friendUserIdList:n,unFriendUserIdList:i}=this.partitionByIsFriend(e),a=this._createNonFriendErrorList(i);return 0===n.length?{code:0,data:{friendList:[],failureUserIDList:a}}:(s=(yield function(n,i){return h(this,void 0,void 0,function*(){var{InfoItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:o}=e=yield i.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:n});return{friendProfileList:e.map(e=>{return{userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,relation:e.Relation,standardSequence:e.StandardSequence,customSequence:e.CustomSequence,profileItem:(null==(e=e.SnsProfileItem)?void 0:e.map(e=>({tag:e.Tag,value:e.Value})))||[]}}),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:o}})}({From_Account:null==(t=this._core.store.get("login"))?void 0:t.userId,To_Account:n},this._core))||{},{successProfiles:r,failedProfiles:o}=this._processFriendProfileResponse(s),{code:0,data:{friendList:r,failureUserIDList:[...o,...a]}})}catch(e){throw console.error(el+" getFriendProfile error:",e),e}})}addFriend(_){return h(this,void 0,void 0,function*(){var e;try{console.log(el+" addFriend options:",_);var{helper:t,store:s}=this._core,{to:r,source:o,type:n,wording:i,remark:a,groupName:l}=_,u=yield function(e,t){return h(this,void 0,void 0,function*(){return fl(yield t.common.buildAndSendPacket({servcmd:"sns.friend_add",data:e}))})}({From_Account:null==(e=s.get("login"))?void 0:e.userId,AddFriendItem:[{To_Account:r,AddSource:o,AddWording:i,GroupName:l,Remark:a}],AddType:n},this._core),{resultList:c=[]}=u,{userID:d,resultCode:p}=c[0];if(0===p)return console.log(el+" addFriend ok"),{code:0,data:{userID:d}};if(p===al)return console.log(el+" addFriend wait for the other party to agree"),{code:0,data:{userID:d,code:p,message:"wait for the other party to agree"}};throw new t.ChatError({functionName:"addFriend",code:p})}catch(e){throw console.error(el+" addFriend error:",e),e}})}deleteFriend(c){return h(this,void 0,void 0,function*(){var s;try{console.log(el+" deleteFriend options:",c);var r=this._core["store"];let{userIDList:e,type:t}=c;var o,n,i,a=null==(s=r.get("login"))?void 0:s.userId,{friendUserIdList:l,unFriendUserIdList:u}=(1e3<e.length&&(console.warn(el+" deleteFriend the length of userIDList cannot exceed:",1e3),e=e.slice(0,tl)),this.partitionByIsFriend(e));return 0===l.length?{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(u)}}:(o=yield function(e,t){return h(this,void 0,void 0,function*(){return fl(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))})}({From_Account:a,To_Account:l,DeleteType:t},this._core),{successUserIDList:n,failureUserIDList:i}=this._processOperationResult({resultList:o.resultList,includeRelation:!1}),console.log(el+" deleteFriend ok"),{code:0,data:{successUserIDList:n,failureUserIDList:i}})}catch(e){throw console.error(el+" deleteFriend error:",e),e}})}updateFriend(p){return h(this,void 0,void 0,function*(){var e;try{console.log(el+" updateFriend options:",p);var{userID:t,remark:s,friendCustomField:r}=p,{helper:o,store:n,appStore:{userStore:i}}=this._core,a=null==(e=n.get("login"))?void 0:e.userId;if(!i.getFriendMap().has(t))throw new o.ChatError({functionName:"updateFriend",code:sl});var l=(yield ml({From_Account:a,UpdateItem:[{To_Account:t,SnsItem:this._buildSnsItemList(s,r)}]},this._core))["resultList"],{to:u,resultCode:c,resultInfo:d}=l[0];if(gl(c)||0===c)return{code:0,data:this._updateLocalFriend({userID:u,remark:s,friendCustomField:r})};throw new o.ChatError({functionName:"updateFriend",code:c,message:d})}catch(e){throw console.error(el+" updateFriend error:",e),e}})}checkFriend(l){return h(this,void 0,void 0,function*(){var e;try{console.log(el+" checkFriend options:",l);var{userIDList:t,type:s}=l,{OuterConstant:r,store:o}=this._core,n=yield vl({From_Account:null==(e=o.get("login"))?void 0:e.userId,To_Account:t,CheckType:s===r.SNS_CHECK_TYPE_SINGLE?s:r.SNS_CHECK_TYPE_BOTH},this._core),{successUserIDList:i=[],failureUserIDList:a=[]}=this._processOperationResult({resultList:n.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:i,failureUserIDList:a}}}catch(e){throw console.error(el+" checkFriend error:",e),e}})}dispose(){this.reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this)}reset(){var e=this._core.appStore["userStore"];e.getFriendMap().clear(),this._startIndex=0,this._standardSequence=0,this._customSequence=0}updateFriendList(r){return h(this,void 0,void 0,function*(){console.log(el+" updateFriendList data:",r);let s=this._core.appStore["userStore"],{addedFriendList:e=[],removedFriendList:t=[]}=r;0<e.length&&(e.forEach(e=>{var t=new Sl({userID:e,core:this._core});s.getFriendMap().set(e,t)}),yield this.getFriendProfile({userIDList:e}),this._emitFriendListUpdated()),0<t.length&&(t.forEach(e=>{s.getFriendMap().delete(e)}),this._emitFriendListUpdated())})}updateFriendInfo(e){console.log(el+" updateFriendInfo data: ",e);let{appStore:{userStore:t,conversationStore:o},utils:{isEmpty:s}}=this._core,{userID:n,tagValueList:i}=e[0]||{},a=t.getFriend(n);if(!s(i)&&a){let r=i.map(e=>({tag:e.BytesTag,value:e.BytesValue}));r.forEach(e=>{var{tag:e,value:t}=e,s=null==(s=o.getConversation("C2C"+n))?void 0:s.remark;e===ul.REMARK&&t!==s&&o.updateConversation("C2C"+n,{remark:t}),a.update(r)}),this._emitFriendListUpdated()}}_processFriendList(e){let{utils:{isEmpty:t},appStore:{userStore:s}}=this._core;t(e)||e.forEach(e=>{var{userID:e,tagValueList:t}=e;this._isInvalidFriend(e)||(t=new Sl({userID:e,tagValueList:t,core:this._core}),s.getFriendMap().set(e,t))})}_isInvalidFriend(e){return"@TLS#NOT_FOUND"===e||""===e}_fetchFriendProfile(){return h(this,void 0,void 0,function*(){try{console.log(el+" _fetchFriendProfile");let{appStore:{userStore:s},user:{userProfile:t}}=this._core,r=[...s.getFriendMap().keys()],o=Math.ceil(r.length/100);for(let e=0;e<o;e++){var n=100*e,i=Math.min(100+n,r.length),a=r.slice(n,i),l=yield null==t?void 0:t.getUserProfile({userIDList:a});l&&l.data&&l.data.forEach(e=>{var t=s.getFriend(e.userID);t&&(t.profile=e)}),this._emitFriendListUpdated()}}catch(e){throw console.error(el+" _fetchFriendProfile error:",e),e}})}_emitFriendListUpdated(){var{notificationCenter:e,OuterEvent:t,appStore:{userStore:s}}=this._core,s=Array.from(s.getFriendMap().values());console.log(el+" _emitFriendListUpdated friendList:",s),e.emitOuterEvent(t.FRIEND_LIST_UPDATED,{name:t.FRIEND_LIST_UPDATED,data:s})}_updateCustomField(r,e){if(!Array.isArray(r)||!Array.isArray(e))return!1;let o=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,o=!0):(r.push({key:t,value:e}),o=!0)}),o}_updateLocalFriend(e){var t=this._core.appStore["userStore"],{userID:e,remark:s,friendCustomField:r}=e,t=t.getFriend(e);if(t)return gl(s)||(t.remark=s),Array.isArray(r)&&0<r.length&&this._updateCustomField(t.friendCustomField,r),this._emitFriendListUpdated(),t}_processOperationResult(e){let{resultList:t,includeRelation:o=!1}=e,s=this._core.utils["isEmpty"],n=[],i=[];return Array.isArray(t)&&!s(t)&&t.forEach(e=>{var{userID:t,relation:s,resultCode:e,resultInfo:r}=e;if(gl(e)||0===e){let e={userID:t};o&&(e.code=0,e.relation=s),n.push(e)}else i.push({userID:t,code:e,message:r})}),{successUserIDList:n,failureUserIDList:i}}_createNonFriendErrorList(e){return e.map(e=>({userID:e,code:sl,message:"The specified userID is not my friend"}))}_buildSnsItemList(e,t){let s=[];return gl(e)||s.push({Tag:ul.REMARK,Value:e}),Array.isArray(t)&&0<t.length&&t.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}_processFriendProfileResponse(e){let{friendProfileList:t=[]}=e,o=this._core.appStore["userStore"],n=[],i=[];return t.forEach(e=>{var{userID:t,resultCode:e,resultInfo:s,profileItem:r}=e;if(0===e){let e=new Sl({userID:t,tagValueList:r,core:this._core});n.push(e),o.getFriendMap().set(t,e)}else i.push({userID:t,code:e,message:s})}),console.log(el+" _processFriendProfileResponse successProfiles:",n),{successProfiles:n,failedProfiles:i}}partitionByIsFriend(e){let s=[],r=[];return e.forEach(e=>{var t=this._core.appStore["userStore"];(t.getFriendMap().has(e)?s:r).push(e)}),console.log(`${el} partitionByIsFriend, friendUserIdList: ${s}, unFriendUserIdList: `+r),{friendUserIdList:s,unFriendUserIdList:r}}isMyFriend(e){var t=this._core.appStore["userStore"];return t.getFriendMap().has(e)}},Cl=new class{init(e){this.core=e}};function Ml(s){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Cl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,ResponseFriendItem:[{To_Account:s.userID,ResponseAction:s.type,Remark:s.remark}]};return Al(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function yl(s){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Cl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,ResponseFriendItem:[{To_Account:s.userID,ResponseAction:"Response_Action_Reject"}]};return Al(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function Tl(s){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Cl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,To_Account:[s.userID],PendencyType:s.type};return Al(yield t.buildAndSendPacket({servcmd:"sns.pendency_delete",data:e}))})}function Al(e){var{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:o}=e;return{resultList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:o}}var Ol=new class{constructor(){this._friendApplicationMap=new Map,this._unreadCount=0,this._startTime=0,this._currentSequence=0}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getFriendApplicationList",context:this,methodName:"getFriendApplicationListFromCache"}),e.registerApi({apiName:"acceptFriendApplication",context:this}),e.registerApi({apiName:"refuseFriendApplication",context:this}),e.registerApi({apiName:"deleteFriendApplication",context:this}),e.registerApi({apiName:"setFriendApplicationRead",context:this})}getFriendApplicationListFromCache(){return h(this,void 0,void 0,function*(){var e=[...this._friendApplicationMap.values()];return console.log(el+" getFriendApplicationListFromCache friendApplicationList:",e),{code:0,data:{friendApplicationList:e,unreadCount:this._unreadCount}}})}syncFriendApplicationListFromServer(){return h(this,void 0,void 0,function*(){let t="syncFriendApplicationListFromServer";console.log(el+" "+t);try{let e=yield function(l){return h(this,void 0,void 0,function*(){var{store:e,OuterConstant:t,common:s}=Cl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,PendencyType:t.SNS_APPLICATION_TYPE_BOTH,MaxLimited:tl,StartTime:l.startTime,LastSequence:l.currentSequence},{PendencyItem:t=[],StartTime:s,UnreadPendencyCount:e,CurrentSequence:r,ActionStatus:o,ErrorCode:n,ErrorInfo:i,ErrorDisplay:a}=t=yield s.buildAndSendPacket({servcmd:"sns.pendency_get",data:e});return{resultList:t.map(e=>({userID:e.To_Account,time:e.AddTime,source:e.AddSource,wording:e.AddWording,nick:e.Nick,type:e.PendencyType,image:e.Image})),startTime:s,unreadCount:e,currentSequence:r,actionStatus:o,errorCode:n,errorInfo:i,errorDisplay:a}})}({startTime:this._startTime,currentSequence:this._currentSequence}),{resultList:t,unreadCount:s,startTime:r,currentSequence:o}=e;this._startTime=r,this._currentSequence=o,this._unreadCount=s,this._friendApplicationMap.clear(),Array.isArray(t)&&t.forEach(e=>{var{userID:t,type:s}=e,e=this._createFriendApplication(e);this._friendApplicationMap.set(t+"_"+s,e)}),this._emitApplicationListUpdated()}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(`${el} ${t} error:`,s),s}})}acceptFriendApplication(e){return h(this,void 0,void 0,function*(){return this._operationApplication({functionName:"acceptFriendApplication",options:e,protocolFunction:Ml})})}refuseFriendApplication(e){return h(this,void 0,void 0,function*(){return this._operationApplication({functionName:"refuseFriendApplication",options:e,protocolFunction:yl})})}deleteFriendApplication(s){return h(this,void 0,void 0,function*(){var{userID:e,type:t}=s;return this._checkApplicationExists(e,t,"deleteFriendApplication"),this._operationApplication({functionName:"deleteFriendApplication",options:s,protocolFunction:Tl})})}_checkApplicationExists(e,t,s){if(!this._friendApplicationMap.has(e+"_"+t))throw new this._core.helper.ChatError({functionName:s,code:il})}_operationApplication(e){return h(this,void 0,void 0,function*(){let{functionName:o,options:n,protocolFunction:i}=e;console.log(el+` ${o} options:`,n);try{let e=yield i(n),{resultList:t=[]}=e,{resultCode:s,resultInfo:r}=t[0];if(0===s)return console.log(el+` ${o} ok`),{code:0,data:{}};throw{errorCode:s,errorInfo:r}}catch(e){let t=new this._core.helper.ChatError({functionName:o,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(el+` ${o} error:`,t),t}})}setFriendApplicationRead(){return h(this,void 0,void 0,function*(){var t="setFriendApplicationRead";console.log(el+" "+t);try{return yield function(){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Cl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,LatestPendencyTimeStamp:(e=Math.floor(Date.now()/1e3),Math.round(Number(e)*Math.pow(10,0))/Math.pow(10,0))},{ActionStatus:t,ErrorCode:e,ErrorInfo:s,ErrorDisplay:r}=t=yield t.buildAndSendPacket({servcmd:"sns.pendency_report",data:e});return{actionStatus:t,errorCode:e,errorInfo:s,errorDisplay:r}})}(),this._unreadCount=0,this._emitApplicationListUpdated(),console.log(el+` ${t} ok`),{code:0,data:{}}}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(el+` ${t} error:`,s),s}})}updateFriendApplicationList(e){var{from:t,addedApplicationList:s=[],removedApplicationList:r=[]}=e,e=(console.log(el+" updateFriendApplicationList data:",e),this._core.utils)["isEmpty"];e(s)||this.onApplicationAdded(s,t),e(r)||this.onApplicationDeleted()}onApplicationAdded(e,t){let s,{store:r,OuterConstant:o}=this._core,n=t===(null==(s=r.get("login"))?void 0:s.userId)?o.SNS_APPLICATION_SENT_BY_ME:o.SNS_APPLICATION_SENT_TO_ME;e.forEach(e=>{var t=e.userID+"_"+n;n!==o.SNS_APPLICATION_SENT_TO_ME||this._friendApplicationMap.has(t)||(this._unreadCount+=1),this._friendApplicationMap.set(t,this._createFriendApplication(Object.assign(Object.assign({},e),{type:n})))}),this._emitApplicationListUpdated()}onApplicationDeleted(){this._startTime=0,this._currentSequence=0,this.syncFriendApplicationListFromServer()}onApplicationRead(){this._unreadCount=0,this._emitApplicationListUpdated()}reset(){this._startTime=0,this._currentSequence=0,this._unreadCount=0,this._friendApplicationMap.clear()}dispose(){this.reset()}_createFriendApplication(e){return{userID:e.userID||"",nick:e.nick||"",avatar:e.avatar||"",time:e.time||0,source:e.source||"",wording:e.wording||"",type:e.type||""}}_emitApplicationListUpdated(){console.log(el+" _emitApplicationListUpdated");var{notificationCenter:e,OuterEvent:t}=this._core;e.emitOuterEvent(t.FRIEND_APPLICATION_LIST_UPDATED,{name:t.FRIEND_APPLICATION_LIST_UPDATED,data:{friendApplicationList:[...this._friendApplicationMap.values()],unreadCount:this._unreadCount}})}};function Dl(){return h(this,void 0,void 0,function*(){var e=Cl.core["common"],t={From_Account:e.getCurrentUserID(),LastSequence:0,NeedFriend:"Need_Friend_Type_Yes"};return Pl(yield e.buildAndSendPacket({servcmd:"sns.group_get",data:t}),e=>({name:e.GroupName,userIDList:e.To_Account||[],count:e.FriendNumber}))})}function Rl(r){return h(this,void 0,void 0,function*(){var{name:e,userIDList:t}=r,s=Cl.core["common"],e={From_Account:s.getCurrentUserID(),GroupName:[e],To_Account:t};return Pl(yield s.buildAndSendPacket({servcmd:"sns.group_add",data:e}),e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function Ll(s){return h(this,void 0,void 0,function*(){var e=Cl.core["common"],t={From_Account:e.getCurrentUserID(),GroupName:[s.name]};return Pl(yield e.buildAndSendPacket({servcmd:"sns.group_delete",data:t}))})}function Nl(r){return h(this,void 0,void 0,function*(){var e=Cl.core["common"],{name:t,userIDList:s}=r,s=wl(s,ll),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Pl(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function bl(r){return h(this,void 0,void 0,function*(){var e=Cl.core["common"],{name:t,userIDList:s}=r,s=wl(s,dl),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Pl(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function Gl(r){return h(this,void 0,void 0,function*(){var e=Cl.core["common"],{oldName:t,newName:s}=r,t={From_Account:e.getCurrentUserID(),GroupOldName:t,GroupNewName:s};return Pl(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}))})}function wl(e,t){return e.filter(e=>El.isMyFriend(e)).map(e=>({To_Account:e,UpdateType:t}))}function Pl(e,t){var{CurrentSequence:e,ActionStatus:s,ErrorCode:r,ErrorInfo:o,ErrorDisplay:n,ResultItem:i=[]}=e,e={currentSequence:e,actionStatus:s,errorCode:r,errorInfo:o,errorDisplay:n};return t&&0<i.length?Object.assign(Object.assign({},e),{resultList:i.map(t)}):e}class Ul{constructor(e){var{name:e="",userIDList:t=[]}=e;this.name=e,this.userIDList=t,this.count=t.length}addToUserIDList(e){-1===this.userIDList.indexOf(e)&&(this.userIDList.push(e),this.count=this.userIDList.length)}removeFromUserIDList(e){e=this.userIDList.indexOf(e);-1<e&&(this.userIDList.splice(e,1),this.count=this.userIDList.length)}}var kl=new class{constructor(){this._friendGroupMap=new Map}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getFriendGroupList",context:this,methodName:"getFriendGroupListFromCache"}),e.registerApi({apiName:"createFriendGroup",context:this}),e.registerApi({apiName:"deleteFriendGroup",context:this}),e.registerApi({apiName:"addToFriendGroup",context:this}),e.registerApi({apiName:"removeFromFriendGroup",context:this}),e.registerApi({apiName:"renameFriendGroup",context:this})}getFriendGroupListFromCache(){return h(this,void 0,void 0,function*(){var e=[...this._friendGroupMap.values()];return console.log(el+" getFriendGroupListFromCache, data: ",e),{code:0,data:e}})}syncFriendGroupListFromServer(){return h(this,void 0,void 0,function*(){var t="syncFriendGroupListFromServer";console.log(el+" "+t);try{var e=yield Dl(),{resultList:s=[]}=e;this._core.helper.isEmpty(s)&&console.log(el+` ${t} ok. count: 0`),s.forEach(e=>{var t=new Ul(e);this._friendGroupMap.set(e.name,t)}),this._emitGroupListUpdated()}catch(e){this._handleError(t,e)}})}createFriendGroup(i){return h(this,void 0,void 0,function*(){var t="createFriendGroup";console.log(el+` ${t} params:`,i);try{var e=i["name"],s=(this._checkGroupExist(t,e),yield Rl(i)),{successUserIDList:r,failureUserIDList:o}=this._parseCreateGroupResponse(s),n=new Ul({name:e,userIDList:r});return this._friendGroupMap.set(e,n),this._emitGroupListUpdated(),{code:0,data:{friendGroup:n,failureUserIDList:o}}}catch(e){this._handleError(t,e)}})}deleteFriendGroup(r){return h(this,void 0,void 0,function*(){var t="deleteFriendGroup";console.log(el+` ${t} params:`,r);try{var e=r["name"],s=(this._checkGroupNotExist(t,e),yield Ll(r),this._friendGroupMap.get(e));return s&&(this._updateFriendGroup({name:e,userIDList:s.userIDList,action:hl}),this._friendGroupMap.delete(e)),this._emitGroupListUpdated(),{code:0,data:s}}catch(e){this._handleError(t,e)}})}addToFriendGroup(e){return h(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"addToFriendGroup",params:e,protocolFunction:Nl})})}removeFromFriendGroup(e){return h(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"removeFromFriendGroup",params:e,protocolFunction:bl})})}renameFriendGroup(o){return h(this,void 0,void 0,function*(){var t="renameFriendGroup";console.log(el+` ${t} params:`,o);try{var{oldName:e,newName:s}=o,r=(this._checkGroupNotExist(t,e),this._checkGroupExist(t,s),yield Gl(o),this._updateGroupNameInCache(e,s));return r&&this._updateFriendGroup({name:e,userIDList:r.userIDList,action:_l,newName:s}),this._emitGroupListUpdated(),{code:0,data:r}}catch(e){this._handleError(t,e)}})}_updateFriendGroupMember(e){return h(this,void 0,void 0,function*(){var{functionName:t,params:s,protocolFunction:r}=e;console.log(el+` ${t} params:`,s);try{let e=s["name"];this._checkGroupNotExist(t,e);var o=yield r(s),{friendGroup:n,failureUserIDList:i}=this._parseUpdateFriendGroupResponse(e,o);return this._emitGroupListUpdated(),{code:0,data:{friendGroup:n,failureUserIDList:i}}}catch(e){this._handleError(t,e)}})}_updateGroupNameInCache(e,t){var s=this._friendGroupMap.get(e);return s&&(s.name=t,this._friendGroupMap.delete(e),this._friendGroupMap.set(t,s)),s}_parseCreateGroupResponse(e){let{resultList:t=[]}=e,r=[],o=[];return t.forEach(({userID:e,resultCode:t,resultInfo:s})=>{gl(t)||0===t?r.push(e):o.push({userID:e,code:t,message:s})}),{successUserIDList:r,failureUserIDList:o}}_parseUpdateFriendGroupResponse(t,e){let{resultList:s=[]}=e,r=this._friendGroupMap.get(t),o=[],n=[],i=[];return s.forEach(e=>{0===e.resultCode?r&&(e.updateType===ll?this._addFriendToGroup(t,e.userID,r,n):e.updateType===dl&&this._removeFriendFromGroup(t,e.userID,r,i)):o.push({userID:e.userID,code:e.resultCode,message:e.resultInfo})}),{friendGroup:r,failureUserIDList:o}}_addFriendToGroup(e,t,s,r){s.addToUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:pl})}_removeFriendFromGroup(e,t,s,r){s.removeFromUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:hl})}_emitGroupListUpdated(){var{notificationCenter:e,OuterEvent:t}=this._core,s=[...this._friendGroupMap.values()];console.log(el+" _emitGroupListUpdated friendGroupList:",s),e.emitOuterEvent(t.FRIEND_GROUP_LIST_UPDATED,{name:t.FRIEND_GROUP_LIST_UPDATED,data:s})}_checkGroupNotExist(e,t){if(!this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:nl})}_checkGroupExist(e,t){if(this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:ol})}_updateFriendGroup(e){let{name:r,userIDList:t,action:o,newName:n}=e,i=this._core.appStore["userStore"];console.log(el+" updateFriendGroup",{name:r,userIDList:t,action:o,newName:n}),r&&!this._core.utils.isEmpty(t)&&t.forEach(e=>{var t=i.getFriend(e);if(t){var s=t["groupList"];switch(o){case pl:-1===s.indexOf(r)&&(s.push(r),t.count=s.length);break;case hl:{let e=s.indexOf(r);-1<e&&(s.splice(e,1),t.count=s.length);break}case _l:if(n){let e=s.indexOf(r);-1!==e&&(s[e]=n)}}}})}_handleError(e,t){t=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(el+` ${e} error:`,t),t}reset(){this._friendGroupMap.clear()}dispose(){this.reset()}};function Fl(e){return e&&0!==e.length?e.map(e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp})):[]}var $l=new class{constructor(){this._blacklistMap=new Map,this._retryCount=0,this._startIndex=0}init(e){var{helper:e,constants:t}=this._core=e;e.registerApi({apiName:"getBlacklist",context:this,methodName:"getBlacklistFromCache"}),e.registerApi({apiName:"addToBlacklist",context:this}),e.registerApi({apiName:"removeFromBlacklist",context:this}),e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.BLACKLIST_RECOVER,this.syncBlacklistFromServer,this)}getBlacklistFromCache(){return h(this,void 0,void 0,function*(){return console.log(el+" getBlacklistFromCache"),{code:0,data:Array.from(this._blacklistMap.keys())}})}syncBlacklistFromServer(){return h(this,void 0,void 0,function*(){try{console.log(el+" syncBlacklistFromServer");var e=yield function(r,o){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,s="sns.black_list_get",e=e.generateProtocolData({servcmd:s,data:r}),s=e.head.seq+s,{BlackListItem:t=[],StartIndex:e=0}=yield t.sendPacket(e,{requestId:s});return{blackList:Fl(t),startIndex:e}})}({From_Account:this._core.common.getCurrentUserID(),MaxLimited:tl,StartIndex:this._startIndex},this._core),{blackList:t=[],startIndex:s=0}=e;return this._startIndex=s,this._addBlacklistMap(t),this._emitBlackListUpdated(),0!==this._startIndex&&this._retryCount<10?(this._retryCount++,yield this.syncBlacklistFromServer()):this._retryCount=0,{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw this._retryCount=0,console.error(el+" syncBlacklistFromServer error:",e),e}})}addToBlacklist(r){return h(this,void 0,void 0,function*(){try{console.log(el+" addToBlacklist options:",r);var e=this._preprocessBlacklist(r),t=yield function(r,o){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,s="sns.black_list_add",e=e.generateProtocolData({servcmd:s,data:r}),s=e.head.seq+s,{ResultItem:t=[]}=yield t.sendPacket(e,{requestId:s});return{blackList:Fl(t)}})}({From_Account:this._core.common.getCurrentUserID(),To_Account:e},this._core),{blackList:s=[]}=t;return this._addBlacklistMap(s),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(el+" addToBlacklist error:",e),e}})}removeFromBlacklist(s){return h(this,void 0,void 0,function*(){try{console.log(el+" removeFromBlacklist options:",s);var e=yield function(r,o){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,s="sns.black_list_delete",e=e.generateProtocolData({servcmd:s,data:r}),s=e.head.seq+s,{ResultItem:t=[]}=yield t.sendPacket(e,{requestId:s});return{blackList:Fl(t)}})}({From_Account:this._core.common.getCurrentUserID(),To_Account:s.userIDList},this._core),{blackList:t=[]}=e;return this._deleteBlacklistMap(t),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(el+" removeFromBlacklist error:",e),e}})}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){console.log(el+" updateBlacklist data:",e);var{addedBlacklist:e=[],removedBlacklist:t=[]}=e;let s=!1;0<e.length&&e.some(e=>!this._blacklistMap.has(e))&&(s=!0,this._addBlacklistMap(e.map(e=>({userID:e})))),0<t.length&&t.some(e=>this._blacklistMap.has(e))&&(s=!0,this._deleteBlacklistMap(t.map(e=>({userID:e})))),s&&this._emitBlackListUpdated()}_addBlacklistMap(e){console.log(el+" _addBlacklistMap blackList:",e),e.forEach(e=>{var{userID:e,addBlackTimeStamp:t=Date.now()}=e;e&&!this._blacklistMap.has(e)&&this._blacklistMap.set(e,{userID:e,addBlackTimeStamp:t})})}_deleteBlacklistMap(e){console.log(el+" _deleteBlacklistMap blackList:",e),e.forEach(e=>{e=e.userID;e&&this._blacklistMap.has(e)&&this._blacklistMap.delete(e)})}_preprocessBlacklist(e){let t=e["userIDList"],s=this._core.common.getCurrentUserID();if(1===t.length&&t[0]===s)throw new this._core.helper.ChatError({functionName:"addToBlacklist",code:rl});return t=t.includes(s)?e.userIDList.filter(e=>e!==s):t}_emitBlackListUpdated(){var{notificationCenter:e,OuterEvent:t}=this._core,s=Array.from(this._blacklistMap.keys());console.log(el+" _emitBlackListUpdated blackList:",s),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:s})}};let ql={addToBlacklist:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},removeFromBlacklist:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},getFriendProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},addFriend:{to:{required:!0,rules:["string"],allowEmpty:!1},source:{required:!0,rules:["string"],allowEmpty:!1},wording:{required:!1,rules:["string"],allowEmpty:!0},type:{required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Cl.core["OuterConstant"];return e===t.SNS_ADD_TYPE_SINGLE||e===t.SNS_ADD_TYPE_BOTH||"type should be SNS_ADD_TYPE_SINGLE or SNS_ADD_TYPE_BOTH"}},remark:{required:!1,rules:["string"],allowEmpty:!0},groupName:{required:!1,rules:["string"],allowEmpty:!0}},deleteFriend:{userIDList:{required:!0,rules:["array"],allowEmpty:!1},type:{required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=Cl.core["OuterConstant"];return e===t.SNS_DELETE_TYPE_SINGLE||e===t.SNS_DELETE_TYPE_BOTH||"type should be SNS_DELETE_TYPE_SINGLE or SNS_DELETE_TYPE_BOTH"}}},checkFriend:{userIDList:{required:!0,rules:["array"],allowEmpty:!1},type:{required:!1,rules:["string"],allowEmpty:!0}},updateFriend:{userID:{required:!0,rules:["string"],allowEmpty:!1},remark:{required:!1,rules:["string"],allowEmpty:!0},friendCustomField:{required:!1,rules:["array"],allowEmpty:!0}},acceptFriendApplication:{userID:{required:!0,rules:["string"],allowEmpty:!1},remark:{required:!1,rules:["string"],allowEmpty:!0},type:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>{var t=Cl.core["OuterConstant"];return e===t.SNS_APPLICATION_AGREE||e===t.SNS_APPLICATION_AGREE_AND_ADD||"type should be SNS_APPLICATION_AGREE or SNS_APPLICATION_AGREE_AND_ADD"}}},refuseFriendApplication:{userID:{required:!0,rules:["string"],allowEmpty:!1}},deleteFriendApplication:{userID:{required:!0,rules:["string"],allowEmpty:!1},type:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>{var t=Cl.core["OuterConstant"];return e===t.SNS_APPLICATION_SENT_TO_ME||e===t.SNS_APPLICATION_SENT_BY_ME||"type should be SNS_APPLICATION_SENT_TO_ME or SNS_APPLICATION_SENT_BY_ME"}}},createFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1},userIDList:{required:!0,rules:["array"],allowEmpty:!1}},deleteFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1}},addToFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1},userIDList:{required:!0,rules:["array"],allowEmpty:!1}},removeFromFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1},userIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameFriendGroup:{oldName:{required:!0,rules:["string"],allowEmpty:!1},newName:{required:!0,rules:["string"],allowEmpty:!1}}},xl={getBlacklist:!0,addToBlacklist:!0,removeFromBlacklist:!0,getFriendList:!0,addFriend:!0,deleteFriend:!0,updateFriend:!0,checkFriend:!0,getFriendProfile:!0,getFriendApplicationList:!0,acceptFriendApplication:!0,refuseFriendApplication:!0,deleteFriendApplication:!0,setFriendApplicationRead:!0,getFriendGroupList:!0,createFriendGroup:!0,deleteFriendGroup:!0,addToFriendGroup:!0,removeFromFriendGroup:!0,renameFriendGroup:!0};var Vl=new class{install(e){console.log(el+" install");var{helper:t,notificationCenter:s,InnerEvent:r,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:n}}=this._core=e;Cl.init(e),El.init(e),Ol.init(e),kl.init(e),$l.init(e),t.registerValidateConfig({auth:xl,params:ql}),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,n.FRIEND_AND_BLACKLIST_SYNC,this.handleLoginSuccess,this),s.subscribeInnerEvent(r.LOGOUT,this.reset,this),s.subscribeInnerEvent(r.MESSAGE_PUSH,s.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this)}handleLoginSuccess(){console.log(el+" handleLoginSuccess"),$l.syncBlacklistFromServer(),El.syncFriendListFromServer(),Ol.syncFriendApplicationListFromServer(),kl.syncFriendGroupListFromServer()}onFriendModified(e){var{from:e,addedBlacklist:t,removedBlacklist:s,addedFriendList:r,removedFriendList:o,addedApplicationList:n,removedApplicationList:i,friendUpdateInfo:a,reportTime:l}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),u=this._core.utils["isEmpty"];u(t)&&u(s)||$l.updateBlacklist({addedBlacklist:t,removedBlacklist:s}),u(r)&&u(o)||(El.updateFriendList({addedFriendList:r,removedFriendList:o}),Ol.updateFriendApplicationList({from:e,removedApplicationList:r})),u(a)||El.updateFriendInfo(a),u(n)&&u(i)||Ol.updateFriendApplicationList({from:e,addedApplicationList:n,removedApplicationList:i}),l&&Ol.onApplicationRead()}_parseFriendListModification(e){var{PushType:e,From_Account:t,To_Account:s,ReportTime:r,BlackListAdd_Account:o=[],BlackListDel_Account:n=[],FriendAdd_Account:i=[],FriendDel_Account:a=[],PendencyAdd:l=[],FrienPencydDel_Account:u=[],FriendUpInfo:c=[]}=e,c=c.map(e=>({userID:e.Friend_Account,tagValueList:[...e.SNS]}));return{pushType:e,from:t,to:s,reportTime:r,addedBlacklist:o,removedBlacklist:n,addedFriendList:i,removedFriendList:a,addedApplicationList:l.map(e=>({userID:e.PendencyAdd_Account,source:e.AddSource,time:e.AddTime,wording:e.AddWording,nick:e.ProfileImNick})),friendUpdateInfo:c,removedApplicationList:u}}reset(){console.log(el+" reset"),$l.reset(),El.reset(),Ol.reset(),kl.reset()}dispose(){console.log(el+" dispose");var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,e.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this),$l.dispose(),El.dispose(),Ol.dispose(),kl.dispose()}};let Bl=new class{init(e){this.core=e}},jl="Follow",Kl="FOLLOW",Wl=3122,Hl={NONE:0,FOLLOWERS:1,FOLLOWING:2,MUTUAL:3};function Yl(i,a){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Bl.core,t={FollowType:i,From_Account:null==(t=t.get("login"))?void 0:t.userId,StartCursor:a,WantNum:ed()},{FollowItem:e=[],NextCursor:t,ActionStatus:s,ErrorCode:r,ErrorInfo:o,ErrorDisplay:n}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_get",data:t});return{resultList:e.map(e=>({userID:e.To_Account,followTime:e.FollowTime,profileItem:e.ProfileItem,profileSequence:e.ProfileSequence})),nextPageToken:t,actionStatus:s,errorCode:r,errorInfo:o,errorDisplay:n}})}function zl(e){return h(this,void 0,void 0,function*(){return Yl(Hl.FOLLOWERS,e)})}function Jl(e){return h(this,void 0,void 0,function*(){return Yl(Hl.MUTUAL,e)})}function Ql(e){return h(this,void 0,void 0,function*(){return Yl(Hl.FOLLOWING,e)})}function Xl(n){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Bl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,FollowItem:n.map(e=>({To_Account:e}))},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:o}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_add",data:t});return{resultList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:o}})}function Zl(n){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Bl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:o}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_delete",data:t});return{resultList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:o}})}function ed(){let e=Bl.core.store.get("cloudConfig")||{},t=null==e?void 0:e.follow_req_count;if(void 0===t)return 500;{let e=Number(t);return 1e3<e?1e3:e}}let td={getMyFollowersList:[{required:!1,rules:["string"],allowEmpty:!0}],getMyFollowingsList:[{required:!1,rules:["string"],allowEmpty:!0}],getMutualFollowersList:[{required:!1,rules:["string"],allowEmpty:!0}],followUser:[{required:!0,rules:["array"],allowEmpty:!1}],unfollowUser:[{required:!0,rules:["array"],allowEmpty:!1}],checkFollow:[{required:!0,rules:["array"],allowEmpty:!1}],getUserFollowInfo:[{required:!0,rules:["array"],allowEmpty:!1}]},sd={getMyFollowersList:!0,getMyFollowingsList:!0,getMutualFollowersList:!0,followUser:!0,unfollowUser:!0,checkFollow:!0,getUserFollowInfo:!0};var od=new class{install(e){var{helper:t,notificationCenter:s,InnerEvent:r}=this._core=e;Bl.init(e),t.registerApi({apiName:"getMyFollowingList",context:this}),t.registerApi({apiName:"getMyFollowersList",context:this}),t.registerApi({apiName:"getMutualFollowersList",context:this}),t.registerApi({apiName:"followUser",context:this}),t.registerApi({apiName:"unfollowUser",context:this}),t.registerApi({apiName:"getUserFollowInfo",context:this}),t.registerApi({apiName:"checkFollowType",context:this}),t.registerValidateConfig({auth:sd,params:td}),s.subscribeInnerEvent(r.MESSAGE_PUSH,s.InnerEventSubType.FOLLOW_LIST_UPDATED,this.onFollowListUpdated,this)}getMyFollowingList(){return h(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowingList",protocolFunction:Ql,nextCursor:e})})}getMyFollowersList(){return h(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowersList",protocolFunction:zl,nextCursor:e})})}getMutualFollowersList(){return h(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMutualFollowersList",protocolFunction:Jl,nextCursor:e})})}_getFollowList(e){return h(this,void 0,void 0,function*(){var{functionName:o,protocolFunction:n,nextCursor:i=""}=e;console.log(jl+` ${o} nextCursor:`,i);try{this._checkBusinessCapabilityBits(o);let e=yield n(i),{resultList:t=[],nextPageToken:s=""}=e,r=this._parseFollowItems(t);return console.log(jl+`.${o} nextCursor: ${i} from remote.`),{code:0,data:{resultList:r,nextCursor:s}}}catch(e){console.error(jl+`.${o} fail:`,e),this._handleError(o,e)}})}followUser(e){return h(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"followUser",userIDList:e,protocolFunction:Xl})})}unfollowUser(e){return h(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"unfollowUser",userIDList:e,protocolFunction:Zl})})}_handleUserFollowRelation(e){return h(this,void 0,void 0,function*(){var{functionName:t,userIDList:s,protocolFunction:r}=e;try{let e=this._sliceUserIDList(s,20);this._checkBusinessCapabilityBits(t);var{resultList:o=[]}=yield r(e);return{code:0,data:o}}catch(e){this._handleError(t,e)}})}getUserFollowInfo(n){return h(this,void 0,void 0,function*(){var s="getUserFollowInfo";console.log(jl+` ${s} userIDList:`,n);try{this._checkBusinessCapabilityBits(s);var o=n||[this._core.common.getCurrentUserID()];console.log(jl+` ${s} userIDList: `+o);let e=yield function(n){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Bl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{FollowInfo:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:o}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_get_info",data:t});return{followInfoList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,followerCount:e.FollowerCount,followingCount:e.FollowingCount,mutualFollowingCount:e.MutualFollowingCount})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:o}})}(n),{followInfoList:t=[]}=e,r=[];return t.forEach(e=>{var{followerCount:e,followingCount:t,mutualFollowingCount:s}=e;r.push({followerCount:e,followingCount:t,mutualFollowingCount:s})}),{code:0,data:r}}catch(e){this._handleError(s,e)}})}checkFollowType(r){return h(this,void 0,void 0,function*(){var t="checkFollowType";console.log(jl+` ${t} userIDList:`,r);try{this._checkBusinessCapabilityBits(t),100<r.length&&(r=r.slice(0,100),console.warn(jl+` ${t} the length of userIDList cannot exceed 100`));var e=yield function(n){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Bl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:o}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_check",data:t});return{resultList:e.map(e=>({userID:e.To_Account,followType:e.FollowType,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:o}})}(r),{resultList:s=[]}=e;return{code:0,data:s.map(({userID:e,followType:t})=>({userID:e,followType:t}))}}catch(e){this._handleError(t,e)}})}onFollowListUpdated(e){console.log(jl+" onFollowListUpdated",e);var{FollowChangeList:e=[]}=e;e.forEach(e=>this._processFollowChangeItem(e))}_processFollowChangeItem(e){let{From_Account:t,FollowDiffList:s=[]}=e,r=p(e,["From_Account","FollowDiffList"]),o={userID:t,avatar:r.FaceUrl,nick:r.NickName};s.forEach(e=>{e=this._updateFollowRelation(e,o);this._notifyFollowChanges(e)})}_updateFollowRelation(e,t){var{IsAdd:e,FollowType:s=0}=e,r=this._initFollowInfo(),s=r[s];return s.isAdd=1===e,s.userInfoList.push(s.isAdd?t:t.userID),r}_notifyFollowChanges(e){let t=this._core["OuterEvent"],s={[Hl.FOLLOWERS]:t.MY_FOLLOWERS_LIST_UPDATED,[Hl.FOLLOWING]:t.MY_FOLLOWING_LIST_UPDATED,[Hl.MUTUAL]:t.MUTUAL_FOLLOWERS_LIST_UPDATED};Object.entries(e).forEach(([e,t])=>{e=Number(e);0<t.userInfoList.length&&s[e]&&this._emitFollowUpdated(s[e],t)})}_initFollowInfo(){let t={};return Object.values(Hl).forEach(e=>{e!==Hl.NONE&&(t[e]={userInfoList:[],isAdd:!1})}),t}_emitFollowUpdated(e,t){console.log(jl+" _emitFollowUpdated");var s=this._core["notificationCenter"];s.emitOuterEvent(e,{name:e,data:t})}_sliceUserIDList(e,t){return e.slice(0,t)}_checkBusinessCapabilityBits(e){var{helper:t,store:s}=this._core;if(!(s.get("commercialConfig")||new Map).get(Kl))throw new t.ChatError({functionName:e,code:Wl,replacement1:e})}_handleError(e,t){t=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(jl+` ${e} fail:`,t),t}_parseFollowItems(e){return e.map(e=>{let t,{userID:s,followTime:r,profileItem:o=[]}=e,n=[];o.forEach(e=>{n.push({tag:e.Tag,value:e.Value})});e=null==(t=this._core.user.userProfile)?void 0:t.createProfile(s,n);return{userID:s,followTime:r,nick:null==e?void 0:e.nick,avatar:null==e?void 0:e.avatar,allowType:null==e?void 0:e.allowType,adminForbidType:null==e?void 0:e.adminForbidType}})}};let nd=new class{init(e){this.core=e}},id="message",rd="user",ad={OR:"or",AND:"and"},cd=20,ud=20,ld=20,dd={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},pd={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![ad.OR,ad.AND].includes(e)||"keywordListMatchType should be OR or AND"},hd={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},_d={required:!1,rules:["string"],allowEmpty:!0},gd={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=nd.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"}},md={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=nd.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"}},vd={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=nd.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},fd=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),Id={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=nd.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Sd={searchCloudMessages:{keywordList:dd,keywordListMatchType:pd,cursor:_d,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:md,conversationID:vd,timePosition:fd("timePosition"),timePeriod:fd("timePeriod")},searchCloudUsers:{keywordList:dd,keywordListMatchType:pd,cursor:_d,count:hd,miniBirthday:fd("miniBirthday"),maxBirthday:fd("maxBirthday"),gender:Id},searchCloudGroupMembers:{keywordList:dd,keywordListMatchType:pd,cursor:_d,count:hd,groupTypeList:gd,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:dd,keywordListMatchType:pd,cursor:_d,count:hd,groupTypeList:gd}},Ed={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Cd=new class{install(e){this._core=e,nd.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:Ed,params:Sd})}searchCloudMessages(I){return h(this,void 0,void 0,function*(){try{let{OuterConstant:i,helper:a,ssoLog:e}=this._core,t=e.createSSOLogData({method:"searchCloudMessages"}),{conversationID:s,timePeriod:r,timePosition:o}=I,n=p(I,["conversationID","timePeriod","timePosition"]),l=Object.assign({count:100},n);s&&(s.startsWith(i.CONV_C2C)?l.account=s.replace(i.CONV_C2C,""):s.startsWith(i.CONV_GROUP)&&(l.groupID=s.replace(i.CONV_GROUP,""))),this._setTimeRangeParams(l,{timePeriod:r,timePosition:o});var u=yield function(c){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:o,endTime:n,startTime:i,cursor:a,account:l,groupID:u}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:o,EndTime:n,StartTime:i,Cursor:a,PeerAccount:l,GroupID:u};return nd.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(l);if(!u)return{code:0,data:{}};var{ErrorCode:c,ErrorInfo:d,TotalCount:_,Cursor:g="",ConversationMsgs:m=[]}=u;if(0!==c)throw{errorCode:c,errorInfo:d};var v=`keywordList:${I.keywordList} keywordListMatchType:${I.keywordListMatchType} cursor:${I.cursor} res: totalCount:`+_,f=(t.setLogInfo({message:v}).end(),m.map(e=>{let{MsgList:t,Count:s,GroupID:o,UserID:r}=e,n=o?""+i.CONV_GROUP+o:""+i.CONV_C2C+r;return this._isSearchingAllConversations(I)&&1<s?{conversationID:n,messageCount:s,messageList:[]}:{conversationID:n,messageCount:s,messageList:t.map(e=>{return a.isEmpty(o)?(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:f,cursor:g,totalCount:_}}}catch(e){var{errorCode:u,errorInfo:c}=e||{};this._handleError({errorCode:u,errorInfo:c,searchType:id,functionName:"searchCloudMessages"})}})}searchCloudUsers(S){return h(this,void 0,void 0,function*(){var s;try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:t,count:r=ud}=S,o=p(S,["keywordListMatchType","count"]),n=Object.assign({count:r,keywordListMatchType:t===ad.AND?1:0},o),i=(this._setBirthdayRangeParams(n,S),yield function(a){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:o,cursor:n,gender:i}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,UserBirthStart:r,UserBirthEnd:o,Gender:i};return nd.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(n));if(!i)return{error:0,data:{}};var{ErrorCode:a,ErrorInfo:l,TotalCount:u,Cursor:c="",Users:d=[]}=i;if(0!==a)throw{errorCode:a,errorInfo:l};var _=`keywordList:${S.keywordList} keywordListMatchType:${S.keywordListMatchType} cursor:${S.cursor} count:${S.count} res: totalCount:`+u,g=(e.setLogInfo({message:_}).end(),[]);for(let e=0,t=d.length;e<t;e++){var m,v,{UserID:f,ProfileItems:I}=d[e];f!==this._core.OuterConstant.USER_NOT_FOUND&&""!==f&&(m=I.map(e=>({tag:e.Tag,value:e.StrValue})),v=null==(s=this._core.user.userProfile)?void 0:s.createProfile(f,m),g.push(v))}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:rd,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(_){return h(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:t=ld,keywordListMatchType:s}=_,r=p(_,["count","keywordListMatchType"]),o=yield function(i){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:o,groupIDList:n}=i,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:o,GroupType:r,GroupIdList:n};return nd.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===ad.AND?1:0},r));if(!o)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:i,GroupMembers:a=[],Cursor:u,TotalCount:c}=o;if(0!==n)throw{errorCode:n,errorInfo:i};var d=`keywordList:${_.keywordList} keywordListMatchType:${_.keywordListMatchType} cursor:${_.cursor} count:${_.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:o,GroupMemberUserID:n,GroupMemberNameCard:i,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:n,nick:o,nameCard:i,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:rd,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(d){return h(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:t=cd,keywordListMatchType:s}=d,r=p(d,["count","keywordListMatchType"]),o=yield function(n){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:o}=n,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:o,GroupType:r};return nd.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===ad.AND?1:0},r));if(!o)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:i,Groups:a,Cursor:l,TotalCount:u}=o;if(0!==n)throw{errorCode:n,errorInfo:i};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:o,GroupOwnerTinyID:n,GroupOwnerUserID:i,GroupOwnerUserName:a,GroupType:l,GroupAddOption:u,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:o,ownerTinyID:n,ownerID:i,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:rd,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:o,helper:n}=this._core;let i=e;60020===e?i="SearchUnable":s!==id&&27003===e?i="SearchParamsError":s!==id&&60018===e&&(i="SearchOverLimit");s=new n.ChatError({code:i,message:t});throw o.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)}},Md=new class{constructor(){this._conversationGroupMap=new Map}init(e){this._core=e}getConversationGroupMap(){return this._conversationGroupMap}getConversationGroup(e){return this._conversationGroupMap.get(e)}setConversationGroup(e,t){this._conversationGroupMap.set(e,t)}};let yd=new class{init(e){this.core=e}},Td="CONV_GROUP",Ad=2500,Od=2503,Dd=1,Rd=2,Ld="NOT_STARTED",Nd="FETCHING",bd="FINISHED",Gd="FAILED",wd=0,Pd=1,Ud=1,kd=2,Fd=3,$d=1,qd=2;function xd(e){var{helper:t,constants:s}=yd.core;if(!t.checkBusinessCapabilityBits(Td))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}function Vd(){var{notificationCenter:e,OuterEvent:t}=yd.core;e.emitOuterEvent(t.CONVERSATION_GROUP_LIST_UPDATED,{name:t.CONVERSATION_GROUP_LIST_UPDATED,data:[...Md.getConversationGroupMap().values()]})}function Bd(e){var{utils:{isUndefined:t},constants:{OuterConstant:s}}=yd.core,{Type:e,To_Account:r,GroupId:o,ToGroupId:o=o,Peer_Account:n}=e;let i="";return e===Dd?t(n)?t(r)||(i=""+s.CONV_C2C+r):i=""+s.CONV_C2C+n:e===Rd&&(i=""+s.CONV_GROUP+o),i}function Kd(e){let t=[],{OuterConstant:s,common:{isC2CConv:r,isGroupConv:o}}=yd.core,{conversationIDList:n,failureConversationIDList:i,additionalData:a={}}=e;return n.forEach(e=>{Wd(e,i),r(e)?t.push(Object.assign({ContactItem:{Type:Dd,To_Account:e.replace(s.CONV_C2C,"")}},a)):o(e)&&t.push(Object.assign({ContactItem:{Type:Rd,ToGroupId:e.replace(s.CONV_GROUP,"")}},a))}),t}function Wd(e,t){var{appStore:{conversationStore:s},common:{isC2CConv:r,isGroupConv:o}}=yd.core;s.getConversation(e)?r(e)||o(e)||t.push({conversationID:e,code:Od}):t.push({conversationID:e,code:Ad})}function Hd(t){var{isString:e}=yd.core["utils"],s=[];if(e(t)){var r=t.length;if(0!==r)for(let e=r-1;0<=e;e--)"1"===t[e]&&s.push(Math.pow(2,r-e-1))}return s}function Yd(o){null!=o&&o.forEach((e,t)=>{var s=yd.core["appStore"],{conversationID:e,data:r}=e,t=t===o.length-1;s.conversationStore.updateConversation(e,r,{emit:t})})}function zd(e){var{conversationInfoList:e,fromAccount:t}=e,t={From_Account:t,MarkItem:e};return yd.core.common.buildAndSendPacket({servcmd:"recentcontact.mark_contact",data:t})}function Jd(e){var{fromAccount:e,groupName:t,conversationInfoList:s}=e,e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:qd,OldGroupName:t,ContactUpdateItem:s}};return yd.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}var Qd=new class{init(e){var{registerApi:t}=e["helper"];this._core=e,t({apiName:"createConversationGroup",context:this})}createConversationGroup(r){return h(this,void 0,void 0,function*(){let{utils:{isPlainObject:n,isArray:i},appStore:a,ssoLog:e}=this._core;xd("createConversationGroup");var l=e.createSSOLogData({method:"createConversationGroup"});l.setLogInfo({message:JSON.stringify(r)});let{groupName:u,conversationIDList:t}=r,c=[],s=this._generateConversationInfo(t,c);if(c.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:c}};try{let o=yield function(e){var{buildAndSendPacket:t,getCurrentUserID:s}=yd.core["common"],{item:e,groupName:r}=e;return t({servcmd:"recentcontact.create_contact_group",data:{From_Account:s(),GroupContactItem:[{GroupName:r,ContactItem:e}]}})}({groupName:u,item:s});if(o){l.end();let{GroupResultItem:e=[]}=o,{GroupItem:s,ResultItem:t}=(null==e?void 0:e[0])||{},r=[];if(n(s)){let{GroupName:e,GroupId:t}=s;Md.setConversationGroup(t,e),Vd()}if(i(t)){let n=[];t.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,o=Bd(t);if(0===s){let t=a.conversationStore.getConversation(o);if(t&&!t.conversationGroupList.includes(u)){let e=t.conversationGroupList.slice();e.push(u),n.push({conversationID:o,data:{conversationGroupList:e}})}}else c.push({conversationID:o,code:s,message:r})}),0<n.length&&(Yd(n),Vd())}return{code:0,data:{successConversationIDList:r,failureConversationIDList:c}}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"createConversationGroup",code:t,message:s});throw l.setError(r).end(),r}})}_generateConversationInfo(e,t,s={}){let r=[],{OuterConstant:o,common:{isC2CConv:n,isGroupConv:i}}=this._core;return e.forEach(e=>{Wd(e,t),n(e)?r.push(Object.assign({Type:Dd,To_Account:e.replace(o.CONV_C2C,"")},s)):i(e)&&r.push(Object.assign({Type:Rd,ToGroupId:e.replace(o.CONV_GROUP,"")},s))}),r}},Xd=new class{constructor(){this._fetchConversationGroupStatus=Ld}init(e){var{helper:{registerApi:t,registerWorkflowStep:s},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:o}}=e;this._core=e,t({apiName:"getConversationGroupList",context:this}),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_GROUP_LIST_SYNC,this._syncConversationGroupList,this),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_GROUP_UPDATE,this._updateConversation,this)}getConversationGroupList(){return h(this,void 0,void 0,function*(){return xd("getConversationGroupList"),this._fetchConversationGroupStatus===Gd&&(yield this._fetchConversationGroupList(0)),{code:0,data:[...Md.getConversationGroupMap().values()]}})}_syncConversationGroupList(){return h(this,void 0,void 0,function*(){return yield this._fetchConversationGroupList(0)})}_fetchConversationGroupList(e){return h(this,arguments,void 0,function*(r,n=[]){let{common:{getCurrentUserID:e},utils:{isArray:i}}=this._core;this._fetchConversationGroupStatus=Nd;try{let s=e(),o=yield function(){var{fromAccount:e,startIndex:t}={fromAccount:s,startIndex:r},e={From_Account:e,StartIndex:t};return yd.core.common.buildAndSendPacket({servcmd:"recentcontact.get_contact_group",data:e})}();if(o){let{CompleteFlag:e,ContactItem:t=[],NextStartIndex:s=0,GroupItem:r=[]}=o;return(i(r)&&r.forEach(e=>{var{GroupName:e,GroupId:t}=e;Md.setConversationGroup(t,e)}),n.push(...t),e===wd)?this._fetchConversationGroupList(s):e===Pd?(this._fetchConversationGroupStatus=bd,n):void 0}}catch(r){this._fetchConversationGroupStatus=Gd,console.error(r)}})}_updateConversation(e){var t=this._core["constants"]["WORKFLOW_STEP"],e=(null==(e=null==e?void 0:e.result)?void 0:e[t.CONVERSATION_GROUP_LIST_SYNC])||[];Yd(this._generateConversationUpdateFields(e)),Vd()}_generateConversationUpdateFields(e){let{utils:{isArray:i},appStore:a}=this._core,l=[];if(i(e)){let n;e.forEach(e=>{let t=[],{StandardMark:s,CustomMark:r="",ContactGroupId:o}=e;i(o)&&o.forEach(e=>{Md.getConversationGroupMap().has(e)&&t.push(Md.getConversationGroup(e))});e=Bd(e);(n=a.conversationStore.getConversation(e))&&l.push({conversationID:e,data:{markList:Hd(s),customData:r,conversationGroupList:[...t]}})})}return l}reset(){this._fetchConversationGroupStatus=Ld}dispose(){this.reset()}},Zd=new class{init(e){var{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{CONVERSATION_MARK_UPDATED:o,CONVERSATION_GROUP_ADD:n,CONVERSATION_GROUP_DELETED:i,CONVERSATION_GROUP_UPDATED:a}}=e;this._core=e,s({apiName:"renameConversationGroup",context:this}),s({apiName:"deleteConversationGroup",context:this}),s({apiName:"markConversation",context:this}),s({apiName:"setConversationCustomData",context:this}),s({apiName:"deleteConversationsFromGroup",context:this}),s({apiName:"addConversationsToGroup",context:this}),t.subscribeInnerEvent(r,n,this._handleConversationGroupAdd,this),t.subscribeInnerEvent(r,i,this._handleConversationGroupDeleted,this),t.subscribeInnerEvent(r,a,this._handleConversationGroupUpdated,this),t.subscribeInnerEvent(r,o,this._handleConversationMarkUpdated,this)}renameConversationGroup(t){return h(this,void 0,void 0,function*(){xd("renameConversationGroup");let{common:{getCurrentUserID:r},ssoLog:e}=this._core,{oldName:o,newName:n}=t,i=e.createSSOLogData({method:"renameConversationGroup"});i.setLogInfo({message:`oldName:${o} newName:`+n});try{let s=yield function(){var{fromAccount:e,oldName:t,newName:s}={fromAccount:r(),oldName:o,newName:n},e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:$d,OldGroupName:t,NewGroupName:s}};return yd.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}();if(s){i.end();let e=s["UpdateGroupResult"],t=e["GroupId"];Md.setConversationGroup(t,n),Vd(),this._updateLocalConversationGroupName({oldName:o,newName:n})}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"renameConversationGroup",code:t,message:s});throw i.setError(r).end(),r}})}deleteConversationGroup(r){return h(this,void 0,void 0,function*(){xd("deleteConversationGroup");let{common:{getCurrentUserID:s},ssoLog:e}=this._core,o=e.createSSOLogData({method:"deleteConversationGroup"});o.setLogInfo({message:"groupName:"+r});try{let t=yield function(){var{fromAccount:e,groupName:t}={fromAccount:s(),groupName:r},e={From_Account:e,GroupName:[t]};return yd.core.common.buildAndSendPacket({servcmd:"recentcontact.del_contact_group",data:e})}();if(t){let e=t["GroupItem"],s=!1;null!=e&&e.forEach(e=>{var e=e["GroupId"],t=Md.getConversationGroupMap();t.has(e)&&(t.delete(e),s=!0)}),s&&Vd(),this._deleteLocalConversationGroupName([r])}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"deleteConversationGroup",code:t,message:s});throw o.setError(r).end(),r}})}markConversation(_){return h(this,void 0,void 0,function*(){xd("markConversation");let{utils:{isNumber:e},common:{getCurrentUserID:s},ssoLog:t,appStore:i}=this._core,{conversationIDList:r,markType:a,enableMark:l}=_,o=this._getFlagBit(a),u=[],c=[],n,d;var h=t.createSSOLogData({method:"markConversation"}),p=(h.setLogInfo({message:JSON.stringify(_)}),!0===l&&e(o)?n=[o]:d=[o],Kd({conversationIDList:r,failureConversationIDList:u,additionalData:{SetMark:n,ClearMark:d,OptType:Ud}}));if(u.length===r.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:u}};try{let t=yield zd({conversationInfoList:p,fromAccount:s()});if(t){h.end();let e=t["ResultItem"],n=[];e.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,o=Bd(t);if(0===s){c.push(o);let s=i.conversationStore.getConversation(o);if(s){let t=s.markList.indexOf(a),e=!1===l&&-1!==t;if(!0===l&&-1===t)n.push({conversationID:o,data:{markList:[...s.markList,a]}});else if(e){let e=s.markList.slice();e.splice(t,1),n.push({conversationID:o,data:{markList:e}})}}}else u.push({conversationID:o,code:s,message:r})}),Yd(n)}return{code:0,data:{successConversationIDList:c,failureConversationIDList:u}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"markConversation",code:t,message:s});throw h.setError(r).end(),r}})}setConversationCustomData(o){return h(this,void 0,void 0,function*(){xd("setConversationCustomData");let{common:{getCurrentUserID:e},ssoLog:t,appStore:n}=this._core,{conversationIDList:s,customData:i}=o,a=[],l=[],u=t.createSSOLogData({method:"setConversationCustomData"});u.setLogInfo({message:JSON.stringify(o)});var r=Kd({conversationIDList:s,failureConversationIDList:a,additionalData:{CustomMark:i,OptType:kd}});if(a.length===s.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:a}};try{let t=yield zd({fromAccount:e(),conversationInfoList:r});if(t){u.end();let e=t["ResultItem"],o=[];null!=e&&e.forEach(e=>{let{ContactItem:s,ResultCode:t,ResultInfo:r}=e;if(0===t){let e=Bd(s),t=(l.push(e),n.conversationStore.getConversation(e));t&&t.customData!==i&&o.push({conversationID:e,data:{customData:i}})}else a.push({conversationID:conversationID,code:t,message:r})}),Yd(o)}return{code:0,data:{successConversationIDList:l,failureConversationIDList:a}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"setConversationCustomData",code:t,message:s});throw u.setError(r).end(),r}})}deleteConversationsFromGroup(o){return h(this,void 0,void 0,function*(){xd("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},ssoLog:t,appStore:n}=this._core,i=t.createSSOLogData({method:"deleteConversationsFromGroup"}),{conversationIDList:s,groupName:a}=(i.setLogInfo({message:JSON.stringify(o)}),o),l=[],u=[],r=Kd({conversationIDList:s,failureConversationIDList:l,additionalData:{ContactOptType:2}});if(l.length===s.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:l}};try{let t=yield Jd({fromAccount:e(),groupName:a,conversationInfoList:r});if(t){i.end();let o=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var s,r=Bd(e.ContactItem);if(0===e.ResultCode){let t=n.conversationStore.getConversation(r);if(t){let e=t.conversationGroupList.indexOf(a);-1!==e&&((s=t.conversationGroupList.slice()).splice(e,1),u.push(r),o.push({conversationID:r,data:{conversationGroupList:s}}))}}else l.push({conversationID:r,code:e.ResultCode,message:e.ResultInfo})}),0<o.length&&(Vd(),Yd(o))}return{code:0,data:{successConversationIDList:u,failureConversationIDList:l}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s});throw i.setError(r).end(),r}})}addConversationsToGroup(u){return h(this,void 0,void 0,function*(){xd("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},ssoLog:t,appStore:o}=this._core,n=t.createSSOLogData({method:"addConversationsToGroup"}),{conversationIDList:s,groupName:i}=(n.setLogInfo({message:JSON.stringify(u)}),u),a=[],l=[],r=Kd({conversationIDList:s,failureConversationIDList:a,additionalData:{ContactOptType:1}});if(a.length===s.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:a}};try{let t=yield Jd({fromAccount:e(),groupName:i,conversationInfoList:r});if(t){n.end();let r=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var s=Bd(e.ContactItem);if(0===e.ResultCode){let t=o.conversationStore.getConversation(s);if(t&&-1===t.conversationGroupList.indexOf(i)){let e=t.conversationGroupList.slice();e.push(i),l.push(s),r.push({conversationID:s,data:{conversationGroupList:e}})}}else a.push({conversationID:s,code:e.ResultCode,message:e.ResultInfo})}),0<r.length&&(Vd(),Yd(r))}return{code:0,data:{successConversationIDList:l,failureConversationIDList:a}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s});throw n.setError(r).end(),r}})}_updateLocalConversationGroupName(e){let t=this._core["appStore"],{oldName:s,newName:r}=e,o=[],n=[],i;Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var t;o=e.conversationGroupList,-1!==(i=o.indexOf(s))&&((t=o.slice()).splice(i,1,r),n.push({conversationID:e.conversationID,data:{conversationGroupList:t}}))}),Yd(n)}_deleteLocalConversationGroupName(o){var{utils:{isEmpty:e},appStore:t}=this._core;if(!e(o)){let r=[];Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var{conversationID:e,conversationGroupList:t}=e,s=t.filter(e=>!o.includes(e));s.length<t.length&&r.push({conversationID:e,data:{conversationGroupList:s}})}),Yd(r)}}_getFlagBit(e){var t=e.toString(2),s=t.length;for(let e=s-1;0<=e;e--)if("1"===t[e])return s-e-1}_handleConversationGroupAdd(e){let t,{utils:{isArray:a},appStore:l}=this._core;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{var e=e["RecentContactCreateContactGroup"]["MsgContactGroupContactItem"];let i=!1;null!=e&&e.forEach(e=>{let{MsgGroupItem:t,MsgRecentContactItem:s}=e,{GroupId:r,GroupName:o}=t,n=[];Md.getConversationGroup(r)!==o&&(Md.setConversationGroup(r,o),i=!0),a(s)&&s.forEach(e=>{var t=Bd(e),s=l.conversationStore.getConversation(t);if(s&&(null==(e=s.conversationGroupList)||!e.includes(o))){let e=s.conversationGroupList.slice();e.push(o),n.push({conversationID:t,data:{conversationGroupList:e}})}}),i&&Vd(),Yd(n)})})}_handleConversationGroupDeleted(e){let t,{isArray:s}=this._core.utils;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{e=((null==e?void 0:e.RecentContactDelContactGroup)||{}).MsgGroupItem;if(s(e)){let r=!1,o=[];e.forEach(e=>{var{GroupId:e,GroupName:t}=e,s=Md.getConversationGroupMap();s.has(e)&&(s.delete(e),r=!0,o.push(t))}),r&&Vd(),0<o.length&&this._deleteLocalConversationGroupName(o)}})}_handleConversationGroupUpdated(e){null!=(e=e.RecentContactMod)&&e.forEach(e=>{var{GroupId:e,GroupName:t,OldGroupName:s,RecentContactUpdateGroupItem:r,UpdateGroupType:o}=e["RecentContactUpdateContactGroup"]["MsgUpdateGroup"];1===o?this._handleGroupNameUpdated({groupID:e,newName:t,oldName:s}):2===o&&this._handleGroupAddOrDeleteFromConversation({groupInfoList:r,groupName:s})})}_handleConversationMarkUpdated(e){let t,n=this._core.appStore;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{let{RecentContactMarkContactItem:t}=e["RecentContactMarkContact"],o=[];null!=t&&t.forEach(e=>{var{RecentContactItem:e,CustomMark:t,StandardMark:s,OptType:r}=e,e=Bd(e),e=n.conversationStore.getConversation(e);e&&(r===Ud?this._updateStandMark({conversation:e,standardMark:s,updateConversationList:o}):r===kd?this._updateCustomMark({conversation:e,customMark:t,updateConversationList:o}):r===Fd&&(this._updateStandMark({conversation:e,standardMark:s,updateConversationList:o}),this._updateCustomMark({conversation:e,customMark:t,updateConversationList:o})))}),Yd(o)})}_updateStandMark(e){var{conversation:e,standardMark:t,updateConversationList:s}=e,t=Hd(t);!function(s,r){if(s===r)return 1;if(s&&r&&s.length===r.length){s.sort(),r.sort();for(let e=0,t=s.length;e<t;e++)if(s[e]!==r[e])return;return 1}}(e.markList,t)&&s.push({conversationID:e.conversationID,data:{markList:t}})}_updateCustomMark(e){var{conversation:e,customMark:t,updateConversationList:s}=e;e.customData!==t&&void 0!==t&&(e.customData=t,s.push({conversationID:e.conversationID,data:{customData:t}}))}_handleGroupNameUpdated(e){var{groupID:e,oldName:t,newName:s}=e;Md.getConversationGroup(e)!==s&&(Md.setConversationGroup(e,s),Vd(),this._updateLocalConversationGroupName({oldName:t,newName:s}))}_handleGroupAddOrDeleteFromConversation({groupInfoList:e,groupName:n}){let i=this._core["appStore"],a=[];e.forEach(e=>{var{RecentContactItem:e,ContactOptType:t}=e,s=Bd(e),r=i.conversationStore.getConversation(s),o=r.conversationGroupList.indexOf(n);if(r){let e=r.conversationGroupList.slice();1===t&&-1===o?(e.push(n),a.push({conversationID:s,data:{conversationGroupList:e}})):2===t&&-1!==o&&(e.splice(o,1),a.push({conversationID:s,data:{conversationGroupList:e}}))}}),Yd(a)}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{CONVERSATION_MARK_UPDATED:s,CONVERSATION_GROUP_ADD:r,CONVERSATION_GROUP_DELETED:o,CONVERSATION_GROUP_UPDATED:n}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleConversationGroupAdd,this),e.unSubscribeInnerEvent(t,o,this._handleConversationGroupDeleted,this),e.unSubscribeInnerEvent(t,n,this._handleConversationGroupUpdated,this),e.unSubscribeInnerEvent(t,s,this._handleConversationMarkUpdated,this)}};let ep={required:!0,rules:["string"],allowEmpty:!1},tp={required:!0,rules:["array"],allowEmpty:!1},sp={createConversationGroup:{groupName:ep,conversationIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameConversationGroup:{oldName:ep,newName:Object.assign(Object.assign({},ep),{customValidator:e=>!(32<e.length)||"newName length cannot longer than 32"})},deleteConversationGroup:[{required:!0,rules:["string"],allowEmpty:!1}],addConversationsToGroup:{conversationIDList:tp,groupName:ep},deleteConversationsFromGroup:{conversationIDList:tp,groupName:ep},markConversation:{conversationIDList:tp,markType:{required:!0,rules:["number"],allowEmpty:!1,customValidator:e=>e<=0?"markType must be greater than 0":!(e>=Math.pow(2,64))||"markType must be less than 2^64"},enableMark:{required:!0,rules:["boolean"],allowEmpty:!1}},setConversationCustomData:{conversationIDList:tp,customData:{required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>"string"!=typeof e?"customData must be string":!(256<e.length)||"customData length cannot longer than 256"}}},op={createConversationGroup:!0,deleteConversationGroup:!0,renameConversationGroup:!0,getConversationGroupList:!0,addConversationsToGroup:!0,deleteConversationsFromGroup:!0,markConversation:!0,setConversationCustomData:!0};var np=new class{install(e){this._core=e,yd.init(e),Md.init(e),Qd.init(e),Xd.init(e),Zd.init(e),e.helper.registerValidateConfig({auth:op,params:sp}),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),Zd.dispose(),Xd.dispose()}reset(){Xd.reset()}};let ip=new class{init(e){this.core=e}},rp="@TOPIC#_",ap=7,cp=8,up=17,lp=18,dp=20,pp=300,hp=0,_p=3600,gp=3021,mp=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],vp=e=>{var{common:{getMessagePreviewText:t}}=ip["core"];return{lastTime:(null==e?void 0:e.time)||0,lastSequence:(null==e?void 0:e.sequence)||0,fromAccount:(null==e?void 0:e.from)||"",payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),nick:(null==e?void 0:e.nick)||"",avatar:(null==e?void 0:e.avatar)||"",version:(null==e?void 0:e.version)||0,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,revoker:(null==e?void 0:e.revoker)||null}};class fp{constructor(e){this.topicID="",this.topicName="",this.avatar="",this.introduction="",this.notification="",this.unreadCount=0,this.muteAllMembers=!1,this.customData="",this.groupAtInfoList=[],this.nextMessageSeq=0,this.lastMessage=vp(),this.selfInfo={muteTime:0,readedSequence:0,messageRemindType:"",excludedUnreadSequenceList:void 0},this._init(e)}_init(e){for(var t in e)mp.includes(t)&&("lastMessage"===t?this[t]=vp(e[t]):"selfInfo"===t?this.updateSelfInfo(e[t]):this[t]="muteAllMembers"===t?1===e[t]:e[t])}updateUnreadCount(e=0){this.unreadCount=e}updateReadSequence(e=0,t=!1){t&&(this.selfInfo.readedSequence=e)}updateNextMessageSeq(e){this.nextMessageSeq=e}updateLastMessage(e){this.lastMessage=vp(e)}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=ip["core"];t(e,this.groupAtInfoList)}updateTopic(e){var{utils:{isUndefined:t},common:{deepMerge:s}}=ip["core"];t(e.selfInfo)||this.updateSelfInfo(e.selfInfo),t(e.muteAllMembers)||(this.muteAllMembers=1===e.muteAllMembers),s(this,e,["groupID","lastMessageTime","selfInfo","muteAllMembers","lastMsg","groupAtInfoList"])}updateSelfInfo(e){var{common:{deepMerge:t}}=ip["core"];return 0<t(this.selfInfo,e,[],[""])}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){return e===(null==(e=this.lastMessage)?void 0:e.lastSequence)}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}clearGroupAtInfoList(){this.groupAtInfoList.length=0}}var Ip=new class{constructor(){this._name="TopicDataHandler",this._topicMap=new Map,this._topicRequestInfo=new Map}init(e){var{helper:e,constants:t,notificationCenter:s,InnerEvent:{LOGOUT:r,DESTROY:o}}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.TOPIC_REQUEST_INFO_RESET,this._resetTopicRequestInfo,this),s.subscribeInnerEvent(r,this._reset,this),s.subscribeInnerEvent(o,this._dispose,this),console.log(this._name+".init")}_hasTopic(e,t){return!(null==(e=this._topicMap.get(e))||!e.get(t))}_setTopic(e,t,s){null!=(e=this._topicMap.get(e))&&e.set(t,s)}_deleteTopic(e,t){null!=(e=this._topicMap.get(e))&&e.delete(t)}getTopic(e,t){return null==(e=this._topicMap.get(e))?void 0:e.get(t)}updateTopic(e){e.forEach(e=>{var{groupID:t,topicID:s}=e;let r=null;this._topicMap.has(t)||this._topicMap.set(t,new Map),this._hasTopic(t,s)?null!=(r=this.getTopic(t,s))&&r.updateTopic(e):(this._getLastMessage(e),r=new fp(e),this._setTopic(t,s,r));e=this.computeUnreadCount(r);null!=r&&r.updateUnreadCount(e)})}_getLastMessage(s){var{isEmpty:r,isUndefined:o,isArray:n}=this._core["utils"];if(!o(s.lastMsg)){let e=null,t="";t=(n(s.lastMsg.elements)?(e=s.lastMsg.elements[0].content,s.lastMsg.elements[0]):(e=s.lastMsg.elements.content,s.lastMsg.elements)).type;o={payload:e,type:t,time:s.lastMsg.time,sequence:s.lastMsg.sequence,from:s.lastMsg.from,nick:s.lastMsg.nick,avatar:s.lastMsg.avatar,version:s.lastMsg.messageVersion,cloudCustomData:s.lastMsg.cloudCustomData,isRevoked:2===s.lastMsg.isPlaceMessage,revoker:r(s.lastMsg.revokerInfo)?null:s.lastMsg.revokerInfo.revoker};s.lastMessage=o}}computeUnreadCount(s){let{excludedUnreadSequenceList:e=[],readedSequence:r}=s.selfInfo,o=s.nextMessageSeq-s.selfInfo.readedSequence-1;if(0<e.length){let t=0;e.forEach(e=>{e>r&&e<=s.nextMessageSeq-1&&(t+=1)}),1<=t&&(o-=t)}return 0<o?o:0}updateTopicAtInfo(e){0!==e.length&&e.forEach(e=>{var t=this._core["utils"]["isEmpty"],e=e["groupAtInfoList"];t(e)||this.updateGroupAtInfoList(e)})}updateGroupAtInfoList(s,a=!1){if(0!==s.length){let{common:{getCurrentUserID:e},utils:{isUndefined:o,isEmpty:t}}=this._core,n=e(),i=null;s.forEach(e=>{var{groupID:t,topicID:s,from:r}=e;r!==n&&((i=this.getTopic(t,s))&&i.updateGroupAtInfoList(e),o(i))&&a&&(this.updateTopic([{groupID:t,topicID:s}]),null!=(r=this.getTopic(t,s)))&&r.updateGroupAtInfoList(e)}),t(i)||this.emitTopicUpdate(i)}}getTopicList(e,t=[]){var e=this._topicMap.get(e),s=[];return e&&s.push(...e.values()),0<t.length?s.filter(e=>t.includes(e.topicID)):s}deleteTopicList(t,e=[]){this._topicMap.has(t)&&(e.forEach(e=>{this._hasTopic(t,e)&&this._deleteTopic(t,e)}),console.log(this._name+`.deleteTopicList groupID:${t} topicID:`+e.join(",")))}clearGroupAtInfoList(e,t){var s=this._core["utils"]["isEmpty"],e=this.getTopic(e,t);s(null==e?void 0:e.groupAtInfoList)||(null!=e&&e.clearGroupAtInfoList(),console.log(this._name+".clearGroupAtInfoList topicID:"+t))}markMessageAsRead(e,s){let{message:{messageDataHandler:t},OuterConstant:{CONV_GROUP:r}}=this._core,o=(null==t?void 0:t.getLocalMessageList(""+r+e))||[];if(0!==o.length){e=o["length"];for(let t=e-1;0<=t;t--){let e=o[t];if(!(s&&e.sequence>s)){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}updateUnreadCount(e,t){var{message:{messageDataHandler:s},OuterConstant:{CONV_GROUP:r}}=this._core;let o=!1;e=this.getTopic(e,t);e&&(s=(null==s?void 0:s.getLocalMessageList(""+r+t))||[],r=e.unreadCount,s=null==s?void 0:s.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount topicID:${t} currentUnreadCount:${r} newUnreadCount:`+s),r!==s&&(e.updateUnreadCount(s),o=!0),o)&&this.emitTopicUpdate(e)}updateSelfInfo(e){var{groupID:e,topicID:t,selfInfo:s}=e,r=this.getTopic(e,t);if(r){let e=r.updateSelfInfo(s);console.log(`${this._name}.updateSelfInfo topicID:${t} info:${JSON.stringify(s)} isUpdated:`+e),e&&this.emitTopicUpdate(r)}}getTopicRequestInfo(e){return this._topicRequestInfo.get(e)||{}}setTopicRequestInfo(e,t){return this._topicRequestInfo.set(e,t)}emitTopicUpdate(e){var{OuterEvent:t,notificationCenter:s}=this._core;s.emitOuterEvent(t.TOPIC_UPDATED,{name:t.TOPIC_UPDATED,data:e})}_resetTopicRequestInfo(){this._topicRequestInfo.clear()}_reset(){this._topicMap.clear(),this._topicRequestInfo.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Sp=(e="")=>{var{OuterConstant:t}=ip["core"];return e.replace(t.CONV_GROUP,"")},Ep=(e="")=>e.split(rp)[0];var Cp=new class{constructor(){this._name="TopicMessageHandler"}init(e){var{helper:e,notificationCenter:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r},InnerEvent:{MESSAGE_PUSH:o,TOPIC_NEW_MESSAGE:n,TOPIC_MESSAGE_DELETED:i,TOPIC_MESSAGE_REVOKED:a,TOPIC_MESSAGE_MODIFIED:l,DESTROY:u}}=this._core=e,{TOPIC_AT_TIPS:c,TOPIC_LATEST_MESSAGE:d}=t["InnerEventSubType"];e.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,r.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(s.RECEIVE_GROUP_NEW_MESSAGE,r.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.subscribeInnerEvent(n,this._handleNewMessage,this),t.subscribeInnerEvent(i,this._handleMessageDeleted,this),t.subscribeInnerEvent(a,this._handleMessageRevoked,this),t.subscribeInnerEvent(l,this._handleMessageModified,this),t.subscribeInnerEvent(o,c,this._handleTopicAtTips,this),t.subscribeInnerEvent(o,d,this._handleLatestMessage,this),t.subscribeInnerEvent(u,this._dispose,this),console.log(this._name+".init")}_handleUnreadSyncFinished(e){let s,{WORKFLOW_STEP:t}=this._core.constants,{groupTipList:r=[]}=e.result[t.UNREAD_MESSAGE_SYNC]||{};for(let t=0;t<r.length;t++){let e=r[t];12===e.Event&&null!=(s=e.GroupTips[0].MsgBody)&&s.TopicId&&this._handleTopicAtTips(e)}}_handleNewMessage(e){var{conversationUpdateFieldList:e=[]}=e.result||{};if(0!==e.length){var t=this._core["common"]["isTopic"];if(t(e[0].conversationID)){let i=this._core["common"]["getCurrentUserID"];e.forEach(e=>{let{conversationID:t="",lastMessage:o}=e,s=Sp(t),r=Ep(s),n=Ip.getTopic(r,s);if(n){let{from:e,sequence:t}=o,s=t+1,r=e===i();if(s>n.nextMessageSeq){n.updateNextMessageSeq(s),n.updateLastMessage(o),n.updateReadSequence(t,r);let e=r?0:Ip.computeUnreadCount(n);n.updateUnreadCount(e),this._emitTopicUpdate(n)}}})}}}_handleMessageDeleted(s){var r=Sp(s),o=Ep(r),o=Ip.getTopic(o,r);if(console.log(this._name+`._handleMessageDeleted, topicID:${r} hasTopic:`+!!o),o){var{message:{messageDataHandler:n},utils:{isEmpty:i}}=this._core,a=(null==n?void 0:n.getLocalMessageList(s))||[];let t={};for(let e=(a.length||0)-1;0<=e;e--)if(!a[e].isDeleted){t=a[e];break}let e=!1;o.lastMessage.lastSequence!==t.sequence&&(i(t)&&(t={}),o.updateLastMessage(t),e=!0),e&&(this._emitTopicUpdate(o),console.log(this._name+`._handleMessageDeleted, topicID:${r} with lastMessage:`+o.lastMessage))}}_handleMessageRevoked(e){var{messageList:e=[]}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+e.length),0!==e.length){let o=null,n=!1;e.forEach(e=>{var{to:e,sequence:t,revoker:s}=e,r=Ep(e);if(o=Ip.getTopic(r,e)){o.reduceUnreadCount()&&(n=!0),o.isLastMessageRevoked(t)&&(o.setLastMessageRevoked(!0),o.setLastMessageRevoker(s),n=!0);let{excludedUnreadSequenceList:e=[]}=o.selfInfo;e.push(t),o.updateSelfInfo({excludedUnreadSequenceList:e})}}),n&&this._emitTopicUpdate(o)}}_handleMessageModified(e){let{conversationID:t,messageList:s}=e,r=Sp(t),o=Ep(r),a=Ip.getTopic(o,r);if(console.log(`${this._name}._handleMessageModified topicID:${r} hasTopic:`+!!a),a){var l=a["lastMessage"];if(l){let i=(null==s?void 0:s[0])||{};if(this._shouldUpdateLastMessage(l,i)){let{getMessagePreviewText:e}=this._core["common"],{time:t,sequence:s,elements:r,cloudCustomData:o,messageVersion:n}=i;l.type=r[0].type,l.payload=r[0].content,l.messageForShow=e(l.type,l.payload),l.cloudCustomData=o,l.version=n,l.lastSequence=s,l.lastTime=t,this._emitTopicUpdate(a)}}}}_shouldUpdateLastMessage(e,t){var s;return null===e.payload||({sequence:t,messageVersion:s}=t,e.lastSequence===t&&e.version!==s)}_emitTopicUpdate(e){var{notificationCenter:t,OuterEvent:s}=this._core;t.emitOuterEvent(s.TOPIC_UPDATED,{name:s.TOPIC_UPDATED,data:e})}_handleTopicAtTips(e){let{GroupTips:t=[]}=e,n=[],i=!1;t.forEach(e=>{var{GroupAtTips:e,MsgBody:t,MsgRandom:s,ClientSeq:r}=e;let o={};e?o=this._convertAtInfo(e):t&&(o=this._convertAtInfo(t),i=!0),o.__random=s,o.__sequence=r,n.push(o)}),Ip.updateGroupAtInfoList(n,i)}_convertAtInfo(e){var{From_Account:e,GroupId:t,TopicId:s,MsgSeq:r,GroupAtType:o}=e;return{groupID:t,topicID:s,from:e,sequence:r,groupAtType:o}}_handleLatestMessage(e){let{utils:{isEmpty:t},message:{messageHelper:r,messageFactory:o}}=this._core,{NewMsg:n,NoUnreadSeqList:i}=e||{};if(!t(n)){let{TopicId:e}=n["GroupInfo"],t=r.parseServerGroupMessage(n),s=o.createMessage(t);s.setElement(t.elements),this._updateUnreadCountAndLastMessage({topicID:e,message:s,excludedUnreadSequenceList:i})}}_updateUnreadCountAndLastMessage(e){let{isUndefined:t}=this._core["utils"],{topicID:s,message:r,excludedUnreadSequenceList:o}=e,n=Ep(s),i=Ip.getTopic(n,s);if(i){let e=i.selfInfo.excludedUnreadSequenceList||[];if(t(o)||(e=o),r._isExcludedFromUnreadCount&&e.push(r.sequence),i.updateSelfInfo({excludedUnreadSequenceList:e}),console.log(`${this._name}._updateUnreadCountAndLastMessage latest message sequence:${r.sequence} lastMessage sequence:`+i.lastMessage.lastSequence),r.sequence>i.lastMessage.lastSequence){let e=r.sequence+1,t=(i.updateLastMessage(r),i.updateNextMessageSeq(e),Ip.computeUnreadCount(i));i.updateUnreadCount(t),this._emitTopicUpdate(i)}}}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,TOPIC_NEW_MESSAGE:s,TOPIC_MESSAGE_DELETED:r,TOPIC_MESSAGE_REVOKED:o,TOPIC_MESSAGE_MODIFIED:n,DESTROY:i}}=this._core,{TOPIC_AT_TIPS:a,TOPIC_LATEST_MESSAGE:l}=e["InnerEventSubType"];e.unSubscribeInnerEvent(s,this._handleNewMessage,this),e.unSubscribeInnerEvent(r,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(o,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,a,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,l,this._handleLatestMessage,this),e.unSubscribeInnerEvent(i,this._dispose,this)}},Mp=new class{constructor(){this._name="TopicOperationHandler"}init(e){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core=e,{TOPIC_TIPS_NOTIFICATION:r,TOPIC_SYSTEM_NOTIFICATION:o,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._handleTopicTips,this),e.subscribeInnerEvent(t,o,this._handleTopicNotices,this),e.subscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.subscribeInnerEvent(s,this._dispose,this),console.log(this._name+".init")}_handleTopicTips(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e];s.MsgBody.OpType!==ap?s.MsgBody.OpType!==cp?this._emitTopicTips(s):this._handleTopicProfileUpdated(s):this._handleMuteTimeUpdated(s)}}_handleMuteTimeUpdated(e){var{getCurrentUserID:t}=this._core["common"],{GroupInfo:{GroupId:s,TopicId:r},MsgBody:{MsgMemberInfo:o=[]}}=e;for(let e=0;e<o.length;e++){var{User_Account:n,ShutupTime:i}=o[e];if(n===t()&&0<=i){Ip.updateSelfInfo({groupID:s,topicID:r,selfInfo:{muteTime:i}});break}}}_handleTopicProfileUpdated(e){var{GroupInfo:{GroupId:e,TopicId:t},MsgBody:{MsgTopicNewInfo:{CustomString:s,ShutupAll:r,TopicFaceUrl:o,TopicIntroduction:n,TopicName:i,TopicNotification:a}}}=e,l=Ip.getTopic(e,t);l&&(l.updateTopic({groupID:e,topicID:t,customData:s,muteAllMembers:r,avatar:o,introduction:n,topicName:i,notification:a}),Ip.emitTopicUpdate(l))}_handleTopicNotices(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e],{MsgBody:{ReportType:r,TopicIdArray:o,MsgFlag:n},GroupInfo:{GroupId:i,TopicId:a}}=s;r===up?this._handleTopicCreated({groupID:i,topicID:a}):r===lp?this._handleTopicDeleted({groupID:i,topicIDList:o}):r===dp?this._handleMessageRemindTypeUpdated({groupID:i,topicID:a,messageRemindType:n}):this._emitTopicNotices(s)}}_handleTopicCreated(e){var{OuterEvent:t,notificationCenter:s}=this._core;Ip.setTopicRequestInfo(e.groupID,{}),s.emitOuterEvent(t.TOPIC_CREATED,{name:t.TOPIC_CREATED,data:e})}_handleTopicDeleted(e){var{OuterEvent:t,notificationCenter:s}=this._core,{groupID:r,topicIDList:o=[]}=e;Ip.deleteTopicList(r,o),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){var{groupID:e,topicID:t,messageRemindType:s}=e;Ip.updateSelfInfo({groupID:e,topicID:t,selfInfo:{messageRemindType:s}})}_handleTopicMessageReadSynced(e){let t=e["GroupTips"],{isUndefined:s}=this._core["utils"];t.forEach(e=>{e=e.MsgBody.GroupReadInfoArray;s(e)||e.forEach(e=>{var{GroupId:e,TopicId:t,LastReadMsgSeq:s}=e;console.log(this._name+`._handleTopicMessageReadSynced topicID:${t} lastReadSequence:`+s),Ip.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),Ip.clearGroupAtInfoList(e,t),Ip.markMessageAsRead(t,s),Ip.updateUnreadCount(e,t)})})}_emitTopicTips(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:o,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=r.MSG_GRP_TIP,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=r.CONV_GROUP,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:[e]})}_emitTopicNotices(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:o,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=r.MSG_GRP_SYS_NOTICE,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=r.CONV_SYSTEM,t.conversationID=r.CONV_SYSTEM,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:[e]})}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{TOPIC_TIPS_NOTIFICATION:r,TOPIC_SYSTEM_NOTIFICATION:o,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,o,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},yp=new class{constructor(){this._name="GetJoinedCommunityHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getJoinedCommunityList",context:this})}getJoinedCommunityList(){return h(this,void 0,void 0,function*(){var e=this._core["apiMap"]["getGroupList"],e=(yield e(!0)).filter(e=>!0===e.isSupportTopic);return console.log(this._name+".getJoinedCommunityList ok, count:"+e.length),{code:0,data:{groupList:e}}})}},Tp=new class{constructor(){this._name="CreateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(n){return h(this,void 0,void 0,function*(){let s="createTopicInCommunity",{utils:{isUndefined:e},common:{isTopic:t},helper:{ChatError:r}}=this._core,o=n["topicID"];if(!e(o)&&!t(o)){let e=new r({functionName:s,code:gp});throw console.error(this._name+`.${s} fail:`,e),e}try{let e=yield function(a,l){return h(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:o,introduction:n,customData:i}=a;return l.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.create_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:o,Introduction:n,CustomString:i}})})}(n,this._core),{TopicId:t=""}=e||{};return console.log(this._name+`.${s} ok, topicID:`+t),Ip.updateTopic([Object.assign(Object.assign({},n),{topicID:t})]),{code:0,data:{topicID:t}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},Ap=new class{constructor(){this._name="DeleteTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteTopicFromCommunity",context:this})}deleteTopicFromCommunity(l){return h(this,void 0,void 0,function*(){var s="deleteTopicFromCommunity",{groupID:i,topicIDList:a=[]}=l;try{let e=yield function(s,r){return h(this,void 0,void 0,function*(){var{groupID:e,topicIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.destroy_topic",data:{GroupId:e,TopicIdList:t}})})}({groupID:i,topicIDList:a},this._core),{DestroyResultItem:t=[]}=e||{},r=[],o=[],n=[];return t.forEach(e=>{var{TopicId:e,ErrorCode:t,ErrorInfo:s}=e;0===t?(r.push({topicID:e}),n.push(e)):o.push({topicID:e,code:t,message:s})}),0<n.length&&Ip.deleteTopicList(l.groupID,n),console.log(`${this._name}.${s} ok, groupID:${i} success:${r.length} fail:`+o.length),{code:0,data:{successTopicList:r,failureTopicList:o}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},Op=new class{constructor(){this._name="GetTopicHandler",this._getCloudConfig=e=>{var t=this._core["store"];return(t.get("cloudConfig")||{})[e]}}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getTopicList",context:this})}getTopicList(e){return h(this,void 0,void 0,function*(){var{groupID:t,topicIDList:s=[]}=e,r=0===s.length;if(this._isFetchingFromCache(t,r)){let e=Ip.getTopicList(t,s);if(r||e.length===s.length)return console.log(this._name+`.getTopicList groupID:${t} from cache, count:`+e.length),{code:0,data:{successTopicList:e,failureTopicList:[]}}}return this._getTopicListFromServer({groupID:t,topicIDList:s},r)})}_isFetchingFromCache(e,t){var{hasFetchedAllTopics:e=!1,time:s=0}=Ip.getTopicRequestInfo(e);return!(!e&&(t||e))&&Date.now()-s<this._getCacheDuration()}_getCacheDuration(){var{isUndefined:e}=this._core["utils"];let t=this._getCloudConfig("topic_cache_time");return!e(t)&&(t=parseInt(t,10))>=hp&&t<=_p?1e3*t:1e3*pp}_getTopicListFromServer(u,c){return h(this,void 0,void 0,function*(){var r="_getTopicListFromServer",{isEmpty:o}=this._core["utils"],l=u["groupID"];try{let e=yield function(s,r){return h(this,void 0,void 0,function*(){var{groupID:e,topicIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.get_topic",data:{GroupId:e,TopicIdList:t,MemberInfoFilter:["NoUnreadSeqList"]}})})}(u,this._core),{TopicAndSelfInfo:t=[]}=e||{},n=[],i=[],a=[],s=(this._convertTopicInfoList(t).forEach(e=>{var{topic:e,selfInfo:t,code:s,message:r}=e,o=e["topicID"];0===s?(n.push(Object.assign(Object.assign({},e),{selfInfo:t})),i.push(o)):a.push({topicID:o,code:s,message:r})}),Ip.updateTopic(n),Ip.updateTopicAtInfo(n),console.log(`${this._name}.${r} groupID:${l} from remote, success count:${i.length}, fail count:`+a.length),[]);return o(i)||(Ip.setTopicRequestInfo(l,{hasFetchedAllTopics:c,time:Date.now()}),s=Ip.getTopicList(l,i)),{code:0,data:{successTopicList:s,failureTopicList:a}}}catch(e){throw console.error(this._name+`.${r} failed, error:`,e),e}})}_convertTopicInfoList(e){let o=[];return e.forEach(e=>{var{TopicInfo:e={},SelfInfo:t={},ErrorCode:s,ErrorInfo:r}=e;o.push({code:s,message:r,topic:this._convertTopicInfo(e),selfInfo:this._convertSelfInfo(t)})}),o}_convertTopicInfo(e){var t,s,r,o,n,i,a,l,u,c,d,h=this._core["utils"]["isEmpty"];return h(e)?{}:({CreateTime:h,CustomString:e,FaceUrl:t,GroupId:s,LastMsgTime:r,NextMsgSeq:o,Introduction:n,Notification:i,ShutUpAllFlag:a,TopicId:l,TopicName:u,LastMsg:c,AtInfoList:d}=e,{createTime:h,customData:e,avatar:t,groupID:s,lastMessageTime:r,nextMessageSeq:o,introduction:n,notification:i,muteAllMembers:a,topicID:l,topicName:u,lastMsg:this._convertLastMsg(c),groupAtInfoList:this._convertAtInfoList({groupID:s,topicID:l,atInfoList:d})})}_convertLastMsg(e){var t,{utils:{isUndefined:s},OuterConstant:r}=this._core;if(!s(e))return 4===e.Event&&(e.MsgBody.MsgType=r.MSG_GRP_TIP),{messageHelper:s}=this._core["message"],r=s.parseServerGroupMessage(e),{From_AccountHeadurl:s,From_AccountNick:e,LastMsgSeq:t}=e,Object.assign(Object.assign({},r),{avatar:s,nick:e,sequence:t})}_convertAtInfoList(e){let{groupID:r,topicID:o,atInfoList:t=[]}=e;if(0===t.length)return[];let n=[];return t.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:r,topicID:o,groupAtType:e,sequence:t,from:s})}),n}_convertSelfInfo(e){var t,s,r,o=this._core["utils"]["isEmpty"];return o(e)?{}:({InheritGroupReceiveOption:o,MsgFlag:e,MsgSeq:t,NoUnreadSeqList:s,ShutUpTime:r}=e,{inheritGroupReceiveOption:o,messageRemindType:e,readedSequence:t,excludedUnreadSequenceList:s,muteTime:r})}},Dp=new class{constructor(){this._name="UpdateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(n){return h(this,void 0,void 0,function*(){var t="updateTopicProfile",{isUndefined:e}=this._core["utils"],{groupID:s,topicID:r,muteAllMembers:o}=n;e(n.muteAllMembers)||(n.muteAllMembers=!0===o?"On":"Off");try{return yield function(l,u){return h(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:o,introduction:n,customData:i,muteAllMembers:a}=l;return u.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:o,Introduction:n,CustomString:i,ShutUpAllMember:a}})})}(n,this._core),console.log(this._name+`.${t} ok, topicID:`+r),Ip.updateTopic([n]),{code:0,data:{topic:Ip.getTopic(s,r)}}}catch(e){throw console.error(this._name+`.${t} failed, topicID:${r} error:`,e),e}})}},Rp=new class{constructor(){this._name="MessageReadHandler"}init(e){let{helper:t,common:{isTopic:s}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>s(e[0].conversationID)})}setMessageRead(n){return h(this,void 0,void 0,function*(){var e=this._core["utils"]["isEmpty"],t=n["conversationID"],s={code:0,data:{}},t=Sp(t),r=Ep(t),o=Ip.getTopic(r,t);return console.log(this._name+`.setMessageRead topicID:${t} unreadCount:`+((null==o?void 0:o.unreadCount)||0)),o&&(e(o.groupAtInfoList)||this._deleteTopicAtTips(r,t),0!==o.unreadCount&&(e=this._getLocalMessageMaxSequence(o),yield this._setTopicMessageRead(r,t,e))),s})}_deleteTopicAtTips(n,i){return h(this,void 0,void 0,function*(){console.log(this._name+`._deleteTopicAtTips groupID:${n} topicID:`+i);let e=Ip.getTopic(n,i);if(e){var r=(null==e?void 0:e.groupAtInfoList)||[];if(0!==r.length)try{let{common:{getCurrentUserID:t},OuterConstant:{CONV_AT_ALL:s}}=this._core;var o=[...r];0===(o=r.filter(e=>!e.atTypeArray.includes(s))).length?Ip.clearGroupAtInfoList(n,i):(yield function(t,s){return h(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:o.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteTopicAtTips ok. count:"+r.length),Ip.clearGroupAtInfoList(n,i))}catch(e){console.error(this._name+"._deleteTopicAtTips fail:",e)}}})}_getLocalMessageMaxSequence(e){var{message:{messageDataHandler:t},OuterConstant:{CONV_GROUP:s}}=this._core,r=e["topicID"],t=t.getLocalMessageList(""+s+r),s=Math.max(...t.map(e=>e.sequence));let o=(null==(r=null==e?void 0:e.lastMessage)?void 0:r.lastSequence)||0;return s>o&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${o} to `+s),o=s),o}_setTopicMessageRead(e,t,s){return h(this,void 0,void 0,function*(){try{yield function(r,o){return h(this,void 0,void 0,function*(){var{groupID:e,topicID:t,lastMessageSequence:s}=r;return o.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.msg_read_report",data:{GroupId:e,TopicId:t,MsgReadedSeq:s}})})}({groupID:e,topicID:t,lastMessageSequence:s},this._core),console.log(this._name+"._setTopicMessageRead ok, lastReadSequence:"+s),Ip.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),Ip.markMessageAsRead(t,s),Ip.updateUnreadCount(e,t)}catch(e){throw console.error(this._name+"._setTopicMessageRead fail:",e),e}})}},Lp=new class{init(e){console.log("TopicAction.init"),yp.init(e),Tp.init(e),Ap.init(e),Op.init(e),Dp.init(e),Rp.init(e)}};let Np={required:!0,rules:["string"],allowEmpty:!1},bp={createTopicInCommunity:{groupID:Np,topicName:Np},deleteTopicFromCommunity:{groupID:Np,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:Np,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:Np,topicID:Np}},Gp={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0};var Fp,wp=new class{install(e){ip.init(e),Ip.init(e),Cp.init(e),Mp.init(e),Lp.init(e),e.helper.registerValidateConfig({auth:Gp,params:bp})}};function Pp(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Up="qualityStat",kp="im-ssolog-quality-stat",$p=(!function(e){e[e.ONLINE=8]="ONLINE"}(Fp=Fp||{}),"networkRTT"),qp="messageE2EDelay",xp="sendMessageC2C",Vp="sendMessageGroup",Bp="sendMessageGroupAV",jp="sendMessageRichMedia",Kp="cosUpload",Wp="messageReceivedGroup",Hp="messageReceivedGroupAVPush",Yp="messageReceivedGroupAVPull",zp={[$p]:2,[qp]:3,[xp]:4,[Vp]:5,[Bp]:6,[jp]:7,[Wp]:8,[Hp]:9,[Yp]:10,[Kp]:11},Jp=[xp,Vp,Bp,jp,Kp],Qp=[Wp,Hp,Yp],Xp=[$p,qp,xp,Vp,Bp,jp,Kp,Wp,Hp,Yp],Zp={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},eh="quality_stat";var th=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(Zp))}init(e){this._core=e,Object.values(Jp).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,o=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case o.TOTAL_COUNT:this._handleTotalCount(t);break;case o.SUCCESS_COUNT:this._handleSuccessCount(t);break;case o.FAILED_COUNT:this._handleFailedCount(t,s);break;case o.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,o,n,i=this._messageStatsMap.get(e);return i&&0!==i.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:o}=i,r=Pp(s/t*100,2),n=Pp((o=s+o)/t*100,2),i=this._calcAverageValue(i,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:o,percent_platform:n,average_value:i}):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:o,CONV_C2C:n,CONV_GROUP:i,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,o].includes(s.type))return jp;if(s.conversationType===n)return xp;if(s.conversationType===i){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?Bp:Vp}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Kp?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)}},sh=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(Up+".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,o=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(o+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:o,percent_business:Pp(o/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(Qp).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?Yp:Wp):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 o=Math.floor((s+r)/2);if(e[o]===t)return o;e[o]<t?s=o+1:r=o-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))}},oh=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"],o=[s,r];t.forEach(e=>{!o.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Pp(this._totalDelay/e,1)}_calculatePercentage(e,t){return Pp(e/t*100,2)}},nh=new class{init(e){this.core=e}},ih=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:o,DESTROY:n},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:a}}=this._core=e;nh.init(e),th.init(e),sh.init(e),oh.init(e),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(o,this._reset,this),s.subscribeInnerEvent(n,this._dispose,this)}handleLoginSuccess(){console.log(Up+".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:eh,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...Xp.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&&th.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:zp[e],timestamp:Date.now(),network_type:Fp.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case qp:return oh.getStatResult();case xp:case Vp:case Bp:case jp:case Kp:return th.getStatResult(e);case Wp:case Hp:case Yp:return sh.getStatResult(e);default:return null}}_uploadQualityReports(t){return h(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=nh.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=Up+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(kp)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(kp,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(eh)}_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(),oh.dispose(),sh.dispose()}};let rh=ls.STANDARD,ah=[],ch=[ro,function(e){Zs.install(e),no.install(e),io.install(e)},lo,So,Mo,ih,ri,ur,zr,Su,Zu,Cd,Qo,Vl,od,np,wp];rh=ls.PROFESSIONAL,ah=ch;var Eh,Ch,Mh,qh,xh,Vh,Wh,uh=Object.freeze({__proto__:null,ChatError:Ss,buildAndSendPacket:qs,get builtInPlugins(){return ah},checkBusinessCapabilityBits:Gs,deepMerge:Ws,getCurrentUserID:js,getErrorMessage:Is,getMessagePreviewText:Hs,isC2CConv:e=>g(e)&&e.slice(0,3)===ss.CONV_C2C,isCommunity:Us,isGroupConv:e=>g(e)&&e.slice(0,5)===ss.CONV_GROUP,isTopic:ks,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=xt.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:ws,registerInterceptor:Ls,registerValidateConfig:Ns,requireAuth:Es,get sdkEdition(){return rh},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:o,CONV_AT_ALL_AT_ME:n}=cs;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:o}=cs,{groupID:n,sequence:i}=t,a=!1;return Us({groupID:n})&&e.forEach(e=>{e.messageSequence===i&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[o]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[o],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(o)&&(e=[n]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:Rs,validateParameters:ys,workflowManager:Ps}),lh=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:o}=s,n=this._conversationMap.get(e);n&&!me(t)&&(Object.keys(t).forEach(e=>{n[e]=t[e]}),r)&&xt.notificationCenter.emitInnerEvent(Wt.CONVERSATION_UPDATED,{needSort:o})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),xt.notificationCenter.emitInnerEvent(Wt.CONVERSATION_UPDATED))}},dh=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&&!me(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},ph=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:o,updateUnreadCount:n=!0}=e,i=p(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(i).forEach(e=>{t[e]=i[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(o,{conversationID:s,messageList:a,updateUnreadCount:n}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];ks(s)?xt.notificationCenter.emitInnerEvent(Zt[e],t):xt.notificationCenter.emitInnerEvent(e,t)}},hh=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)}},_h=Object.freeze({__proto__:null,conversationStore:lh,groupStore:dh,messageStore:ph,userStore:hh});let gh={on:xt.notificationCenter.subscribeOuterEvent.bind(xt.notificationCenter),off:xt.notificationCenter.unSubscribeOuterEvent.bind(xt.notificationCenter),destroy:function(){return h(this,void 0,void 0,function*(){var e,t;try{null!=(e=xt.store.get("login"))&&e.isLogin&&(yield gh.logout()),xt.notificationCenter.emitInnerEvent(Wt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{xt.notificationCenter.emitOuterEvent(jt.SDK_DESTROY,{SDKAppID:null==(t=xt.store.get("instance"))?void 0:t.sdkAppId}),ws.clear(),bs.clear(),Ps.destroy(),xt.destroy()}})},callExperimentalAPI:function(e,t){return mh[e]?mh[e](t):Promise.reject(new Error(`API ${e} is not found`))},use:bs.installExternalPlugin.bind(bs),registerPlugin:function(e){console.log("registerPlugin",e)},setLogLevel:function(e){console.log("setLogLevel",e),!xt||"function"!=typeof xt.setLogLevel||null!=xt&&xt.setLogLevel(e)}},mh={},vh={};function fh(e){let{apiName:r,context:t,methodName:o=r,matcher:s}=e;vh[r]||(vh[r]=[]),vh[r].push({context:t,methodName:o,matcher:s}),gh[r]&&1!==vh[r].length||(gh[r]=(...t)=>{Rs(o,t);var s=vh[r];for(let e of s)if(!e.matcher||e.matcher(t))return e.context[e.methodName].bind(e.context)(...t)})}function Ih(e,t,s){s=s||e;mh[e]=t[s].bind(t)}function Sh(){return Object.assign(Object.assign({InnerEvent:Wt,InnerEventSubType:xt.notificationCenter.InnerEventSubType,OuterEvent:jt,OuterConstant:cs,SignalingEvent:Ht,helper:Object.assign(Object.assign(Object.assign({},xt.utils),xt.common),{registerApi:fh,registerExperimentalAPI:Ih,registerInterceptor:Ls,registerValidateConfig:Ns,checkBusinessCapabilityBits:Gs,registerWorkflowStep:Ps.registerWorkflowStep.bind(Ps),ChatError:Ss}),apiMap:gh},xt),{constants:Object.assign(Object.assign({},fs),xt.constants),common:Object.assign(Object.assign({},uh),xt.common),utils:xt.utils,appStore:_h})}mh.statTUIKeyFeatures=function(e){console.log("statTUIKeyFeatures",e)},function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Eh=Eh||{}),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Ch=Ch||{}),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(Mh=Mh||{});let yh={[Ch.multipleAccount]:"multipleAccount",[Ch.multipleDevice]:"multipleDevice",[Ch.restApi]:"REST_API_Kick",[Mh.multipleAccount]:"multipleAccount",[Mh.multipleDevice]:"multipleDevice",[Mh.restApi]:"REST_API_Kick",[Mh.usersigExpired]:"userSigExpired"},Th="login_online_presence_task",{ERROR:Ah,DESTROY:Oh,FORCE_OFFLINE:Dh}=Wt,{KICKED_OUT_MULT_ACCOUNT:Rh,KICKED_OUT_MULT_DEVICE:Lh,KICKED_OUT_REST_API:Nh,ACCOUNT_A2KEY_EXPIRED:bh,MSG_A2KEY_EXPIRED:Gh}=us;class wh{init(){var e=xt["notificationCenter"];e.subscribeInnerEvent(Dh,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Ah,Gh,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ah,bh,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ah,Rh,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ah,Lh,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ah,Nh,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Oh,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 h(this,void 0,void 0,function*(){var e=t["kickedOutReasonCode"];try{yield xt.login.loginAction.logout(Eh.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(t),xt.notificationCenter.emitOuterEvent(jt.KICKED_OUT,{data:{type:yh[e]},name:jt.KICKED_OUT}),[Ch.restApi,bh,Gh].includes(e)&&xt.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,s=xt.ssoLog.createSSOLogData({method:"kickedOut"}),e=`type:${yh[e]} newInstanceInfo: `+JSON.stringify(t);s.setLogInfo({message:e}).end(!0),console.warn("loginModule."+e)}_isKickedOut(e){return[Ch.multipleAccount,Ch.multipleDevice,Ch.restApi].includes(e)}_dispose(){var e=xt["notificationCenter"];e.unSubscribeInnerEvent(Dh,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Ah,bh,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ah,Gh,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ah,Rh,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ah,Lh,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ah,Nh,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Oh,this._dispose,this)}}function Ph(){return h(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=xt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=""+t.head.seq+e;try{let d=yield xt.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:o,PurchaseBits:n,A2Key:i,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:u,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:o,purchaseBits:n,a2Key:i,authKey:a,errorCode:l,errorInfo:u,actionStatus:c}}}catch(e){throw console.warn(e),e}})}class Uh{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){var{notificationCenter:e,store:t}=xt;t.set("login",{isReady:!1}),fh({apiName:"login",context:this}),fh({apiName:"logout",context:this}),fh({apiName:"getLoginUser",context:this}),fh({apiName:"isReady",context:this}),e.subscribeInnerEvent(Wt.RECONNECTED,this._reLogin,this),xt.notificationCenter.subscribeInnerEvent(Wt.DESTROY,this._dispose,this)}login(s){return h(this,void 0,void 0,function*(){let e=this._getUiPlatform(),t=(xt.store.get("instance")||{})["sdkEdition"],r=xt.ssoLog.createSSOLogData({method:"login",eventType:4,uiPlatform:e,message:t});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Ss({functionName:"login",code:us.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 Ss({functionName:"login",code:t});throw r.setError(s).end(!0),s}finally{this._latestLoginAt=0}})}_getUiPlatform(){var{store:e,utils:{IN_BROWSER:t,isH5:s}}=xt,e=(null==(e=e.get("instance"))?void 0:e.scene)||"";let r=e;return t&&(r=e+"_web",s)&&(r=e+"_h5"),gs[r]}_reLogin(){return h(this,void 0,void 0,function*(){var e,t,s,r,o,n;try{this._isLoginIn()&&(t=xt.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Ph())&&({instanceID:r,customStatus:o}=s,xt.store.set("login",{statusInstanceId:r}),Ps.executeWorkflow(ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:o,statusType:es.USER_STATUS_ONLINE}),n=`socketId:${null==(e=xt.channel.getSocketAdapter())?void 0:e.getId()} instanceId:`+r,t.setLogInfo({message:n}).end(!0))}catch(e){console.warn(e)}})}logout(){return h(this,arguments,void 0,function*(s=Eh.USER_INITIATED){let e=xt.ssoLog.createSSOLogData({method:"logout"});e.setLogInfo({moreMessage:"identifier:"+js()});try{yield this._performLogout(s),e.end(!0),xt.ssoLog.uploadSSOLogData()}catch(s){let e=s["errorCode"],t=new Ss({functionName:"logout",code:e});this._handleLogoutError(t)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?js():""}isReady(){var e;return null==(e=xt.store.get("login"))?void 0:e.isReady}_updateAndEmitSDKReady(){xt.store.set("login",{isReady:!0}),setTimeout(()=>{xt.notificationCenter.emitOuterEvent(jt.SDK_READY,{name:jt.SDK_READY})},1)}_updateAndEmitSDKNotReady(){xt.store.set("login",{isReady:!1}),xt.notificationCenter.emitOuterEvent(jt.SDK_NOT_READY,{name:jt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s="login";if(!e)throw new Ss({functionName:s,message:"login response is empty"});var{tinyID:e,a2Key:r}=e||{},o=xt.ssoLog.getSSOLogData(s);if(!e){let e=new Ss({functionName:s,code:us.NO_TINYID});throw null!=(t=null==o?void 0:o.setError)&&t.call(o,e).end(),e}if(!r){let e=new Ss({functionName:s,code:us.NO_A2KEY});throw null!=(t=null==o?void 0:o.setError)&&t.call(o,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Is({code:"RepeatLogin",replacement1:null==(e=xt.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return h(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return xt.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Ph()})}_ensureAsyncComplete(){return h(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=xt.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:o,purchaseBits:n}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),xt.user.userStatus.setCustomStatus(o),Ps.executeWorkflow(ds.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:n}),xt.common.taskScheduler.addTask({id:Th,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(s){return h(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=xt.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield xt.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutError(e){xt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error("logout "+e)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Ps.reset(),xt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;xt.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_logLoginSuccess(e){var t=xt.ssoLog.getSSOLogData("login"),{helloInterval:e,instanceID:s,timeStamp:r,customStatus:o}=e,n=null==(n=xt.channel.getSocketAdapter())?void 0:n.getId(),i=xt.common.timeManager.getTimeOffsetWithServer(),{appId:a,href:l}=xt.store.get("instance")||{},n=`login._logLoginSuccess socketID:${n} scene: helloInterval:${e} instanceID:${s}
5
+ timeStamp:${r} offset:${i} customStatus:${o} href: ${l} appId: `+a;console.log("login ok. "+n),t.updateLogCreatedAtByTimeOffset(),t.setLogInfo({moreMessage:n}).end()}_sendOnlinePresenceRequest(){return h(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=xt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield xt.channel.sendPacket(t,{requestId:e})}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=xt.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),xt.common.taskScheduler.removeTask(Th),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,xt.store.clear("login"),xt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();var e=xt["notificationCenter"];e.unSubscribeInnerEvent(Wt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(Wt.DESTROY,this._dispose,this)}}let kh={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Fh={logout:!0};class $h{constructor(){this.loginAction=new Uh,this.kickedOutHandler=new wh,this.loginAction.init(),this.kickedOutHandler.init(),Ns({auth:Fh,params:kh})}}!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(qh=qh||{}),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(xh=xh||{}),function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem",e.MSG_IMAGE="TIMImageElem",e.MSG_AUDIO="TIMSoundElem",e.MSG_FILE="TIMFileElem",e.MSG_VIDEO="TIMVideoFileElem",e.MSG_GRP_TIP="TIMGroupTipElem",e.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",e.MSG_MERGER="TIMRelayElem"}(Vh=Vh||{});let Bh={1:xh.MSG_PRIORITY_HIGH,2:xh.MSG_PRIORITY_NORMAL,3:xh.MSG_PRIORITY_LOW,4:xh.MSG_PRIORITY_LOWEST},jh=0,Kh=1,Hh=(!function(e){e.IN="in",e.OUT="out"}(Wh=Wh||{}),{});function Yh(e){var t,s,r;return e?(void 0===Hh[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),Hh[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Hh[e])):Hh[e]+=1,Hh[e]):0}class zh{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=xh.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=xt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:o,needReadReceipt:n,isSupportExtension:i,customModerationConfigurationId:a,to:l,from:u,nick:c="",avatar:d="",time:h,messageControlInfo:p,tinyID:_,cloudCustomData:g="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:S=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:A=Jt.SUCCESS,revokeReason:T="",conversationSubType:D,clientSequence:O,protocol:R="JSON",revokerInfo:L={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:b,groupProfile:G,atUserList:w,flow:P,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||_,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===i||1===i,this._cmConfigID=a,this.to=l,this.nick=c,this.avatar=d,this.protocol=R,this.random=void 0===b?(t=t||99999999,Math.round(Math.random()*t)):b,this.time=h||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==p||!p.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==p||!p.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=g,this.messageLifeTime=m,this.from=u||null,this.sequence=I||0,this.conversationType=f||qh.CONV_C2C,this.hasRiskContent=1<S,this.version=v,this.isPlaceMessage=E,this.isRevoked=2===E||8===C,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=T,this.revokerInfo=L,this._receiverList=M,this.conversationSubType=D,this.revoker=(null==L?void 0:L.revoker)||"",this.clientSequence=O||I||0,this.status=A,this.atUserList=w||[],this.flow=P,this.isRead=U,this.reInitialize(o),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===qh.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!==qh.CONV_SYSTEM?(e=t!==qh.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=qh.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Yh(e)),0===this.sequence&&this.conversationType===qh.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===qh.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class Jh{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new Jh({data:e,description:s,extension:t})}constructor(e){this.type=Vh.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=xt.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 Qh{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new Qh({text:e})}constructor(e){this.type=zt.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 Xh{constructor(){this._elementClassMap={[Vh.MSG_CUSTOM]:Jh,[Vh.MSG_TEXT]:Qh}}init(){fh({apiName:"createCustomMessage",context:this}),fh({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=Wh.OUT}=e,r=(xt.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=Wh.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new zh(t)}createCustomMessage(t){let e=js(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[Vh.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 Qh({text:t}),s=js(),(e=xt.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:o}=xt.store.get("login")||{},n=hh.getUserProfile(r);return e.nick=t||(null==n?void 0:n.nick)||"",e.avatar=s||(null==n?void 0:n.avatar)||"",e.tinyID=e.tinyID||o||"",e.from=r,e.status=Jt.UNSENT,e.flow=Wh.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Wh.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Wh.OUT}}let Zh={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}},e_={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},t_={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function s_(r,o){return Object.keys(o).forEach(e=>{var{range:t,defaultValue:s}=o[e];r[e]=t.includes(r[e])?r[e]:s}),r}function o_(e){var t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function n_(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,e=s_(e,e_),{sound:s="",FCMChannelID:r=""}=e,e=p(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:o_(s),OPPOChannelID:t,GoogleChannelID:r})}function i_(e){var{apnsInfo:e={},ignoreIOSBadge:t=!1,disableVoipPush:s}=e,e=s_(e,t_),{ignoreIOSBadge:r,disableVoipPush:o,enableIOSBackgroundNotification:n}=e,e=p(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),r=!0===r||!0===t?1:0;let i;return _(s)||(i=!1===s?1:0),_(o)||(i=!1===o?1:0),Object.assign(Object.assign({},e),{BadgeMode:r,IsVoipPush:i,ContentAvailable:n?1:0})}function r_(e){return xt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:i_(e),AndroidInfo:n_(e)}:Zh}function a_(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:o,IsSyncMsg:n,MsgBody:i,MsgClientTime:a,MsgLifeTime:l,MsgRandom:u,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:p,TinyId:_,MsgCheckResult:g,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,S,{From_Account:E,To_Account:C}=e;if(1===n){let e=C;C=E,E=e}if(I){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;S={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:E,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:n,clientTime:a,messageLifeTime:l,random:u,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:p,to:C,tinyID:_,checkResult:g,cloudCustomData:m,revokerInfo:S,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:o,elements:d_(i)}}function c_(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:o,MsgTimeStamp:n,To_Account:i,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:o,time:n,to:i,elements:d_(t),messageVersion:a,cloudCustomData:l}}function u_(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:o,MsgClientTime:n,MsgRandom:i,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,TinyId:d,CloudCustomData:h,MsgVersion:p,MsgCheckResult:_,NeedReadReceipt:g,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,S=xh.MSG_PRIORITY_NORMAL;if(Object.keys(Bh).includes(String(e.MsgPriority))&&(S=Bh[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}var E=function(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{e.GroupAtAllFlag===jh?t.push(e.GroupAt_Account):e.GroupAtAllFlag===Kh&&t.push(cs.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:n,priority:S,random:i,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:p,messageCheckResult:_,needReadReceipt:g,isPlaceMessage:m,revokerInfo:I,atUserList:E,elements:d_(o),to:l_(e)}}function l_(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=xt,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:o}={}}=e;return r!==s||t(o)?e:o}function d_(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=xt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=xt.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function p_(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:o,MsgTimeStamp:n,GroupId:i,TopicId:a,MsgVersion:l,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:o,time:n,groupID:i,topicID:a,elements:d_(t),messageVersion:l,cloudCustomData:u}}function h_({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:o,flow:n,_isExcludedFromUnreadCount:i,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!i&&n===Wh.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:o,unreadCount:t?1:0,lastMessage:a})}var __=Object.freeze({__proto__:null,autoIncrementIndex:Yh,parseServerGroupMessage:u_,parseServerPushC2CModifyMessage:c_,parseServerPushGroupModifyMessage:p_,parseServerPushMessage:a_,parseServerPushMessageElement:d_,updateConversationFields:h_});let g_=xt.utils["isPlainObject"];function m_(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,o=t["offlinePushInfo"],n=(e.conversationType===qh.CONV_C2C&&!0===s&&(o?o.disablePush=!0:o={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(n=e.cloudCustomData);var i=[];if(r&&g_(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&i.push("NoUnread"),!0===t&&i.push("NoLastMsg"),!0===s&&i.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:n,messageControlInfo:i,offlinePushInfo:o}}function v_(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 f_(t,s){return h(this,void 0,void 0,function*(){var e=yield qs((t.conversationType===qh.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:o,messageControlInfo:n,offlinePushInfo:i}=m_(e,t),a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let l;return v(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=xt.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:a,CloudCustomData:o,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:r_(i),SendMsgControl:r?void 0:n,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:v_(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:o,messageControlInfo:n,offlinePushInfo:i}=m_(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=xt.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:o,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?n:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:r_(i),forbidCallbackControl:v_(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let I_=xt.utils["isPlainObject"],{MSG_AUDIO:S_,MSG_FILE:E_,MSG_IMAGE:C_,MSG_VIDEO:M_,MSG_MERGER:y_}=cs;class T_{init(){fh({apiName:"sendMessage",context:this,matcher:e=>![S_,E_,C_,M_,y_].includes(e[0].type)})}sendMessage(c,t){return h(this,void 0,void 0,function*(){let r=xt.ssoLog.createSSOLogData({method:"sendMessage"}),{TOTAL_COUNT:e,SEND_COST:i,SUCCESS_COUNT:a,FAILED_COUNT:n}=vs;if(!(c instanceof zh)){let e=new Ss({code:us.MSG_INSTANCE_REQUIRED});throw r.setError(e).end(),e}let o=c.validateBeforeSend();if(!o.isValid){let{code:e,message:t=""}=o.error||{},s=new Ss({code:e,message:t});throw r.setError(s).end(),s}this._reportMessageSendQuality({name:e,message:c});let l=!1;var u=(xt.message||{})["messageDataHandler"];try{let r=(t||{})["messageControlInfo"],o=null,n=(u.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===qh.CONV_C2C?(l=!0===(null==t?void 0:t.onlineUserOnly),o=yield f_(c,t)):c.conversationType===qh.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),o=yield f_(c,t)),o){let{messageDropReason:e,sequence:t,time:s}=o;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:i,message:c,startTs:n}),!0===c.isResend){let e=u.findMessage(c.ID);e&&(console.log("sendMessage resend ok. ID:"+e.ID),u.deleteConversationMessage(e))}return c.status=Jt.SUCCESS,c.time=s,c.conversationType===qh.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=Jt.FAIL,u.removeRandomOfSentMessage(c.random);let{errorCode:t,errorMessage:s="",errorInfo:r=s}=e||{},o=(this._hasRiskContent(t)&&(c.hasRiskContent=!0),l||this._isRejectedByRestApi(t)||u.storeConversationMessage(c),this._reportMessageSendQuality({name:n,message:c,error:e}),new Ss({code:t,message:r,data:{message:c}}));throw this._logSendMessageError({message:c,error:o}),o}})}_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=xt.ssoLog.createSSOLogData({method:"sendMessage"});let r=`head.seq: type:${e.type} from:${e.from} to:`+e.to;if(xt.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,o=ks(s)?Wt.TOPIC_NEW_MESSAGE:Wt.NEW_MESSAGE;xt.notificationCenter.emitInnerEvent(o,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&I_(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t){var s=xt.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=(xt.message||{})["messageDataHandler"];let s=!1;var r,o=e["conversationID"],n=t.getLatestMsgSentByMe(o);n&&({nick:n,avatar:r}=n,s=n!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:o,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(o){return h(this,void 0,void 0,function*(){var{to:t,from:s}=o;let r=t,e=dh.getGroup(r);if(Us({groupID:r})&&null!=e&&e.isSupportTopic)throw new Ss({code:us.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(ks(t)&&([r]=t.split(rs.TOPIC),e=dh.getGroup(r)),!e&&"function"==typeof(null==gh?void 0:gh.getGroupProfile)){let e=yield gh.getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===cs.GRP_AVCHATROOM){let e=Is({code:us.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new Ss({code:us.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){xt.notificationCenter.emitInnerEvent(Wt.QUALITY_STAT,{label:ms.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class A_{constructor(e){this.value=e,this.next=null}}class O_{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new A_(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 D_{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new O_(100),xt.notificationCenter.subscribeInnerEvent(Wt.LOGOUT,this._reset,this),xt.notificationCenter.subscribeInnerEvent(Wt.DESTROY,this._dispose,this)}get _messagesByConversation(){return ph.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),i=this._getMessageFromLocalMessage(a,e);if(i){let{messageVersion:s,elements:r,cloudCustomData:o,checkResult:e=0}=t,n=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${i.version} remoteVersion:`+s),i.version<s){let e=this._getUniqueIdOfMessage(i),t=ve(r);return null!=(l=this._messagesByConversation.get(a))&&l.has(e)?ph.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:o,hasRiskContent:n,operation:Qt.modify}):(i.version=s,i._elements=t,i.payload=i._elements[0].content,i.type=i._elements[0].type,i.cloudCustomData=o,i.isModified=!0,i.hasRiskContent=n),{isUpdated:!0,message:i}}return{isUpdated:!1,message:i}}}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 o of e)if(s=o.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:o}){let e=this._messagesByConversation.get(t),n=null;if(e){var i=Array.from(e.values());if(n=this._findMessageBySequenceAndRandom({messageList:i,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(n);return ph.updateMessage(t,[e],{isRevoked:!0,revoker:o,operation:Qt.revoke}),n}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(n=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return n.isRevoked=!0,n.revoker=o,n}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:r}){for(let e=0;e<t.length;e+=1){var o=t[e];if(o.sequence===s&&(_(r)||o.random===r))return o}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],o=[],n=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);n.has(e)||(r.push(t),o.push([e,t]))}if(0<o.length){let e=new Map([...o,...n.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var o=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];o.has(e.ID)||o.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:o}=e;return e+`-${t}-${s}-${r}-`+o}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:n,latestNick:i,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),o=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===o&&(t!==i&&(e.nick=i),s!==n)&&(e.avatar=n)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),xt.notificationCenter.unSubscribeInnerEvent(Wt.LOGOUT,this._reset,this),xt.notificationCenter.unSubscribeInnerEvent(Wt.DESTROY,this._dispose,this)}}function R_(e,t){var s,r,o,n,i,a,l,u=lh.getConversation(e);null!=u&&u.lastMessage&&(u=u["lastMessage"],{lastTime:s,lastSequence:r,version:o}=u,{time:t,sequence:n,messageVersion:i,elements:a,cloudCustomData:l}=t,s===t)&&r===n&&o!==i&&(u.type=a[0].type,u.payload=a[0].content,u.messageForShow=Hs(u.type,u.payload),u.cloudCustomData=l,u.version=i,lh.updateConversation(e,{lastMessage:u}))}class L_{init(){fh({apiName:"modifyMessage",context:this})}modifyMessage(c){return h(this,void 0,void 0,function*(){let r=xt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:o,payload:e,sequence:n,conversationType:i,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:"+o}),i===qh.CONV_C2C?t=yield function(c){return h(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:o,time:n,type:i,cloudCustomData:a}=c,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:o,MsgTime:n,MsgType:i,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},u=yield qs({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:d_(e),messageVersion:t,cloudCustomData:s}}})}(c):i===qh.CONV_GROUP&&(t=yield function(i){return h(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=i,o={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:i.transformElementsToServerFormat(),CloudCustomData:r},n=yield qs({servcmd:"openim.modify_group_msg",data:o});if(n){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=n;return{elements:d_(e),messageVersion:t,cloudCustomData:s}}})}(c)),t){r.end();let e=""+i+o;return o===js()&&i===qh.CONV_C2C&&(e=""+i+u),s={conversationType:i,from:u,to:o,time:l,random:a,sequence:n,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:c}}}}catch(e){let t=(e||{})["errorCode"],s=new Ss({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}else r.setLogInfo({message:"can not modify message element. message type: "+t}).end()})}_logModifyMessageError(e){xt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=xt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&xt.notificationCenter.emitOuterEvent(jt.MESSAGE_MODIFIED,{name:jt.MESSAGE_MODIFIED,data:[r]}),xt.notificationCenter.emitInnerEvent(Wt.MESSAGE_MODIFIED,{conversationID:t,message:r}),R_(t,e)}_canModifyMessageElement(e){return[Vh.MSG_TEXT,Vh.MSG_CUSTOM,Vh.MSG_LOCATION,Vh.MSG_FACE].includes(e)}}class N_{init(){var e=xt["notificationCenter"],t=e["InnerEventSubType"];Ps.registerWorkflowStep(ds.RECEIVE_C2C_NEW_MESSAGE,ps.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Ps.registerWorkflowStep(ds.RECEIVE_C2C_NEW_MESSAGE,ps.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Ps.registerWorkflowStep(ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,ps.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(Wt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Wt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(Wt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){Ps.executeWorkflow(ds.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(xt.message||{})["messageDataHandler"],r=[],o=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)&&h_({conversationUpdateFields:o,message:e}),s.isMessageSentByCurrentInstance(e)&&!t)||r.push(e)}),{conversationUpdateFieldList:[...o.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[ps.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[ps.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&&xt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&xt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=qh.CONV_C2C,e=a_(e),t=xt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Wh.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(r){var e;let o=(xt.message||{})["messageDataHandler"],t=null==(e=xt.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:i,conversationID:a=""}=r;if(s!==t){let s=o.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;_(n)||_(i)?(r.nick=g(e)?e:r.nick,r.avatar=g(t)?t:r.avatar):n===e&&i===t||(o.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:i,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:n,avatar:i}))}}else{let e=o.getLatestMsgSentByMe(a);!e||n===e.nick&&i===e.avatar||o.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:i,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=lh.getConversation(e)||{};r.avatar===s&&r.nick===t||lh.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=xt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&xt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),xt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),R_(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=qh.CONV_C2C,e=c_(e),{to:s,from:r}=e;let o=""+t+s;s===(null==(s=xt.store.get("login"))?void 0:s.userId)&&(o=""+t+r),e=Object.assign({conversationType:t,conversationID:o},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=xt["notificationCenter"],e=e["InnerEventSubType"];xt.notificationCenter.unSubscribeInnerEvent(Wt.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),xt.notificationCenter.unSubscribeInnerEvent(Wt.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),xt.notificationCenter.unSubscribeInnerEvent(Wt.DESTROY,this._dispose,this)}}class b_{init(){var e=xt["notificationCenter"],t=e["InnerEventSubType"];Ps.registerWorkflowStep(ds.RECEIVE_GROUP_NEW_MESSAGE,ps.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Ps.registerWorkflowStep(ds.RECEIVE_GROUP_NEW_MESSAGE,ps.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(Wt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Wt.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(Wt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&Ps.executeWorkflow(ds.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=xt.message["messageDataHandler"],r=[],o=new Map,n=null==t?void 0:t.GroupMsgArray;return null!=n&&n.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):s.isInMessageList(e)||s.storeConversationMessage(e)&&(r.push(e),h_({conversationUpdateFields:o,message:e})))}),{conversationUpdateFieldList:[...o.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[ps.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&xt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&xt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=qh.CONV_GROUP,e=u_(e),t=xt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Wh.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(e){var t=(xt.message||{})["messageDataHandler"],{from:e,nick:s,avatar:r,conversationID:o=""}=e;if(e===(null==(e=xt.store.get("login"))?void 0:e.userId)){let e=t.getLatestMsgSentByMe(o);!e||s===e.nick&&r===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:o,latestNick:s,latestAvatar:r,isSentByMe:!0})}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=xt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&xt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),R_(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=qh.CONV_GROUP,{topicID:s,groupID:r}=e=p_(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=xt["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(Wt.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(Wt.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(Wt.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===is.GRP_AVCHATROOM;return!(!dh.getGroup(e)&&t)}}class G_{constructor(){this.c2cMessageReceiver=new N_,this.groupMessageReceiver=new b_}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}let w_={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."}}}},P_={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class U_{constructor(){this.messageHelper=__,this.messageFactory=new Xh,this.messageSender=new T_,this.messageAction=new L_,this.messageReceiver=new G_,this.messageDataHandler=new D_,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),Ns({auth:P_,params:w_})}}let k_="User",F_="Tag_Profile_IM_",$_=100,q_={NICK:F_+"Nick",GENDER:F_+"Gender",BIRTHDAY:F_+"BirthDay",LOCATION:F_+"Location",SELFSIGNATURE:F_+"SelfSignature",ALLOWTYPE:F_+"AllowType",LANGUAGE:F_+"Language",AVATAR:F_+"Image",MESSAGESETTINGS:F_+"MsgSettings",ADMINFORBIDTYPE:F_+"AdminForbidType",LEVEL:F_+"Level",ROLE:F_+"Role"},x_="USER_STATUS",V_=1,B_={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:[]},j_=new Map([[q_.NICK,"nick"],[q_.GENDER,"gender"],[q_.BIRTHDAY,"birthday"],[q_.LOCATION,"location"],[q_.SELFSIGNATURE,"selfSignature"],[q_.ALLOWTYPE,"allowType"],[q_.LANGUAGE,"language"],[q_.AVATAR,"avatar"],[q_.MESSAGESETTINGS,"messageSettings"],[q_.ADMINFORBIDTYPE,"adminForbidType"],[q_.LEVEL,"level"],[q_.ROLE,"role"]]);var K_=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}):j_.has(e)&&(s[j_.get(e)]=t)}),Object.assign(Object.assign({},B_),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:q_[e.toUpperCase()],value:t[e]})}),s}normalizeProfileFields(e){let r={};return e.forEach(e=>{var{tag:t,value:s}=e;if(j_.has(t)){let e=j_.get(t);r[e]=s}}),r}};let W_=xt.common["generateProtocolData"];function H_(r){return h(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:js(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var n=W_({servcmd:e,data:t}),s=n.head.seq+e,n=yield xt.channel.sendPacket(n,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:o}=n,i=[];return o.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:o,ProfileItem:n}=e,n=K_.parseProfileItem(n);i.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:o,profileItem:n})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:i}}})}function Y_(e){return hh.getFriendMap().has(e)}let z_=xt.utils["isEmpty"];class J_{init(){fh({apiName:"getMyProfile",context:this}),fh({apiName:"getUserProfile",context:this}),fh({apiName:"updateMyProfile",context:this}),this.createProfile=K_.createProfile.bind(K_);var e=xt["notificationCenter"];Ps.registerWorkflowStep(ds.SYNC_SERVER_INFO_AFTER_LOGIN,ps.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(Wt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(Wt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Wt.DESTROY,this._dispose,this)}getMyProfile(){return h(this,void 0,void 0,function*(){let t=xt.ssoLog.createSSOLogData({method:"getMyProfile"});try{var s=js(),r=yield H_([s]);if(r){let e=this._handleProfileFormResponse(r)[0];return hh.getUserProfileMap().set(s,e),{code:0,data:e}}t.end()}catch(e){var{errorCode:r,errorInfo:s}=e,r=new Ss({functionName:"getMyProfile",code:r,message:s});throw t.setError(r).end(),e}})}getUserProfile(l){return h(this,void 0,void 0,function*(){var o=xt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let e=l["userIDList"],{userIdListToRequest:t,userIdListToCache:s}=(e.length>$_&&(e=e.slice(0,$_)),this._filterRequestAndCacheUsers(e)),r=[];s.forEach(e=>{e=hh.getUserProfile(e);r.push(e)});var n="userIDList.length:"+e.length;if(0===t.length)return o.setLogInfo({message:n}).end(),{code:0,data:r};var i=yield H_(t);if(i){let e=this._handleProfileFormResponse(i);e.forEach(e=>{Y_(e.userID)&&hh.getUserProfileMap().set(e.userID,e)});var a=e.concat(r);return o.setLogInfo({message:n}).end(),{code:0,data:a}}}catch(e){i=e["errorCode"],n=new Ss({functionName:"getUserProfile",code:i});throw o.setError(n).end(),n}})}getMyProfileCacheThenServer(){return h(this,void 0,void 0,function*(){var e=js(),e=hh.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return h(this,void 0,void 0,function*(){let o=xt.ssoLog.createSSOLogData({method:"updateMyProfile"}),t=js(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);let r=K_.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};o.setLogInfo({message:JSON.stringify(r)}),yield function(r){return h(this,void 0,void 0,function*(){let e="profile.portrait_set",t=W_({servcmd:e,data:r}),s=""+t.head.seq+e,o=yield xt.channel.sendPacket(t,{requestId:s});if(o){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=o;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var n=hh.getUserProfile(t),i=n?Object.assign(Object.assign({},n),s):K_.createProfile(t,r);return Ms(n,i,["lastUpdatedTime","profileCustomField"])||xt.notificationCenter.emitOuterEvent(jt.PROFILE_UPDATED,{name:jt.PROFILE_UPDATED,data:[i]}),i.lastUpdatedTime=Date.now(),hh.getUserProfileMap().set(t,i),o.end(),{code:0,data:i}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new Ss({functionName:"updateMyProfile",code:t,message:s});throw o.setError(r).end(),r}})}updateMyNickAndAvatar(o){return h(this,void 0,void 0,function*(){var e=js(),t=Date.now(),s=hh.getUserProfile(e),r={};(r=s?Object.assign(s,o):K_.createProfile(e,o)).lastUpdatedTime=t,hh.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:K_.parseProfileList(s)}}();z_(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&(xt.notificationCenter.emitInnerEvent(Wt.PROFILE_UPDATE,{name:Wt.PROFILE_UPDATE,data:[e]}),xt.notificationCenter.emitOuterEvent(jt.PROFILE_UPDATED,{name:jt.PROFILE_UPDATED,data:[e]})))}_dispose(){var e=xt["notificationCenter"];e.unSubscribeInnerEvent(Wt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(Wt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(Wt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=hh.getUserProfile(t);if(!r||!Y_(t))return{isProfileUpdated:!1,profile:null};let o=K_.normalizeProfileFields(s),n=Object.keys(o).some(e=>r[e]!==o[e]);return n?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),o),{lastUpdatedTime:e}),hh.getUserProfileMap().set(t,e),lh.updateConversation("C2C"+t,{userProfile:e}),{isProfileUpdated:n,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=hh.getUserProfileMap().has(e);(Y_(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&&!z_(e.profileItem)),s=Date.now();return t.map(e=>{e=K_.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_reset(){hh.getUserProfileMap().clear()}}let Q_=new Map,X_=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=X_.length;e<t;e++)Q_.set(e,X_[e]);function Z_(e){if(!e)return"";var o=String(e).replace(/[=]+$/,"");let n="";if(o.length%4==1)return"";for(let e,t,s=0,r=0;t=o.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(n+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}let eg=xt.utils["isEmpty"],tg=xt.common["generateProtocolData"];function sg(o){return h(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=tg({servcmd:s,data:{To_Account:o}}),s=r.head.seq+s,r=yield xt.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:Z_(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:eg(t)?e:t,code:s,message:r}})}})}class og{constructor(){this._customStatus=""}init(){var e=xt["notificationCenter"];fh({apiName:"getUserStatus",context:this}),fh({apiName:"setSelfStatus",context:this}),fh({apiName:"subscribeUserStatus",context:this}),fh({apiName:"unsubscribeUserStatus",context:this}),Ps.registerWorkflowStep(ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,ps.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(Wt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(Wt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Wt.DESTROY,this._dispose,this)}setSelfStatus(s){return h(this,void 0,void 0,function*(){let o=xt.ssoLog.createSSOLogData({method:"setSelfStatus"}),e=js(),t=s["customStatus"];try{return yield function(o){return h(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=tg({servcmd:e,data:{CustomStatus:o}}),s=""+t.head.seq+e,r=yield xt.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,o.setLogInfo({message:"customStatus: "+t}).end(),{code:0,data:{userID:e,statusType:V_,customStatus:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new Ss({functionName:"setSelfStatus",code:t,message:s});throw o.setError(r).end(),r}})}getUserStatus(s){return h(this,void 0,void 0,function*(){var e=xt.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=Z_(e);this._customStatus=e}subscribeUserStatus(r){return h(this,void 0,void 0,function*(){try{console.log(k_+" subscribeUserStatus options: ",r);var{userIDList:e=[]}=r,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return h(this,void 0,void 0,function*(){var e=xt["channel"],t="im_open_status.ws_status_subscribe",s=tg({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(k_+" subscribeUserStatus error:",e),e}})}unsubscribeUserStatus(r){return h(this,void 0,void 0,function*(){try{console.log(k_+" unsubscribeUserStatus options: ",r),this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=r,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return h(this,void 0,void 0,function*(){var e=xt["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=tg({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(k_+" 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:Z_(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=Z_(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:js(),statusType:V_,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){xt.notificationCenter.emitOuterEvent(jt.USER_STATUS_UPDATED,{name:jt.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:xt.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!xt.store.get("commercialConfig").get(x_))throw new Ss({functionName:e,code:us.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=xt.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:$_},unsubscribe:{key:"status_unsub_count",default:$_}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){var e=xt.ssoLog.getSSOLogData("getUserStatus"),t=(e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"}),{userID:js(),statusType:V_,customStatus:this._customStatus});return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(o){return h(this,void 0,void 0,function*(){var t=xt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");var s=this._getMaxUserCount("query"),{successUserList:r,failureUserList:e}=(yield sg(this._sliceUserIDList(o,s)))||{};return t.end(),{code:0,data:{successUserList:r,failureUserList:e}}}catch(e){s=e["errorCode"],r=new Ss({functionName:"getUserStatus",code:s});throw t.setError(r).end(),r}})}_isOnlyMeInArray(e){var t=js();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=xt["notificationCenter"];e.unSubscribeInnerEvent(Wt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(Wt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(Wt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let ng={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}}},ig={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class rg{constructor(){this.userProfile=new J_,this.userStatus=new og,this.userProfile.init(),this.userStatus.init(),Ns({auth:ig,params:ng})}}console.log("TencentCloudLiteChat.VERSION:"+We);var ag={create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:o=""}=e;if("number"!=typeof e&&(n=Number(e),Number.isNaN(n)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(e=Number(e),ws.has(e))return ws.get(e);var n=""+(i()+i())+i()+i()+i()+i()+i()+i();function i(){return(65536*(1+Math.random())|0).toString(16).substring(1)}xt.init({sdkAppId:e,instanceId:n,testEnv:t,devMode:s,unlimitedAVChatRoom:r,scene:o,sdkEdition:rh}),Ps.init(),xt.message=new U_,xt.user=new rg,xt.login=new $h,bs.installBuiltInPlugin(ah);t=gh;return ws.set(e,t),t},TSignaling:Ht,EVENT:jt,VERSION:We,TYPES:cs};export{ag as default};